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            // Route the per-`:placement` empty-clusters diagnostic
8243            // through the substrate-primitive
8244            // [`AplicacaoError::placement_without_clusters`] ctor rather
8245            // than the pre-lift three-line open-coded
8246            // `AplicacaoError::PlacementWithoutClusters { estrategia:
8247            // p.estrategia() }` struct-literal — folds the sole in-crate
8248            // wire-up on this variant onto one dispatch matching the
8249            // sibling per-`:placement :clusters` dedup /
8250            // per-`:contratos` self-edge / per-`:upgrade-from :from`
8251            // duplicate substrate-primitive-projection ctors on the
8252            // same `AplicacaoError` / `UpgradeError` envelopes.
8253            return Err(AplicacaoError::placement_without_clusters(p));
8254        }
8255        let mut seen = std::collections::HashSet::new();
8256        for c in p.clusters() {
8257            // Per-entry value-shape gate: the cluster name lands in
8258            // every K8s context / `lareira-fleet-programs` aggregator
8259            // filter / future M4 CR materializer's per-cluster axis
8260            // a validated `:clusters` entry passes through, each
8261            // enforcing the DNS-1123 label rule on admission. Same
8262            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
8263            // on the peer name axis — both axes' validated values
8264            // are guaranteed-accepted by the apiserver without
8265            // re-validation at any downstream renderer or admission
8266            // layer.
8267            validate_placement_cluster(c)?;
8268            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
8269                // Route the per-`:placement :clusters` dedup diagnostic
8270                // through the substrate-primitive
8271                // [`AplicacaoError::placement_cluster_duplicate`] ctor
8272                // rather than the pre-lift three-line open-coded
8273                // `AplicacaoError::PlacementClusterDuplicate { cluster:
8274                // c.clone() }` struct-literal — folds the sole in-crate
8275                // wire-up on this variant onto one dispatch matching the
8276                // sibling per-`:membros :caixa` / per-`:entrada :paths` /
8277                // per-`:politicas <scalar>` single-slot ctor families on
8278                // the same [`AplicacaoError`] envelope.
8279                AplicacaoError::placement_cluster_duplicate(c)
8280            })?;
8281        }
8282        // Route the per-`:placement :affinity` per-hint value-shape
8283        // gate through the typed [`Placement::affinity`] accessor rather
8284        // than the raw `&self.placement.affinity` field access — the
8285        // sole open-coded field-access site on the per-`:placement`
8286        // M3-Adaptive-compression-hint axis the accessor lift now owns.
8287        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
8288        // the accessor's `Option<&str>` return type;
8289        // [`validate_placement_affinity`]'s `&str` parameter accepts
8290        // the narrower borrow without a re-allocation, so the routing
8291        // change is byte-for-byte in the pass arm and remains
8292        // byte-for-byte in every failure diagnostic
8293        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
8294        // String` field is populated inside
8295        // [`validate_placement_affinity`] via the peer `.to_string()`
8296        // path on the same borrowed slice). Peer of the sibling
8297        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
8298        // routing through [`Placement::shard_key`] at the caixa-core
8299        // site above — extends the "read `:placement` optional-scalars
8300        // through the typed accessor" discipline to the second
8301        // `Option<String>`-shape slot on the M3 mesh-slot family.
8302        //
8303        // Per-hint value-shape gate: the `:affinity` value lands
8304        // verbatim in the M3 Adaptive compression overlay
8305        // (caixa-mesh's `placement.affinity` emission) and every
8306        // future M4 placement-engine routing axis keying off the
8307        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
8308        // selector — each enforces the DNS-1123 label rule on
8309        // admission. Same typed-shape trajectory as `:placement
8310        // :clusters` (6c8c00b) on the sibling slot and the four
8311        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
8312        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
8313        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
8314        // on the Aplicacao surface to land on the canonical
8315        // [`crate::render::is_dns_1123_label`] floor.
8316        if let Some(a) = p.affinity() {
8317            validate_placement_affinity(a)?;
8318        }
8319        match p.estrategia() {
8320            // Route the `Sharded`-arm shape-gate cascade through the
8321            // typed [`Placement::shard_key`] accessor rather than the
8322            // raw `&self.placement.shard_key` field access — one of the
8323            // two open-coded field-access sites on the per-`:placement`
8324            // Akka-cluster-sharding-key axis the accessor lift now
8325            // owns. The `Some(k)`-bound `k` narrows from `&String` to
8326            // `&str` under the accessor's `Option<&str>` return type;
8327            // `str::is_empty` and [`validate_placement_shard_key`]'s
8328            // `&str` parameter both accept the narrower borrow without
8329            // a re-allocation.
8330            PlacementStrategy::Sharded => match p.shard_key() {
8331                None => return Err(AplicacaoError::ShardedWithoutKey),
8332                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
8333                // Per-axis value-shape gate on the Akka-cluster-sharding
8334                // `:shard-key` extractor expression. The shape gate runs
8335                // after the more self-locating `ShardedKeyEmpty` arm so
8336                // a `:shard-key ""` surfaces the narrower empty
8337                // diagnostic first; every non-empty `:shard-key` past
8338                // this call is guaranteed to be a printable-ASCII
8339                // single-token reference the future M4 Akka-style
8340                // cluster-sharding reconciler can hash without
8341                // re-validating at the runtime layer. Mirrors the
8342                // payload-axis shape gates on the peer `:contratos`
8343                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
8344                // 63e18a0 / c4213a4) — each lifts the runtime parser's
8345                // intersection-floor to a caixa-build-time gate.
8346                Some(k) => validate_placement_shard_key(k)?,
8347            },
8348            // `:shard-key` is the Akka-cluster-sharding axis
8349            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
8350            // across the cluster pool. `Replicated` (active-active across
8351            // every named cluster) and `SingleNode` (Erlang/OTP
8352            // distributed-app takeover/failover, §II.1) have no hash-keyed
8353            // routing axis to consume the slot; downstream renderers
8354            // (caixa-mesh's `placement.shardKey` overlay at
8355            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
8356            // sharding reconciler) ignore `:shard-key` outside the
8357            // `Sharded` arm by construction. Until this gate landed an
8358            // author who wrote `:placement (:estrategia Replicated
8359            // :shard-key "tenantId")` (an off-by-one strategy typo, a
8360            // copy-paste from a Sharded sibling caixa, the "I think I
8361            // configured sharding" footgun) silently passed validate and
8362            // the typed slot's value vanished at the renderer layer with
8363            // no diagnostic — the canonical "declared-but-inert" footgun
8364            // the empty-:affinity / empty-shard-key / zero-:politicas /
8365            // empty-:contratos-target gates already close on every other
8366            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
8367            // Lifting the rejection to a build-time gate closes the
8368            // Sharded ↔ non-Sharded partition over the typed
8369            // `:placement` slot: every validated `Placement` past this
8370            // call has `shard_key.is_some()` iff `estrategia ==
8371            // Sharded`, structurally — the future Akka reconciler can
8372            // reach for `placement.shard_key` knowing it's `Some` exactly
8373            // when the strategy consumes it, without re-deriving the
8374            // partition from inline strategy probes.
8375            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
8376                // Route the non-`Sharded`-arm declared-but-inert refusal
8377                // through the typed [`Placement::shard_key`] accessor —
8378                // the second of the two open-coded field-access sites the
8379                // accessor lift now owns. The `Some(k)`-bound `k` narrows
8380                // from `&String` to `&str`; the `AplicacaoError::
8381                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
8382                // materializes the owned `String` via `k.to_string()`
8383                // (peer to the sibling per-Membro `String`-carry sites
8384                // 4127bb6 routed through `m.nome().to_string()` /
8385                // `m.versao_requirement().to_string()`), so the whole
8386                // `Sharded` ↔ non-`Sharded` partition on the
8387                // `:shard-key` axis now flows through the same typed
8388                // dispatch as the sibling `Sharded`-arm shape gate.
8389                if let Some(k) = p.shard_key() {
8390                    return Err(AplicacaoError::ShardKeyOnNonSharded {
8391                        estrategia: p.estrategia(),
8392                        shard_key: k.to_string(),
8393                    });
8394                }
8395            }
8396        }
8397        Ok(())
8398    }
8399
8400    /// Reject `:politicas` values that are operationally meaningless.
8401    /// Each axis is optional — omitting it expresses "no policy on this
8402    /// axis". Carrying a *zero* value for a declared axis is the bug
8403    /// this function rejects: zero is either
8404    ///
8405    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
8406    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
8407    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
8408    ///     "every Aplicacao declares :politicas :timeout (no infinite
8409    ///     blocking)", or
8410    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
8411    ///     first call; a 0-rate rate-limit denies every request).
8412    ///
8413    /// Lifting these "0 means the opposite of what you think" idioms to
8414    /// the typed Aplicacao surface as build errors mirrors the §III.3
8415    /// promise that contract drift, capability leaks, and cycles are all
8416    /// build errors — not runtime surprises.
8417    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
8418        // Route the whole per-axis + cross-axis `:politicas` cascade
8419        // through the substrate primitive [`MeshPolicy::validate`],
8420        // which folds all six per-axis brackets (`:timeout`,
8421        // `:retries`, `:circuit-breaker :max-failures`,
8422        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
8423        // window-canonical-form) plus the compound cross-axis fold
8424        // [`MeshPolicy::first_cross_axis_violation`] into one
8425        // `Result<(), AplicacaoError>` return. The whole per-axis-
8426        // brackets + cross-axis-fold cascade collapses to one call, and
8427        // every future [`MeshPolicy`] consumer (the future M4
8428        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8429        // admission webhook, the per-`:contratos`-edge `:politicas`
8430        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
8431        // of which resolves an *effective* per-edge [`MeshPolicy`] and
8432        // must emit *the same* diagnostic on the same input as `feira
8433        // build`) reaches through the same substrate-primitive dispatch
8434        // rather than re-inlining the four-per-axis + one-cross-axis
8435        // cascade in lockstep with this validate gate. Same trajectory
8436        // the peer per-kind compound entry gates
8437        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
8438        // [`crate::render::require_supervisor_view`] (8d8a5c3),
8439        // [`crate::render::require_v0_servico_shape`] (per-Caixa
8440        // layout axis) and the sibling compound cross-axis fold
8441        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
8442        // extended here onto the per-slot compound entry gate that
8443        // folds both per-axis + cross-axis surfaces on the M3
8444        // mesh-slot family.
8445        self.politicas().validate()
8446    }
8447
8448    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8449    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8450    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8451    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8452    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8453    /// block on its subscribers, so they can never close a sync loop.
8454    ///
8455    /// Iterative DFS with three-coloring; the reported cycle is the
8456    /// path of caixa names traversed from the back-edge target around
8457    /// to itself, in declaration order. Adjacency lists and DFS roots
8458    /// are visited in `BTreeMap` key order so the diagnostic is
8459    /// deterministic across runs.
8460    ///
8461    /// Now the cross-edge axis of the per-slot compound gate
8462    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
8463    /// the per-entry cascade rather than at the outer
8464    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
8465    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
8466    /// sync-cycle) reach every consumer through one call. Kept
8467    /// standalone (rather than inlined) so consumers that want only the
8468    /// cross-edge axis (the M4 per-edge policy resolver
8469    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
8470    /// mutates one `:contratos` entry and needs to re-probe *just* the
8471    /// cycle invariant against the post-patch adjacency without
8472    /// re-running the per-entry shape/membership/dedup cascade the
8473    /// per-entry-only [M4 admission] fast path already covered) still
8474    /// have a self-contained entry point on the cycle axis.
8475    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8476        use std::collections::{BTreeMap, BTreeSet};
8477
8478        #[derive(Clone, Copy, PartialEq, Eq)]
8479        enum Mark {
8480            White,
8481            Gray,
8482            Black,
8483        }
8484
8485        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8486        for m in self.membros() {
8487            adj.entry(m.nome()).or_default();
8488        }
8489        for c in self.contratos() {
8490            // target() was already called by validate(); re-running here
8491            // keeps detect_sync_cycles self-contained for callers that
8492            // reuse it (M4 per-edge policy resolver) without revalidating.
8493            //
8494            // The pub-sub-arm check routes through the lifted
8495            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8496            // arm-discriminator predicate rather than a raw `matches!(…,
8497            // WitTarget::PubSub { .. })` on the variant so a future
8498            // rebrand on the axis (an M4 per-edge WIT registry split of
8499            // [`WitTarget::PubSub`] into shape-specific peers, a
8500            // per-consumer rename that the accept-set already carries)
8501            // reaches this call site through the derive rather than a
8502            // scattered per-arm `matches!` rewrite — same
8503            // `IsVariant`-derived-arm-discriminator discipline the
8504            // peer closed-set typed enums ([`crate::CaixaKind`] via
8505            // f5bba80, [`PlacementStrategy`] via 766ec63,
8506            // [`crate::supervisor::RestartStrategy`] +
8507            // [`crate::supervisor::RestartPolicy`],
8508            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8509            // already route through on the substrate's other typed-enum
8510            // arm-discriminator axes.
8511            if c.target()?.is_pubsub() {
8512                continue;
8513            }
8514            adj.entry(c.source()).or_default().insert(c.destination());
8515        }
8516
8517        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8518        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8519
8520        // Stable DFS root order — BTreeMap iteration is sorted by key.
8521        let roots: Vec<&str> = adj.keys().copied().collect();
8522
8523        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8524        for root in roots {
8525            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8526                continue;
8527            }
8528            let root_neighbors: Vec<&str> = adj
8529                .get(root)
8530                .map(|s| s.iter().copied().collect())
8531                .unwrap_or_default();
8532            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8533            color.insert(root, Mark::Gray);
8534
8535            loop {
8536                // Read+advance the top frame in one borrow scope so we
8537                // can later mutate the stack (push/pop) without holding
8538                // a borrow across.
8539                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8540                    let node = top.0;
8541                    if top.2 >= top.1.len() {
8542                        (node, None)
8543                    } else {
8544                        let nxt = top.1[top.2];
8545                        top.2 += 1;
8546                        (node, Some(nxt))
8547                    }
8548                });
8549                let Some((node, nxt_opt)) = step else { break };
8550                let Some(nxt) = nxt_opt else {
8551                    color.insert(node, Mark::Black);
8552                    stack.pop();
8553                    continue;
8554                };
8555                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8556                match nxt_color {
8557                    Mark::Gray => {
8558                        // Reconstruct the cycle from `node` back through
8559                        // the parent chain to `nxt`, then close.
8560                        let mut cycle = Vec::new();
8561                        let mut cur = node;
8562                        cycle.push(cur.to_string());
8563                        while cur != nxt {
8564                            match parent.get(cur).copied() {
8565                                Some(p) => {
8566                                    cur = p;
8567                                    cycle.push(cur.to_string());
8568                                }
8569                                None => break,
8570                            }
8571                        }
8572                        cycle.reverse();
8573                        cycle.push(nxt.to_string());
8574                        return Err(AplicacaoError::ContratoCycle { cycle });
8575                    }
8576                    Mark::White => {
8577                        parent.insert(nxt, node);
8578                        color.insert(nxt, Mark::Gray);
8579                        let nxt_neighbors: Vec<&str> = adj
8580                            .get(nxt)
8581                            .map(|s| s.iter().copied().collect())
8582                            .unwrap_or_default();
8583                        stack.push((nxt, nxt_neighbors, 0));
8584                    }
8585                    Mark::Black => {}
8586                }
8587            }
8588        }
8589        Ok(())
8590    }
8591
8592    /// Substrate-canonical destination-facing TCP port every emitted
8593    /// per-Aplicacao artifact must key `destination`-shaped port axes
8594    /// off. Returns the typed `:entrada :port` scalar when this
8595    /// Aplicacao's `:entrada` block names `destination` under its
8596    /// `:para` axis (the destination Servico *is* the ingress apex, so
8597    /// the substrate honors the author-declared listener port
8598    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8599    /// fallback otherwise (every non-apex destination — the internal
8600    /// mesh Servicos `:contratos` reach across, the future per-edge
8601    /// policy resolver's per-destination probe targets, the
8602    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8603    /// L4 port resolver — reads the same substrate-canonical port floor
8604    /// by construction).
8605    ///
8606    /// Prior to this lift the "if :entrada matches this destination use
8607    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8608    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8609    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8610    /// prior to this lift), with no typed method on the substrate primitive
8611    /// that named the rule. A future per-destination port axis addition
8612    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8613    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8614    /// per-Servico listener ports land, a per-cluster override the operator
8615    /// pins through a future `:placement :default-port` slot — would have
8616    /// to be threaded through every renderer's inline cascade in lockstep
8617    /// or one consumer would silently disagree on which port a given
8618    /// destination Servico's ingress lands at. Lifting the rule to a
8619    /// typed method on the substrate primitive means the M4 CR
8620    /// materializer, the future per-edge policy resolver, and every
8621    /// downstream test-fixture navigator reach for exactly one typed
8622    /// dispatch — the resolver's accept-set moves as a unit on any
8623    /// future axis addition.
8624    ///
8625    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8626    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8627    /// the typed primitive, thin projections at each consumer"
8628    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8629    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8630    /// destination-facing port-resolution axis every per-Aplicacao
8631    /// L4-fallback renderer consumes.
8632    #[must_use]
8633    pub fn port_for_destination(&self, destination: &str) -> u16 {
8634        // Route the per-`:entrada` composite-reference read through
8635        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8636        // the raw `self.entrada.as_ref()` field access — the
8637        // per-destination L4-port fallback resolver's composite-
8638        // projection seed is now the canonical read-side surface
8639        // every per-Aplicacao entrada consumer routes through, peer
8640        // of the sibling `validate` per-`:entrada` shape-and-
8641        // membership gate migration on the same outer-composite
8642        // axis.
8643        // Route the per-`:entrada` apex-destination membership probe
8644        // through the lifted [`Entrada::destination`] accessor rather
8645        // than the raw `e.para == destination` field access — the last
8646        // un-lifted `.para` production-code read site on the per-
8647        // `:entrada` `:para` axis, sibling to the four caixa-core
8648        // consumer sites the peer 15ddd8c converge already routed
8649        // through the accessor (the three
8650        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8651        // membership gate sites: the `validate_entrada_para` DNS-1123
8652        // shape gate, the per-`:membros` membership lookup, and the
8653        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8654        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8655        // `entrada.para`-projection converge at
8656        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8657        // route-name projection site). Prior to this converge the
8658        // `port_for_destination` resolver was the solitary consumer
8659        // bypassing the typed dispatch on the `.para` axis — the two
8660        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8661        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8662        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8663        // reach through the same accessor family compose with this
8664        // resolver at the emit boundary via the apex-identity
8665        // invariant `spec.port_for_destination(entrada.destination())
8666        // == entrada.port` the sibling
8667        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8668        // pin pins across four permutations. A future extension of the
8669        // `:entrada :para` axis to a richer author surface (a per-
8670        // cluster alias overlay the operator pins through a future
8671        // `:placement`-scoped slot, a namespace-qualified rewrite the
8672        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8673        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8674        // §III.2 acknowledges) that lands on the accessor would silently
8675        // disagree between this resolver and the two `caixa-mesh` emit
8676        // sites — an author-declared `:para "cart"` value the accessor
8677        // rewrote to `"cart-v2"` under a future canary arm would leave
8678        // the resolver's membership arm falling through to
8679        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8680        // `.para`) while the peer emit-site consumers landed on the
8681        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8682        // silently disagreed on which destination port a given typed
8683        // `:entrada` resolves to at cluster-apply time. Pinned by the
8684        // drift-detection test
8685        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8686        // below.
8687        self.entrada()
8688            .filter(|e| e.destination() == destination)
8689            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8690    }
8691}
8692
8693/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8694/// entry may name the Aplicacao's own `:nome`.
8695///
8696/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8697/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8698/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8699/// Servicos that compose the app; an Aplicacao is never its own constituent),
8700/// and the lacre pipeline's closure-resolution would otherwise be handed a
8701/// node that is its own parent: a one-node cycle it either rejects far from
8702/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8703/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8704/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8705/// label + lacre closure root), a member whose `:caixa` equals the
8706/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8707/// peer.
8708///
8709/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8710/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8711/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8712/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8713/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8714/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8715/// (the Aplicacao :membros set; the supervision-tree :children list was the
8716/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8717/// every validated Supervisor's children are distinct from its `:nome`,
8718/// every validated Aplicacao's membros are distinct from its `:nome`. The
8719/// transitive consequence is that `:entrada :para` and `:contratos`
8720/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8721/// name the Aplicacao itself, without re-deriving the partition.
8722pub fn validate_no_self_membership(
8723    membros: &[Membro],
8724    parent_nome: &str,
8725) -> Result<(), AplicacaoError> {
8726    for m in membros {
8727        if m.nome() == parent_nome {
8728            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
8729        }
8730    }
8731    Ok(())
8732}
8733
8734#[derive(Debug, Error, PartialEq, Eq)]
8735pub enum AplicacaoError {
8736    #[error("Aplicacao must declare at least one :membros entry")]
8737    NoMembros,
8738    #[error(
8739        ":membros entry has empty :caixa (every member must name a Servico; \
8740         omit the entry instead of carrying an empty name)"
8741    )]
8742    MembroCaixaEmpty,
8743    #[error(
8744        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8745         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8746         name / label value the member name lands in; use a lowercase \
8747         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8748    )]
8749    MembroCaixaInvalid { caixa: String, reason: String },
8750    #[error(
8751        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8752         semver constraint that resolves through the lacre pipeline)"
8753    )]
8754    MembroVersaoEmpty { caixa: String },
8755    #[error(
8756        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8757         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8758         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8759         carries; the lacre pipeline resolves both through the same parser)"
8760    )]
8761    MembroVersaoInvalid {
8762        caixa: String,
8763        versao: String,
8764        reason: String,
8765    },
8766    #[error(
8767        ":membros entry {caixa:?} appears more than once (the graph node set \
8768         is a set, not a multiset; duplicate members produce duplicate \
8769         programs.yaml entries and ambiguous :contratos membership lookups)"
8770    )]
8771    MembroDuplicate { caixa: String },
8772    #[error(
8773        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8774         never its own constituent Servico (the application graph is a DAG rooted \
8775         at the Aplicacao; :membros names the *other* caixas that compose the \
8776         app, not the app itself). Since every :nome is a globally-unique \
8777         substrate identity, a member naming the Aplicacao's own :nome is a \
8778         one-node lacre-closure recursion, not a coincidentally-named peer; \
8779         drop the self-referential :membros entry or rename it to the actual \
8780         constituent caixa."
8781    )]
8782    MembroIsSelfAplicacao { caixa: String },
8783    #[error(
8784        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8785         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8786         member name)"
8787    )]
8788    ContratoCaixaEmpty { slot: &'static str },
8789    #[error(
8790        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8791         :contratos {slot} value names a member of :membros, which is itself a \
8792         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8793         object the member name lands in — Service, Pod, identity-based Cilium \
8794         selector; use a lowercase alphanumeric + hyphen identifier like \
8795         `\"checkout\"` or `\"cart-v2\"`)"
8796    )]
8797    ContratoCaixaInvalid {
8798        slot: &'static str,
8799        caixa: String,
8800        reason: String,
8801    },
8802    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8803    ContratoMemberMissing { caixa: String },
8804    #[error(
8805        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8806         entry is an inter-Servico contract whose :de and :para must name distinct \
8807         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8808         the contract, or point :para at the member it actually calls)"
8809    )]
8810    ContratoSelfLoop { caixa: String, wit: String },
8811    #[error("contrato {de:?} → {para:?} has empty :wit")]
8812    EmptyWit { de: String, para: String },
8813    #[error(
8814        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8815         {reason} (the substrate dispatches `:wit` values on the canonical \
8816         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8817         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8818         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8819         kebab-case identifier per segment)"
8820    )]
8821    ContratoWitInvalid {
8822        de: String,
8823        para: String,
8824        wit: String,
8825        reason: String,
8826    },
8827    #[error(
8828        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8829         :membros; fill the :para field with a member name)"
8830    )]
8831    EntradaParaEmpty,
8832    #[error(
8833        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8834         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8835         label per the K8s apiserver's `metadata.name` rule on every object the \
8836         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8837         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8838         `\"checkout\"` or `\"cart-v2\"`)"
8839    )]
8840    EntradaParaInvalid { para: String, reason: String },
8841    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8842    EntradaMemberMissing { para: String },
8843    #[error(":entrada must declare a non-empty :host")]
8844    EmptyEntradaHost,
8845    #[error(
8846        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8847         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8848         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8849         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8850    )]
8851    EntradaHostInvalid { host: String, reason: String },
8852    #[error(":entrada :port must be in 1..=65535, got 0")]
8853    EntradaPortZero,
8854    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8855    EntradaPathEmpty,
8856    #[error(
8857        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8858    )]
8859    EntradaPathNotAbsolute { path: String },
8860    #[error(
8861        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8862         value: {reason} (the K8s apiserver enforces the same shape on \
8863         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8864         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8865         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8866    )]
8867    EntradaPathInvalid { path: String, reason: String },
8868    #[error(":entrada :paths entry {path:?} appears more than once")]
8869    EntradaPathDuplicate { path: String },
8870    #[error(
8871        ":placement {estrategia} requires at least one :clusters entry \
8872         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8873    )]
8874    PlacementWithoutClusters { estrategia: PlacementStrategy },
8875    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8876    PlacementClusterEmpty,
8877    #[error(
8878        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8879         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8880         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8881         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8882         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8883         identifier like `\"rio\"` or `\"mar-east\"`)"
8884    )]
8885    PlacementClusterInvalid { cluster: String, reason: String },
8886    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8887    PlacementClusterDuplicate { cluster: String },
8888    #[error(
8889        ":placement :affinity must be non-empty when set (omit :affinity to express \
8890         `no placement hint`)"
8891    )]
8892    PlacementAffinityEmpty,
8893    #[error(
8894        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8895         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8896         `placement.affinity` field and in every future M4 placement-engine routing \
8897         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8898         selector — both enforce the DNS-1123 label rule on admission; use a \
8899         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8900         `\"low-latency\"`, or `\"anti-affinity\"`)"
8901    )]
8902    PlacementAffinityInvalid { affinity: String, reason: String },
8903    #[error(":placement Sharded requires :shard-key")]
8904    ShardedWithoutKey,
8905    #[error(
8906        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8907         hashes every entity onto the same shard, defeating sharding entirely)"
8908    )]
8909    ShardedKeyEmpty,
8910    #[error(
8911        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8912         entity-id extractor expression: {reason} (the future M4 Akka-style \
8913         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8914         as a single-token property reference and hashes the extracted entity ID \
8915         to compute shard placement; use a printable-ASCII extractor expression \
8916         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8917         `\"${{tenant}}\"`)"
8918    )]
8919    ShardKeyInvalid { shard_key: String, reason: String },
8920    #[error(
8921        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8922         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8923         convention); :estrategia Replicated runs every cluster active-active and \
8924         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8925         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8926         to :estrategia Sharded if hash-keyed routing is the intent"
8927    )]
8928    ShardKeyOnNonSharded {
8929        estrategia: PlacementStrategy,
8930        shard_key: String,
8931    },
8932    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8933    ContratoMissingTarget {
8934        de: String,
8935        para: String,
8936        wit: String,
8937        expected: &'static str,
8938    },
8939    #[error(
8940        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8941         expected `:{expected}` only"
8942    )]
8943    ContratoWrongTarget {
8944        de: String,
8945        para: String,
8946        wit: String,
8947        expected: &'static str,
8948    },
8949    #[error(
8950        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8951         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8952         that matches no traffic and silently drops every request)"
8953    )]
8954    ContratoEndpointEmpty { de: String, para: String },
8955    #[error(
8956        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8957         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8958         :entrada :paths)"
8959    )]
8960    ContratoEndpointNotAbsolute {
8961        de: String,
8962        para: String,
8963        endpoint: String,
8964    },
8965    #[error(
8966        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8967         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8968         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8969         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8970         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8971         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8972         and whitespace)"
8973    )]
8974    ContratoEndpointInvalid {
8975        de: String,
8976        para: String,
8977        endpoint: String,
8978        reason: String,
8979    },
8980    #[error(
8981        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8982         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8983         pub-sub-shaped)"
8984    )]
8985    ContratoSubjectEmpty { de: String, para: String },
8986    #[error(
8987        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8988         NATS subject: {reason} (the NATS server's subject parser enforces the \
8989         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8990         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8991         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8992         `\"orders.*.completed\"` — a malformed subject silently drops every \
8993         message at runtime far from the source caixa.lisp)"
8994    )]
8995    ContratoSubjectInvalid {
8996        de: String,
8997        para: String,
8998        subject: String,
8999        reason: String,
9000    },
9001    #[error(
9002        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
9003         addresses the bucket root, defeating the per-key isolation the slot exists \
9004         for; omit :slot only if the WIT world is not store-shaped)"
9005    )]
9006    ContratoSlotEmpty { de: String, para: String },
9007    #[error(
9008        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
9009         WASI keyvalue store slot template: {reason} (the substrate enforces \
9010         the printable-ASCII intersection-floor every kv backend admits — \
9011         use a single-token path / template expression like `\"checkout/$orderId\"`, \
9012         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
9013         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
9014         slot either gets rejected on write by strict backends or silently \
9015         corrupts the next read on permissive ones, far from the source caixa.lisp)"
9016    )]
9017    ContratoSlotInvalid {
9018        de: String,
9019        para: String,
9020        slot: String,
9021        reason: String,
9022    },
9023    #[error(
9024        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
9025         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
9026        cycle.join(" → ")
9027    )]
9028    ContratoCycle { cycle: Vec<String> },
9029    #[error(
9030        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
9031         than once (the typed graph edges are a set, not a multiset; duplicate \
9032         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
9033         values that K8s admission rejects far from the source caixa.lisp)"
9034    )]
9035    ContratoDuplicate {
9036        de: String,
9037        para: String,
9038        wit: String,
9039        target: String,
9040    },
9041    #[error(
9042        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
9043         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
9044         express `no per-call deadline on this axis`"
9045    )]
9046    PolicyTimeoutZero,
9047    #[error(
9048        ":politicas :retries must be > 0 when set; omit :retries to express \
9049         `no retries on transient failure`"
9050    )]
9051    PolicyRetriesZero,
9052    #[error(
9053        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
9054         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
9055         retry policy into a thundering-herd amplification vector on transient \
9056         failure (one caller request fans out to `(retries+1)^depth` server-side \
9057         calls across the synchronous-:contratos subgraph), exactly the failure \
9058         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
9059         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
9060         or omit :retries to disable retries entirely"
9061    )]
9062    PolicyRetriesExceedsCap { retries: u32 },
9063    #[error(
9064        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
9065         breaker trips on the first call); omit :circuit-breaker to disable it"
9066    )]
9067    PolicyBreakerZeroFailures,
9068    #[error(
9069        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
9070         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
9071         above this cap turns the typed breaker policy into a no-op: the trip \
9072         threshold is structurally so high that no realistic failures-per-:window \
9073         traffic shape can reach it, so the breaker never trips and every typed-slot \
9074         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
9075         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
9076         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
9077         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
9078         omit :circuit-breaker to disable the breaker entirely"
9079    )]
9080    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
9081    #[error(
9082        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
9083         tracks no failures); omit :circuit-breaker to disable it"
9084    )]
9085    PolicyBreakerZeroWindow,
9086    #[error(
9087        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
9088         request); omit :rate-limit to disable rate limiting"
9089    )]
9090    PolicyRateLimitZero,
9091    #[error(
9092        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
9093         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
9094         rate-limit policy into a no-op limiter: the token-bucket capacity is \
9095         structurally so high that no realistic per-edge traffic shape can drain it, \
9096         so the limiter never trips and every typed-slot consumer (the future \
9097         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9098         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
9099         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
9100         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
9101         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
9102         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
9103         to disable rate limiting entirely"
9104    )]
9105    PolicyRateLimitExceedsCap { rate: u32 },
9106    #[error(
9107        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
9108         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
9109         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
9110         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
9111         three canonical windows)"
9112    )]
9113    PolicyRateLimitWindowNotCanonical { window: Duration },
9114    #[error(
9115        ":politicas :timeout must be an integer number of milliseconds — the canonical \
9116         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
9117         duration codec round-trips losslessly; got {timeout:?} which carries a \
9118         sub-millisecond residue that either truncates to a different `Duration` on \
9119         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
9120         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
9121         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
9122         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
9123    )]
9124    PolicyTimeoutNotCanonical { timeout: Duration },
9125    #[error(
9126        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
9127         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
9128         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
9129         overlays carry a deadline so long no realistic synchronous-:contratos \
9130         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
9131         CSE invariant degenerates to enforcement only at the per-Servico \
9132         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
9133         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
9134         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
9135         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
9136         maxes out at the same `3600s` ceiling) or omit :timeout to express \
9137         `no per-call deadline on this axis` (the synchronous-call deadline then \
9138         relies entirely on the per-Servico `:limits :wall-clock` axis)"
9139    )]
9140    PolicyTimeoutExceedsCap { timeout: Duration },
9141    #[error(
9142        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
9143         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
9144         the shared duration codec round-trips losslessly; got {window:?} which carries a \
9145         sub-millisecond residue that either truncates to a different `Duration` on \
9146         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
9147         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
9148    )]
9149    PolicyBreakerWindowNotCanonical { window: Duration },
9150    #[error(
9151        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
9152         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
9153         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
9154         is structurally so long that transient failures are never forgotten, the breaker \
9155         trips once and stays tripped for the lifetime of the component, and every typed-slot \
9156         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9157         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
9158         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
9159         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
9160         the breaker entirely"
9161    )]
9162    PolicyBreakerWindowExceedsCap { window: Duration },
9163    #[error(
9164        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
9165         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
9166         a single timing-out call can be declared failed, so the dominant failure mode \
9167         the breaker exists to catch is structurally never counted: a call dispatched at \
9168         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
9169         open at dispatch has already rolled, and every typed-slot consumer (the future \
9170         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9171         outlier_detection.interval paired against the per-route request timeout) emits a \
9172         breaker that cannot trip on timeouts however high the call volume. Pin :window \
9173         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
9174         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
9175         same shape), lower :timeout, or omit one of the two axes"
9176    )]
9177    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
9178    #[error(
9179        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
9180         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
9181         :window ({cb_window:?}) — the token-bucket dispatches at most \
9182         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
9183         structurally below the trip threshold, so the breaker cannot trip even under \
9184         100% failure and every typed-slot consumer (the future \
9185         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9186         outlier_detection.consecutive_5xx paired against \
9187         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
9188         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
9189         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
9190    )]
9191    PolicyBreakerCannotTripUnderRateLimit {
9192        rate: u32,
9193        rl_window: Duration,
9194        max_failures: u32,
9195        cb_window: Duration,
9196    },
9197    #[error(
9198        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
9199         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
9200         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
9201         at or before the last retry, so the breaker opens with declared retries still \
9202         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
9203         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
9204         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
9205         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
9206         Envoy / resilience4j production playbooks recommend the breaker's trip \
9207         threshold be observably larger than any single client's retry budget so the \
9208         breaker distinguishes one persistently-failing client from sustained \
9209         multi-client failure), lower :retries, or omit one of the two axes"
9210    )]
9211    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
9212    #[error(
9213        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
9214         ({retries}) plus the initial attempt — one client's declared retry sequence is \
9215         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
9216         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
9217         retry policy is silently truncated by the same rate limiter it feeds through and \
9218         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
9219         overlay, Envoy's retry_policy.num_retries paired against \
9220         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
9221         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
9222         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
9223         bucket capacity be observably larger than any single client's retry budget so the \
9224         limiter distinguishes one client's declared retries from sustained multi-client \
9225         load), lower :retries, or omit one of the two axes"
9226    )]
9227    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
9228}
9229
9230// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
9231// ctor `entrada_host_invalid` is folded onto the sibling
9232// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
9233// `{ <field>: String, reason: String }` variants
9234// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
9235// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
9236// `ShardKeyInvalid`), so every variant on the uniform two-slot
9237// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
9238// reads through one substrate-primitive family rather than one macro
9239// closing six sites plus a hand-written seventh ctor closing the
9240// paired site alone. Prior separate-ctor rationale (17dd504) migrates
9241// verbatim to the macro's outer doc block.
9242
9243// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
9244// wit, expected }` wire-up sites at [`WitContract::target`] onto one
9245// substrate-primitive family per typed variant — the paired sibling on
9246// [`AplicacaoError`] of the four `LayoutError` constructor families
9247// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
9248// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
9249// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
9250// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
9251// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
9252// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
9253// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
9254// HTTP with subject/slot, PubSub with endpoint/slot, Store with
9255// endpoint/subject, Capability with any payload; three
9256// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
9257// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
9258// opened the identical six-line
9259// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
9260// WitTarget::<label> }` struct-literal against the local `edge()` closure
9261// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
9262// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
9263// on the same altitude the peer four `LayoutError` constructor families
9264// each closed on their sibling envelopes.
9265//
9266// The macro below generates one `#[must_use]` inherent constructor per
9267// variant of shape `fn <ctor>(edge: (String, String, String), expected:
9268// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
9269// dispatch per arm: `return
9270// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
9271// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
9272// the pre-lift struct-literal on the same edge fixture. The uniform four-
9273// field construction (`de, para, wit` triple-destructure onto same-named
9274// fields + `expected` verbatim) is spelled once — inside the macro —
9275// rather than at every wire-up site. `#[must_use]` fires a compile warning
9276// at any wire-up that mistakenly discards the constructed error.
9277//
9278// Every future consumer that wants to construct one of these two variants
9279// outside [`WitContract::target`] (a deferred
9280// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9281// admission validator raising wrong-target / missing-target diagnostics
9282// on unrecognized shapes, a future `feira validate --contratos` per-caixa
9283// admission verb, a per-`WitContract` payload-axis pre-emitter probing
9284// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
9285// slots) reaches the variant through one call rather than re-inlining the
9286// six-line struct-literal block in lockstep with the seven in-crate
9287// wire-up sites.
9288macro_rules! contrato_target_ctors {
9289    ($($ctor:ident => $variant:ident),* $(,)?) => {
9290        impl AplicacaoError {
9291            $(
9292                #[doc = concat!(
9293                    "Construct an [`AplicacaoError::",
9294                    stringify!($variant),
9295                    "`] naming the offending edge `(de, para, wit)` triple ",
9296                    "under the given `expected` payload-field-name label. ",
9297                    "Folds the uniform `{ de, para, wit, expected }` four-",
9298                    "slot struct-literal onto one substrate primitive so ",
9299                    "every [`WitContract::target`] wire-up on this variant ",
9300                    "reads through one dispatch rather than the pre-lift ",
9301                    "six-line open-coded block. The `edge` triple threads ",
9302                    "verbatim from [`WitContract::edge_triple`] via the ",
9303                    "local `edge()` closure at the call site."
9304                )]
9305                #[must_use]
9306                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
9307                    let (de, para, wit) = edge;
9308                    Self::$variant { de, para, wit, expected }
9309                }
9310            )*
9311        }
9312    };
9313}
9314
9315contrato_target_ctors! {
9316    contrato_wrong_target => ContratoWrongTarget,
9317    contrato_missing_target => ContratoMissingTarget,
9318}
9319
9320// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
9321// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
9322// onto one substrate-primitive family per typed variant — the paired
9323// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
9324// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
9325// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9326// `ContratoMissingTarget`) and of the two-slot
9327// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
9328// on the sibling per-`:entrada :host` envelope. Every one of the four
9329// wire-up sites — three under [`WitContract::target`] (the empty
9330// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
9331// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
9332// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
9333// value-shape gate fires ahead of) — opened the identical two-line
9334// `let (de, para) = <contract>.edge_pair(); return Err(
9335// AplicacaoError::<Variant> { de, para });` block against the local
9336// [`WitContract::edge_pair`] composite-projection accessor, the exact
9337// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9338// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
9339// and [`AplicacaoError::entrada_host_invalid`] each closed on their
9340// sibling envelopes.
9341//
9342// The macro below generates one `#[must_use]` inherent constructor per
9343// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
9344// collapsing the four sites onto one dispatch per arm:
9345// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
9346// equal to the pre-lift struct-literal on the same edge pair. The
9347// uniform two-field construction (`de, para` pair-destructure onto
9348// same-named fields) is spelled once — inside the macro — rather than
9349// at every wire-up site. `#[must_use]` fires a compile warning at any
9350// wire-up that mistakenly discards the constructed error.
9351//
9352// Every future consumer that wants to construct one of these four
9353// variants outside the two in-crate wire-up sites (a deferred
9354// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9355// admission validator raising empty-payload / empty-`:wit` diagnostics,
9356// a future `feira validate --contratos` per-caixa admission verb, an
9357// M4 typed WIT-registry-driven per-arm pre-emitter probing the
9358// [`WitContract`] payload slot against a canonical per-arm requirement
9359// table) reaches the variant through one call rather than re-inlining
9360// the two-line pair-destructure block in lockstep with the four
9361// in-crate wire-up sites.
9362macro_rules! contrato_empty_pair_ctors {
9363    ($($ctor:ident => $variant:ident),* $(,)?) => {
9364        impl AplicacaoError {
9365            $(
9366                #[doc = concat!(
9367                    "Construct an [`AplicacaoError::",
9368                    stringify!($variant),
9369                    "`] naming the offending edge `(de, para)` pair. ",
9370                    "Folds the uniform `{ de, para }` two-slot struct-",
9371                    "literal onto one substrate primitive so every ",
9372                    "wire-up on this variant reads through one dispatch ",
9373                    "rather than the pre-lift two-line open-coded ",
9374                    "`let (de, para) = <contract>.edge_pair(); return ",
9375                    "Err(<Variant> { de, para });` block. The `edge` ",
9376                    "pair threads verbatim from [`WitContract::edge_pair`] ",
9377                    "at the call site."
9378                )]
9379                #[must_use]
9380                pub fn $ctor(edge: (String, String)) -> Self {
9381                    let (de, para) = edge;
9382                    Self::$variant { de, para }
9383                }
9384            )*
9385        }
9386    };
9387}
9388
9389contrato_empty_pair_ctors! {
9390    empty_wit => EmptyWit,
9391    contrato_endpoint_empty => ContratoEndpointEmpty,
9392    contrato_subject_empty => ContratoSubjectEmpty,
9393    contrato_slot_empty => ContratoSlotEmpty,
9394}
9395
9396// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
9397// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
9398// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
9399// onto one substrate primitive on [`AplicacaoError`] — sibling on the
9400// `{ de: String, para: String, <field>: String }` three-slot envelope of
9401// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
9402// variants on the paired `{ de, para }` two-slot envelope carrying the
9403// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
9404// { de, para });` pair-destructure prelude), the peer four-slot
9405// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
9406// the paired `{ de, para, <field>: String, reason: String }` envelope
9407// carrying the parser-shaped `reason` trailer), and the peer four-slot
9408// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
9409// `{ de, para, wit, expected: &'static str }` envelope carrying the
9410// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
9411// variant is the sole occupant of the three-slot `{ de, para, <field>:
9412// String }` shape on [`AplicacaoError`] (no sibling
9413// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
9414// and `:slot` axes carry no "must start with /" invariant, since the
9415// NATS subject grammar and the WASI keyvalue slot template grammar don't
9416// share the Gateway-API-HTTPPathMatch leading-slash prelude the
9417// `:endpoint` axis does), so a full macro isn't warranted; a single
9418// `#[must_use]` inherent ctor matching the ambient
9419// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
9420// peer per-`:contratos` ctor families each carry closes the last
9421// open-coded three-slot struct-literal on the envelope, matching the
9422// same standalone-ctor discipline the sibling
9423// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
9424// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
9425// [`crate::SupervisorError::child_caixa_invalid`] /
9426// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
9427// `{ caixa: String, [versao: String,] reason: String }` two- and three-
9428// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
9429// one variant on the `{ host: String, reason: String }` two-slot
9430// envelope) apply on their sibling one-off variants.
9431//
9432// The one wire-up site on this variant — [`WitContract::target`]'s
9433// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
9434// six per-`:contratos` value-shape gates inside the same method body,
9435// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
9436// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
9437// `ContratoWitInvalid`) each already reach through one of the three
9438// peer macro-generated ctor families above — opened the same five-line
9439// `let (de, para) = self.edge_pair(); return
9440// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
9441// ep.to_string() });` struct-literal against the local
9442// [`WitContract::edge_pair`] composite-projection accessor and the
9443// caller-side `&str` endpoint — the exact "same block re-inlined at
9444// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9445// altitude the six peer `AplicacaoError` constructor families each
9446// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
9447// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
9448// becomes a caixa-build error, not a Cilium L7 policy-side path-match
9449// silent traffic drop far from the source caixa.lisp) now routes through
9450// one substrate primitive on the envelope.
9451//
9452// The ctor below folds the site onto one dispatch:
9453// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
9454// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
9455// on the same `(edge_pair, endpoint)` pair. The uniform three-field
9456// construction (`de, para` pair-destructure onto same-named fields +
9457// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
9458// body — rather than at the wire-up site. `#[must_use]` fires a compile
9459// warning at any future wire-up that mistakenly discards the constructed
9460// error.
9461//
9462// Every future consumer that wants to construct this variant outside
9463// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
9464// CR materializer's per-`:contratos` admission validator raising the
9465// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
9466// `feira validate --contratos` per-caixa admission verb re-running the
9467// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
9468// probing each declared `:endpoint` against the same shared
9469// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
9470// resolver rejecting a leading-slash-missing `:endpoint` against a
9471// cluster-local Cilium snapshot the M4 CR materializer projects) now
9472// reaches this variant through one call rather than re-inlining the
9473// five-line pair-destructure + struct-literal block in lockstep with
9474// the sole in-crate wire-up site.
9475impl AplicacaoError {
9476    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
9477    /// naming the offending edge `(de, para)` pair and the per-payload
9478    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
9479    /// endpoint.to_string() }` three-slot struct-literal onto one
9480    /// substrate primitive so every wire-up on this variant reads
9481    /// through one dispatch rather than the pre-lift five-line
9482    /// pair-destructure + struct-literal block. The `edge` pair threads
9483    /// verbatim from [`WitContract::edge_pair`] at the call site,
9484    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
9485    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
9486    /// paired two-slot and four-slot per-`:contratos :endpoint`
9487    /// envelopes on the same [`AplicacaoError`] type.
9488    #[must_use]
9489    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
9490        let (de, para) = edge;
9491        Self::ContratoEndpointNotAbsolute {
9492            de,
9493            para,
9494            endpoint: endpoint.to_string(),
9495        }
9496    }
9497
9498    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
9499    /// offending self-edge's owning `caixa` and its `:wit` world
9500    /// reference, projecting both slots through the [`WitContract`]'s
9501    /// own [`WitContract::source`] and [`WitContract::world_ref`]
9502    /// scalar accessors on the substrate primitive.
9503    ///
9504    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
9505    /// contract.world_ref().to_string() }` two-slot struct-literal onto
9506    /// one substrate primitive so every wire-up on this variant reads
9507    /// through one dispatch rather than the pre-lift four-line
9508    /// twin-`.to_string()` struct-literal block. The `contract` borrow
9509    /// threads verbatim from the caller-side `for c in
9510    /// self.contratos()` iteration at the sole in-crate wire-up site
9511    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
9512    /// per-`:contratos` `WitContract`-projection ctor discipline the
9513    /// peer [`AplicacaoError::empty_wit`] /
9514    /// [`AplicacaoError::contrato_endpoint_empty`] /
9515    /// [`AplicacaoError::contrato_subject_empty`] /
9516    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
9517    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
9518    /// envelope.
9519    ///
9520    /// The `caixa` slot is projected through [`WitContract::source`]
9521    /// rather than [`WitContract::destination`] to preserve byte-equal
9522    /// diagnostic ordering with the pre-lift open-coded body — a
9523    /// [`WitContract::is_self_loop`]-gated call site has
9524    /// `source() == destination()` by that predicate's own contract, so
9525    /// the two accessors are exchange-symmetric at this call site, but
9526    /// naming `source` at the ctor definition matches the pre-lift
9527    /// site's field selection and pins the discipline for any future
9528    /// consumer that constructs the variant against a not-yet-gated
9529    /// candidate contract (e.g. an M4
9530    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9531    /// webhook re-checking a per-`(:de, :para)` patched contract, a
9532    /// future `feira validate --contratos` per-caixa verb re-running
9533    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
9534    /// overlay resolver rejecting a self-edge introduced by a
9535    /// cluster-local `:contratos` override the M4 CR materializer
9536    /// projects).
9537    ///
9538    /// Peer of the sibling `WitContract`-projection ctors on the
9539    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
9540    /// same "one typed dispatch on the substrate primitive, projecting
9541    /// through the paired [`WitContract`] accessors, thin projections
9542    /// at each consumer" discipline extended here onto the last unlifted
9543    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
9544    /// inside [`AplicacaoSpec::validate_contratos`].
9545    #[must_use]
9546    pub fn contrato_self_loop(contract: &WitContract) -> Self {
9547        Self::ContratoSelfLoop {
9548            caixa: contract.source().to_string(),
9549            wit: contract.world_ref().to_string(),
9550        }
9551    }
9552
9553    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
9554    /// offending `:membros :caixa` and its `:versao` requirement under
9555    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
9556    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
9557    /// reason.into() }` three-slot struct-literal onto one substrate
9558    /// primitive so every wire-up on this variant reads through one
9559    /// dispatch, matching the peer
9560    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
9561    /// shape verbatim on the sibling `SupervisorError { caixa: String,
9562    /// versao: String, reason: String }` envelope's per-`:children :versao`
9563    /// axis. `reason` accepts both `&str` literals and `format!(…)`
9564    /// outputs through the `impl Into<String>` bound so the sole
9565    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
9566    /// requirement-cascade closure (routing the shared
9567    /// [`crate::render::require_valid_versao_requirement`]-delivered
9568    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
9569    /// transformation on the caller-side `reason` axis. The
9570    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
9571    /// routing the sole wire-up already threads through remains verbatim
9572    /// — the ctor's two `&str` parameters accept the two accessors'
9573    /// returns as-is with no re-allocation at the call site.
9574    #[must_use]
9575    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
9576        Self::MembroVersaoInvalid {
9577            caixa: caixa.to_string(),
9578            versao: versao.to_string(),
9579            reason: reason.into(),
9580        }
9581    }
9582
9583    /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
9584    /// the offending `:placement :clusters` entry.
9585    ///
9586    /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
9587    /// cluster.to_string() }` one-field struct-literal onto one substrate
9588    /// primitive so every wire-up on this variant reads through one
9589    /// dispatch rather than the pre-lift three-line open-coded
9590    /// struct-literal block. The `cluster` slot threads verbatim from the
9591    /// caller-side `for c in p.clusters()` iteration at the sole in-crate
9592    /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
9593    /// per-entry dedup closure passed to
9594    /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
9595    /// bracket accepts the free function pointer as-is.
9596    ///
9597    /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
9598    /// per-`:politicas <scalar>` single-slot ctor families
9599    /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
9600    /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
9601    /// `{ path: String }` at the peer per-gateway envelope,
9602    /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
9603    /// at the peer per-`:politicas` cap-scalar envelope) on the same
9604    /// [`AplicacaoError`] type — extends the "one typed dispatch per
9605    /// substrate primitive on every single-slot per-M3-slot envelope"
9606    /// discipline onto the last unlifted `{ cluster: String }` one-slot
9607    /// per-`:placement :clusters` dedup-envelope inside
9608    /// [`AplicacaoSpec::validate_placement_shape`].
9609    ///
9610    /// Every future consumer that wants to construct this variant outside
9611    /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
9612    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9613    /// webhook re-checking a `:placement :clusters` overlay against a
9614    /// per-tenant cluster-topology snapshot, a future `feira validate
9615    /// --placement` per-caixa admission verb re-running the dedup check
9616    /// on demand, an M4 per-cluster placement resolver rejecting a
9617    /// duplicate cluster-name entry introduced by a fleet-local overlay
9618    /// the M4 CR materializer projects — now reaches this variant through
9619    /// one call rather than re-inlining the three-line struct-literal.
9620    #[must_use]
9621    pub fn placement_cluster_duplicate(cluster: &str) -> Self {
9622        Self::PlacementClusterDuplicate {
9623            cluster: cluster.to_string(),
9624        }
9625    }
9626
9627    /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
9628    /// the offending `:placement :estrategia` scalar the empty `:clusters`
9629    /// list was declared against, projecting through the paired
9630    /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
9631    /// primitive.
9632    ///
9633    /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
9634    /// placement.estrategia() }` one-field struct-literal onto one
9635    /// substrate primitive so every wire-up on this variant reads through
9636    /// one dispatch rather than the pre-lift three-line open-coded
9637    /// `AplicacaoError::PlacementWithoutClusters { estrategia:
9638    /// p.estrategia() }` block inside
9639    /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
9640    /// projection posture as the sibling
9641    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
9642    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
9643    /// per-`:contratos` self-edge envelope) and the peer
9644    /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
9645    /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
9646    /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
9647    /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
9648    /// per-`:placement` empty-clusters envelope inside
9649    /// [`AplicacaoSpec::validate_placement`].
9650    ///
9651    /// `#[must_use]` and `const fn` alike: the ctor threads the paired
9652    /// [`Placement::estrategia`] `Copy`-scalar return through one
9653    /// zero-runtime-work construction — no allocation, no owned-string
9654    /// materialization — so the pre-lift `Copy`-pass-through property the
9655    /// open-coded `p.estrategia()` field expression carried survives
9656    /// verbatim through the substrate primitive. The sibling
9657    /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
9658    /// carries the paired `.to_string()`-owned-String allocation on the
9659    /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
9660    /// preserves the zero-alloc posture at the substrate-primitive
9661    /// dispatch, matching the peer
9662    /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
9663    /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
9664    /// per-`:politicas` cap-scalar envelopes.
9665    ///
9666    /// Every future consumer that wants to construct this variant outside
9667    /// [`AplicacaoSpec::validate_placement`] — a deferred
9668    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9669    /// webhook re-checking a `:placement :clusters` overlay against a
9670    /// per-tenant cluster-topology snapshot when the overlay resolves to
9671    /// an empty list, a future `feira validate --placement` per-caixa
9672    /// admission verb re-running the empty-clusters check on demand, an
9673    /// M4 per-cluster placement resolver rejecting an empty cluster pool
9674    /// after a fleet-local overlay strips every declared cluster — now
9675    /// reaches this variant through one call rather than re-inlining the
9676    /// three-line struct-literal in lockstep with the one in-crate
9677    /// wire-up site.
9678    #[must_use]
9679    pub const fn placement_without_clusters(placement: &Placement) -> Self {
9680        Self::PlacementWithoutClusters {
9681            estrategia: placement.estrategia(),
9682        }
9683    }
9684}
9685
9686// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
9687// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
9688// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
9689// substrate-primitive family per typed variant — the paired
9690// `{ <field>: String, reason: String }` two-slot sibling on
9691// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
9692// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9693// `ContratoMissingTarget`) and the peer two-slot
9694// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
9695// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
9696// on the sibling per-`:contratos` envelopes, plus the peer four-family
9697// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
9698// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
9699// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
9700// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
9701// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
9702// sibling layout-side envelope.
9703//
9704// Every one of the seven wire-up sites — six under the per-axis
9705// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
9706// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
9707// on `EntradaParaInvalid`, `validate_placement_cluster` on
9708// `PlacementClusterInvalid`, `validate_placement_affinity` on
9709// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
9710// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
9711// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
9712// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
9713// sites at [`validate_entrada_host`] (17dd504 already folded onto the
9714// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
9715// the macro-generated ctor of the same name), opened the identical
9716// four-line `AplicacaoError::<Variant>Invalid
9717// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
9718// the local `<field>: &str` argument — the exact "same block re-inlined
9719// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
9720// same altitude the peer three `AplicacaoError` constructor families
9721// and the four peer `LayoutError` constructor families each closed on
9722// their sibling envelopes.
9723//
9724// The macro below generates one `#[must_use]` inherent constructor per
9725// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
9726// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
9727// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
9728// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
9729// pre-lift struct-literal on the same `(<field>, reason)` pair. The
9730// uniform two-field construction (`<field>: <val>.to_string()`,
9731// `reason: reason.into()`) is spelled once — inside the macro — rather
9732// than at every wire-up site. The `reason: impl Into<String>` bound
9733// accepts both `&str` literals (with or without a trailing
9734// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
9735// wire-up site changes its per-arm diagnostic shape at the lift.
9736// `#[must_use]` fires a compile warning at any wire-up that mistakenly
9737// discards the constructed error rather than routing it through
9738// `return Err(…)` / `.map_err(…)` / a closure return.
9739//
9740// Every future consumer that wants to construct one of these seven
9741// variants outside the current in-crate wire-up sites (the deferred
9742// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
9743// admission validators, a future `feira validate --<axis>` per-caixa
9744// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
9745// on `:entrada :host`, an M4 typed placement-engine per-cluster /
9746// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
9747// per-path pre-emitter) reaches the variant through one call rather
9748// than re-inlining the four-line struct-literal block in lockstep with
9749// the current in-crate wire-up sites.
9750macro_rules! aplicacao_field_reason_ctors {
9751    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
9752        impl AplicacaoError {
9753            $(
9754                #[doc = concat!(
9755                    "Construct an [`AplicacaoError::",
9756                    stringify!($variant),
9757                    "`] naming the offending `",
9758                    stringify!($field),
9759                    "` under the given `reason`. Folds the uniform ",
9760                    "`{ ",
9761                    stringify!($field),
9762                    ": ",
9763                    stringify!($field),
9764                    ".to_string(), reason: reason.into() }` two-slot ",
9765                    "construction onto one substrate primitive so every ",
9766                    "wire-up on this variant reads through one dispatch ",
9767                    "rather than the pre-lift four-line struct-literal ",
9768                    "block. `reason` accepts both `&str` literals and ",
9769                    "`format!(…)` outputs through the `impl Into<String>` ",
9770                    "bound."
9771                )]
9772                #[must_use]
9773                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
9774                    Self::$variant {
9775                        $field: $field.to_string(),
9776                        reason: reason.into(),
9777                    }
9778                }
9779            )*
9780        }
9781    };
9782}
9783
9784aplicacao_field_reason_ctors! {
9785    membro_caixa_invalid => MembroCaixaInvalid { caixa },
9786    entrada_para_invalid => EntradaParaInvalid { para },
9787    entrada_host_invalid => EntradaHostInvalid { host },
9788    entrada_path_invalid => EntradaPathInvalid { path },
9789    placement_cluster_invalid => PlacementClusterInvalid { cluster },
9790    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
9791    shard_key_invalid => ShardKeyInvalid { shard_key },
9792}
9793
9794// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
9795// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
9796// [`WitContract::target`] onto one substrate-primitive family per typed
9797// variant — the paired `{ de: String, para: String, <field>: String,
9798// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
9799// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
9800// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
9801// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
9802// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
9803// `ContratoSlotEmpty`), and the peer two-slot
9804// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
9805// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
9806// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
9807// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
9808// sibling `AplicacaoError` envelopes, plus the peer four-family
9809// `LayoutError` ctor set on the sibling layout-side envelope.
9810//
9811// Every one of the four wire-up sites — four per-`:contratos` value-
9812// shape gates inside [`WitContract::target`] (the world-ref prefix
9813// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
9814// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
9815// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
9816// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
9817// failure on `:slot`) — opened the identical five-line
9818// `let (de, para) = self.edge_pair();
9819// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
9820// <field>: <val>.to_string(), reason });` block against the local
9821// [`WitContract::edge_pair`] composite-projection accessor and the
9822// per-arm `<val>: &str` argument — the exact "same block re-inlined at
9823// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9824// altitude the peer three `AplicacaoError` constructor families and the
9825// four peer `LayoutError` constructor families each closed on their
9826// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
9827// macro closes the last unlifted `{ de, para, <field>: String, reason:
9828// String }` four-slot envelope inside `impl WitContract`, so every
9829// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
9830// reads through this one substrate primitive.
9831//
9832// The macro below generates one `#[must_use]` inherent constructor per
9833// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
9834// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
9835// sites onto one dispatch per arm:
9836// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
9837// byte-equal to the pre-lift struct-literal on the same
9838// `(edge_pair, <val>, reason)` triple. The uniform four-field
9839// construction (`de, para` pair-destructure onto same-named fields +
9840// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
9841// once — inside the macro — rather than at every wire-up site. The
9842// `reason: impl Into<String>` bound accepts both `&str` literals and
9843// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
9844// diagnostic shape at the lift, matching the peer
9845// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
9846// envelope. `#[must_use]` fires a compile warning at any wire-up that
9847// mistakenly discards the constructed error.
9848//
9849// Every future consumer that wants to construct one of these four
9850// variants outside [`WitContract::target`] (a deferred
9851// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9852// admission validator raising per-payload value-shape diagnostics on
9853// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
9854// future `feira validate --contratos` per-caixa admission verb, an M4
9855// typed WIT-registry-driven per-arm pre-emitter probing each declared
9856// `:endpoint` / `:subject` / `:slot` payload against a canonical
9857// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
9858// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
9859// pre-emitter probing each `:endpoint` against the same shared
9860// HTTPPathMatch grammar) reaches the variant through one call rather
9861// than re-inlining the five-line pair-destructure + struct-literal
9862// block in lockstep with the four in-crate wire-up sites.
9863macro_rules! contrato_pair_value_reason_ctors {
9864    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
9865        impl AplicacaoError {
9866            $(
9867                #[doc = concat!(
9868                    "Construct an [`AplicacaoError::",
9869                    stringify!($variant),
9870                    "`] naming the offending edge `(de, para)` pair, the ",
9871                    "per-payload `",
9872                    stringify!($field),
9873                    "` value, and the parser-shaped `reason`. Folds the ",
9874                    "uniform `{ de, para, ",
9875                    stringify!($field),
9876                    ": ",
9877                    stringify!($field),
9878                    ".to_string(), reason: reason.into() }` four-slot ",
9879                    "construction onto one substrate primitive so every ",
9880                    "wire-up on this variant reads through one dispatch ",
9881                    "rather than the pre-lift five-line pair-destructure ",
9882                    "+ struct-literal block. The `edge` pair threads ",
9883                    "verbatim from [`WitContract::edge_pair`] at the ",
9884                    "call site; `reason` accepts both `&str` literals ",
9885                    "and `format!(…)` outputs through the `impl ",
9886                    "Into<String>` bound."
9887                )]
9888                #[must_use]
9889                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
9890                    let (de, para) = edge;
9891                    Self::$variant {
9892                        de,
9893                        para,
9894                        $field: $field.to_string(),
9895                        reason: reason.into(),
9896                    }
9897                }
9898            )*
9899        }
9900    };
9901}
9902
9903contrato_pair_value_reason_ctors! {
9904    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
9905    contrato_subject_invalid => ContratoSubjectInvalid { subject },
9906    contrato_slot_invalid => ContratoSlotInvalid { slot },
9907    contrato_wit_invalid => ContratoWitInvalid { wit },
9908}
9909
9910// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
9911// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
9912// caixa-only struct-variant wire-up sites at
9913// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
9914// `:contratos :para` arms of `ContratoMemberMissing`),
9915// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
9916// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
9917// and [`validate_no_self_membership`] (one site, the parent-`:nome`
9918// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
9919// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
9920// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
9921// three variants on `{ caixa: String }` at
9922// [`crate::SupervisorSpec::validate_children`] and
9923// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
9924// `SupervisorError` envelope, extending the same "one substrate primitive per
9925// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
9926// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
9927// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
9928// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
9929// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
9930// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
9931// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
9932// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
9933// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
9934// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
9935// variants on `{ nome, caminho }`), and
9936// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
9937// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
9938// peer three `AplicacaoError` sub-family folds already lifted here
9939// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
9940// [`aplicacao_field_reason_ctors!`] 981060b,
9941// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
9942// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
9943// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
9944// [`crate::LayoutError::missing_entry`] 1b09f9d,
9945// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
9946// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
9947//
9948// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
9949// at the per-`:contratos :de`/`:para` unknown-member arms, one on
9950// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
9951// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
9952// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
9953// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
9954// three-line struct-literal against a caller-side `&str` — the exact "same
9955// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
9956// bug, on the same altitude the peer `SupervisorError` /
9957// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
9958// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
9959// their sibling envelopes. The four variants share one `{ caixa: String }`
9960// shape, so the fold routes each wire-up site through one dispatch per typed
9961// variant.
9962//
9963// The macro below generates one `#[must_use]` inherent constructor per
9964// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
9965// wire-up site collapses onto one dispatch:
9966// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
9967// on the same `&str` fixture. The uniform one-field construction
9968// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
9969// than at every wire-up site. Every constructor is `#[must_use]` so a caller
9970// who mistakenly discards the constructed error trips a compile warning at
9971// the wire-up site.
9972//
9973// Every future consumer that wants to construct one of these four variants
9974// outside the current in-crate wire-up sites — a deferred
9975// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
9976// re-checking one added/renamed `:membros` entry against the sibling
9977// `:contratos` graph, a future `feira validate --membros` per-caixa admission
9978// verb re-checking each declared `:membros` entry's `:caixa` name against the
9979// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
9980// duplicate / self-referencing / unknown-membered `:contratos` entry against
9981// a cluster-local snapshot the M4 CR materializer projects — now reaches each
9982// variant through one call rather than re-inlining the three-line
9983// struct-literal in lockstep with the five in-crate wire-up sites.
9984macro_rules! aplicacao_caixa_only_ctors {
9985    ($($ctor:ident => $variant:ident),* $(,)?) => {
9986        impl AplicacaoError {
9987            $(
9988                #[doc = concat!(
9989                    "Construct an [`AplicacaoError::",
9990                    stringify!($variant),
9991                    "`] naming the offending `:membros :caixa` (or ",
9992                    "parent `:nome`, on the self-membership arm; or ",
9993                    "`:contratos :de`/`:para`, on the unknown-member ",
9994                    "arm). Folds the uniform `Self::",
9995                    stringify!($variant),
9996                    " { caixa: caixa.to_string() }` one-field ",
9997                    "struct-literal onto one substrate primitive so ",
9998                    "every wire-up on this variant reads through one ",
9999                    "dispatch rather than the pre-lift three-line ",
10000                    "open-coded struct-literal block."
10001                )]
10002                #[must_use]
10003                pub fn $ctor(caixa: &str) -> Self {
10004                    Self::$variant { caixa: caixa.to_string() }
10005                }
10006            )*
10007        }
10008    };
10009}
10010
10011aplicacao_caixa_only_ctors! {
10012    contrato_member_missing => ContratoMemberMissing,
10013    membro_versao_empty => MembroVersaoEmpty,
10014    membro_duplicate => MembroDuplicate,
10015    membro_is_self_aplicacao => MembroIsSelfAplicacao,
10016}
10017
10018// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
10019// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
10020// sites onto one substrate-primitive family per typed variant — the direct
10021// per-`:entrada :paths` value-shape sibling of the peer
10022// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
10023// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
10024// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
10025// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
10026// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
10027// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
10028// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
10029// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
10030// `:deps` envelope — every single-`String`-slot error family in caixa-core
10031// now reaches through one substrate primitive per typed variant.
10032//
10033// The three wire-up sites — one under [`validate_entrada_path`]'s
10034// leading-slash grammar arm (`EntradaPathNotAbsolute` against
10035// `path: &str`), one under the per-`:entrada :paths` loop's identical
10036// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
10037// and one under the per-`:entrada :paths` loop's dedup arm
10038// (`EntradaPathDuplicate` against the same `&String` via
10039// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
10040// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
10041// three-line struct-literal against a caller-side `&str` / `&String`, the
10042// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
10043// names as a bug. Every one of the compile-time guarantees in
10044// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
10045// start with `/` becomes a caixa-build error, not a Gateway API webhook
10046// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
10047// becomes a caixa-build error, not a silent last-writer-wins render) now
10048// routes through one dispatch per typed variant at every emit site.
10049//
10050// The macro below generates one `#[must_use]` inherent constructor per
10051// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
10052// every wire-up site onto one dispatch:
10053// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
10054// on the same `&str` fixture) or the `&String` sites through
10055// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
10056// construction (`path: path.to_string()`) is spelled once — inside the
10057// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
10058// a caller who mistakenly discards the constructed error trips a compile
10059// warning at the wire-up site.
10060//
10061// Every future consumer that wants to construct one of these two variants
10062// outside the current in-crate wire-up sites — a deferred
10063// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
10064// per-`:entrada :paths` re-check against a cluster-local Gateway API
10065// snapshot, a future `feira validate --entrada` per-caixa admission verb
10066// re-checking each declared `:paths` entry against the same axes, a
10067// per-tenant per-`Aplicacao` overlay resolver rejecting a
10068// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
10069// snapshot the M4 CR materializer projects — now reaches each variant
10070// through one call rather than re-inlining the three-line struct-literal in
10071// lockstep with the three in-crate wire-up sites.
10072macro_rules! aplicacao_path_only_ctors {
10073    ($($ctor:ident => $variant:ident),* $(,)?) => {
10074        impl AplicacaoError {
10075            $(
10076                #[doc = concat!(
10077                    "Construct an [`AplicacaoError::",
10078                    stringify!($variant),
10079                    "`] naming the offending `:entrada :paths` entry. ",
10080                    "Folds the uniform `Self::",
10081                    stringify!($variant),
10082                    " { path: path.to_string() }` one-field ",
10083                    "struct-literal onto one substrate primitive so ",
10084                    "every wire-up on this variant reads through one ",
10085                    "dispatch rather than the pre-lift three-line ",
10086                    "open-coded struct-literal block."
10087                )]
10088                #[must_use]
10089                pub fn $ctor(path: &str) -> Self {
10090                    Self::$variant { path: path.to_string() }
10091                }
10092            )*
10093        }
10094    };
10095}
10096
10097aplicacao_path_only_ctors! {
10098    entrada_path_not_absolute => EntradaPathNotAbsolute,
10099    entrada_path_duplicate => EntradaPathDuplicate,
10100}
10101
10102// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
10103// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
10104// substrate-primitive family per typed variant — the per-`:politicas` copy-
10105// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
10106// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
10107// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
10108// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
10109// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
10110// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
10111// the `String`-slot axis, and the peer per-`:politicas` cross-axis
10112// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
10113// carries at line 3064 on the same M3 mesh envelope.
10114//
10115// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
10116// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
10117// { <slot> }` one-line struct-literal closure against the caller-side
10118// `<slot>: <ty>` argument that the shared
10119// [`crate::render::require_positive_bounded_u32`] /
10120// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
10121// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
10122// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
10123// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
10124// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
10125// on line 3211) — the exact "same one-line struct-literal re-inlined at every
10126// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
10127// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
10128// been folded onto a substrate primitive.
10129//
10130// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
10131// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
10132// collapsing every wire-up onto either one direct dispatch
10133// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
10134// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
10135// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
10136// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
10137// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
10138// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
10139// constructor with matching arity and signature. The `const fn` qualifier
10140// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
10141// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
10142// per-variant `$field:ident` axis re-uses the enum's canonical field name so
10143// the generated ctor's parameter name matches every wire-up's local binding
10144// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
10145// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
10146// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
10147// warning at any wire-up that mistakenly discards the constructed error, on
10148// the same footing as every sibling `AplicacaoError` / `DepError` /
10149// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
10150// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
10151// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
10152// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
10153//
10154// Every future consumer that wants to construct one of these eight variants
10155// outside [`MeshPolicy::validate`] — a deferred
10156// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
10157// checking each `:politicas` axis against a cluster-local `:politicas` cap
10158// overlay, a future per-`:contratos`-edge `:politicas` override the
10159// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
10160// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
10161// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
10162// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
10163// a future `feira validate --politicas` per-caixa admission verb re-checking
10164// each declared per-axis value against the same bounds — now reaches each
10165// variant through one call rather than re-inlining the one-line struct-
10166// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
10167// which is exactly the invariant every prior ctor-macro lift already closed
10168// on its sibling envelope. Closes the last remaining per-`:politicas`
10169// per-axis `AplicacaoError` variant family that had not yet been folded onto
10170// a substrate primitive; the compound cross-axis variants
10171// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
10172// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
10173// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
10174macro_rules! aplicacao_policy_scalar_ctors {
10175    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
10176        impl AplicacaoError {
10177            $(
10178                #[doc = concat!(
10179                    "Construct an [`AplicacaoError::",
10180                    stringify!($variant),
10181                    "`] naming the offending per-`:politicas` `",
10182                    stringify!($field),
10183                    "` scalar. Folds the uniform `Self::",
10184                    stringify!($variant),
10185                    " { ",
10186                    stringify!($field),
10187                    " }` one-field `Copy`-pass-through struct-literal onto ",
10188                    "one substrate primitive so every per-axis wire-up on ",
10189                    "this variant reads through one dispatch — as a direct ",
10190                    "call (`AplicacaoError::",
10191                    stringify!($ctor),
10192                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
10193                    "the same `Copy`-`",
10194                    stringify!($ty),
10195                    "` fixture) or as a bare function pointer in the ",
10196                    "`impl FnOnce(",
10197                    stringify!($ty),
10198                    ") -> AplicacaoError` bracket-closure slot every ",
10199                    "`crate::render::require_positive_bounded_*` / ",
10200                    "`crate::render::require_positive_canonical_bounded_*` ",
10201                    "gate carries — rather than the pre-lift open-coded ",
10202                    "one-line closure over the same one-field struct-",
10203                    "literal. `const fn` preserves the `Copy`-pass-through's ",
10204                    "zero-runtime-work property verbatim."
10205                )]
10206                #[must_use]
10207                pub const fn $ctor($field: $ty) -> Self {
10208                    Self::$variant { $field }
10209                }
10210            )*
10211        }
10212    };
10213}
10214
10215aplicacao_policy_scalar_ctors! {
10216    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
10217    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
10218    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
10219    policy_breaker_max_failures_exceeds_cap =>
10220        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
10221    policy_breaker_window_not_canonical =>
10222        PolicyBreakerWindowNotCanonical { window: Duration },
10223    policy_breaker_window_exceeds_cap =>
10224        PolicyBreakerWindowExceedsCap { window: Duration },
10225    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
10226    policy_rate_limit_window_not_canonical =>
10227        PolicyRateLimitWindowNotCanonical { window: Duration },
10228}
10229
10230#[cfg(test)]
10231mod tests {
10232    use super::*;
10233
10234    fn membro(name: &str, ver: &str) -> Membro {
10235        Membro {
10236            caixa: name.into(),
10237            versao: ver.into(),
10238        }
10239    }
10240
10241    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
10242        WitContract {
10243            de: de.into(),
10244            para: para.into(),
10245            wit: "wasi:http/proxy".into(),
10246            endpoint: Some(ep.into()),
10247            subject: None,
10248            slot: None,
10249        }
10250    }
10251
10252    fn three_member_spec() -> AplicacaoSpec {
10253        AplicacaoSpec {
10254            membros: vec![
10255                membro("catalog", "^0.1"),
10256                membro("cart", "^0.1"),
10257                membro("payment", "^0.2"),
10258            ],
10259            contratos: vec![
10260                contract_http("cart", "catalog", "/products/:id"),
10261                contract_http("cart", "payment", "/charge"),
10262            ],
10263            politicas: MeshPolicy {
10264                timeout: Some(Duration::from_secs(30)),
10265                retries: Some(3),
10266                mtls_required: Some(true),
10267                ..Default::default()
10268            },
10269            placement: Placement {
10270                estrategia: PlacementStrategy::Replicated,
10271                clusters: vec!["rio".into(), "mar".into()],
10272                affinity: Some("data-locality".into()),
10273                shard_key: None,
10274            },
10275            entrada: Some(Entrada {
10276                host: "checkout.quero.cloud".into(),
10277                para: "cart".into(),
10278                paths: vec!["/api/cart".into(), "/api/products".into()],
10279                port: 8080,
10280            }),
10281        }
10282    }
10283
10284    #[test]
10285    fn happy_path_validates() {
10286        three_member_spec().validate().unwrap();
10287    }
10288
10289    #[test]
10290    fn rejects_empty_membros() {
10291        let mut s = three_member_spec();
10292        s.membros = vec![];
10293        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
10294    }
10295
10296    #[test]
10297    fn rejects_empty_membro_caixa() {
10298        // A `:caixa ""` entry has no name to render into programs.yaml
10299        // and no caixa.lisp to resolve at lacre time.
10300        let mut s = three_member_spec();
10301        s.membros[1].caixa = String::new();
10302        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
10303    }
10304
10305    #[test]
10306    fn rejects_empty_membro_versao() {
10307        // A `:versao ""` entry can't pin a semver constraint, so the
10308        // lacre pipeline fails far from the source.
10309        let mut s = three_member_spec();
10310        s.membros[2].versao = String::new();
10311        let err = s.validate().unwrap_err();
10312        assert!(
10313            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
10314            "got {err:?}"
10315        );
10316    }
10317
10318    #[test]
10319    fn rejects_duplicate_membro_caixa() {
10320        // Two `:membros` entries with the same `:caixa` collapse to one
10321        // node in the membership HashSet, which masks `:contratos`
10322        // membership errors and produces duplicate programs.yaml entries.
10323        let mut s = three_member_spec();
10324        s.membros.push(membro("cart", "^0.2"));
10325        let err = s.validate().unwrap_err();
10326        assert!(
10327            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
10328            "got {err:?}"
10329        );
10330    }
10331
10332    #[test]
10333    fn rejects_invalid_membro_versao_requirement() {
10334        // The fail-before-pass-after pin: a non-empty but malformed
10335        // semver requirement (`"^bad-version"`) silently passed
10336        // `validate()` on every pre-gate codebase because the prior
10337        // shape only refused the empty string. The parse failure
10338        // surfaced far downstream at lacre-resolve time with a
10339        // `semver::Error` that didn't name which `:membros` entry
10340        // carried the typo. The new gate moves the check to caixa-build
10341        // time at the source caixa.lisp.
10342        let mut s = three_member_spec();
10343        s.membros[2].versao = "^bad-version".into();
10344        let err = s.validate().unwrap_err();
10345        assert!(
10346            matches!(
10347                err,
10348                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10349                    if caixa == "payment" && versao == "^bad-version"
10350            ),
10351            "got {err:?}"
10352        );
10353    }
10354
10355    #[test]
10356    fn rejects_membro_versao_with_double_caret_typo() {
10357        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
10358        // Cargo-shaped requirement on first glance but fails the parser
10359        // because semver doesn't accept stacked operators. Pin this
10360        // adjacent-shape footgun explicitly so a future relaxation that
10361        // accepts "looks-canonical-but-isn't" forms surfaces here.
10362        let mut s = three_member_spec();
10363        s.membros[0].versao = "^^0.1".into();
10364        let err = s.validate().unwrap_err();
10365        assert!(
10366            matches!(
10367                err,
10368                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10369                    if caixa == "catalog" && versao == "^^0.1"
10370            ),
10371            "got {err:?}"
10372        );
10373    }
10374
10375    #[test]
10376    fn rejects_membro_versao_with_v_prefixed_tag() {
10377        // `"v0.1"` is the canonical "git-tag-shape leaking into the
10378        // semver requirement slot" typo — an author copies the
10379        // publish-side git-tag string verbatim into `:versao`, but
10380        // Cargo's semver parser rejects the leading `v` (only digits +
10381        // canonical operators are valid in the major-version
10382        // position). The gate's diagnostic names which member entry
10383        // carried the v-prefix so the fix is one edit, not a grep
10384        // through every member's `:versao`. (Note: bare `x`-glob
10385        // shorthands like `^0.1.x` are *accepted* by the semver crate
10386        // as an `*` wildcard on the patch axis — they're a Cargo-side
10387        // valid shape, not a typo, so the gate intentionally lets them
10388        // through.)
10389        let mut s = three_member_spec();
10390        s.membros[1].versao = "v0.1".into();
10391        let err = s.validate().unwrap_err();
10392        assert!(
10393            matches!(
10394                err,
10395                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10396                    if caixa == "cart" && versao == "v0.1"
10397            ),
10398            "got {err:?}"
10399        );
10400    }
10401
10402    #[test]
10403    fn accepts_canonical_membro_versao_forms() {
10404        // The four Cargo-shaped requirement forms `:deps :versao`
10405        // already accepts via `crate::parse_requirement` must pass the
10406        // membros gate without re-validating at the resolver layer.
10407        // Pin every leg so a future tightening of the canonical set
10408        // surfaces here as a test failure.
10409        for form in [
10410            "^0.1",      // caret — minor-range pin (the most common shape)
10411            "~0.1.2",    // tilde — patch-range pin
10412            "0.1.0",     // exact — single-version pin
10413            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
10414            ">=0.1, <2", // multi-range — comma-separated comparators
10415        ] {
10416            let mut s = three_member_spec();
10417            for m in &mut s.membros {
10418                m.versao = form.into();
10419            }
10420            s.validate()
10421                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
10422        }
10423    }
10424
10425    #[test]
10426    fn membro_versao_empty_takes_precedence_over_invalid() {
10427        // Order pin: the existing `MembroVersaoEmpty` diagnostic
10428        // (which doesn't try to parse) fires before the new
10429        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
10430        // `:versao` keeps its narrower error message — `parse_requirement`
10431        // would also reject `""`, but the empty-string arm is the more
10432        // self-locating diagnostic for the author.
10433        let mut s = three_member_spec();
10434        s.membros[1].versao = String::new();
10435        let err = s.validate().unwrap_err();
10436        assert!(
10437            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
10438            "got {err:?}"
10439        );
10440    }
10441
10442    #[test]
10443    fn membro_versao_invalid_fires_before_duplicate_check() {
10444        // Order pin: a malformed requirement on a non-duplicate entry
10445        // surfaces *its own* diagnostic (which names the offending
10446        // `:versao` string), even when a later entry would otherwise
10447        // collapse onto an earlier name. The per-entry shape gate runs
10448        // inline before the duplicate-key insert, parallel to
10449        // `membros_validation_runs_before_contratos_membership_check`
10450        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
10451        let mut s = three_member_spec();
10452        s.membros[0].versao = "^bad".into();
10453        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
10454        let err = s.validate().unwrap_err();
10455        assert!(
10456            matches!(
10457                err,
10458                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
10459            ),
10460            "got {err:?}"
10461        );
10462    }
10463
10464    #[test]
10465    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
10466        // The diagnostic-shape pin: the error names the offending
10467        // `:versao` value verbatim so the author can grep their
10468        // caixa.lisp without re-running the build, and carries a
10469        // non-empty `reason` from `semver::VersionReq::parse` so the
10470        // parser's own wording flows through to the diagnostic.
10471        let mut s = three_member_spec();
10472        s.membros[2].versao = "not-a-req".into();
10473        let err = s.validate().unwrap_err();
10474        let AplicacaoError::MembroVersaoInvalid {
10475            caixa,
10476            versao,
10477            reason,
10478        } = err
10479        else {
10480            panic!("expected MembroVersaoInvalid, got other variant");
10481        };
10482        assert_eq!(caixa, "payment");
10483        assert_eq!(versao, "not-a-req");
10484        assert!(
10485            !reason.is_empty(),
10486            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
10487        );
10488    }
10489
10490    #[test]
10491    fn membro_versao_invalid_runs_before_contratos_check() {
10492        // A malformed `:versao` on any member must surface its own
10493        // diagnostic (which names *which* member to fix) before any
10494        // `:contratos` membership lookup raises `ContratoMemberMissing`.
10495        // The `:contratos` gate runs after `validate_membros`, so this
10496        // is structurally guaranteed — pin it explicitly so a future
10497        // refactor that reorders the gates surfaces here.
10498        let mut s = three_member_spec();
10499        s.membros[1].versao = "^^0.1".into();
10500        // Add a contrato whose `:para` doesn't exist — would normally
10501        // raise ContratoMemberMissing at the membership lookup, but
10502        // the membros gate must fire first.
10503        s.contratos
10504            .push(contract_http("cart", "phantom", "/never-reached"));
10505        let err = s.validate().unwrap_err();
10506        assert!(
10507            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
10508            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
10509        );
10510    }
10511
10512    #[test]
10513    fn membros_validation_runs_before_contratos_membership_check() {
10514        // If `:membros` carries a duplicate, the membership-collapse
10515        // would silently accept a `:contratos :para "phantom"` so long
10516        // as some entry hashes to "phantom". Pinning order: the
10517        // duplicate-membros error fires first, regardless of whether
10518        // contratos reference real members.
10519        let mut s = three_member_spec();
10520        s.membros = vec![
10521            membro("cart", "^0.1"),
10522            membro("cart", "^0.2"),
10523            membro("catalog", "^0.1"),
10524            membro("payment", "^0.1"),
10525        ];
10526        let err = s.validate().unwrap_err();
10527        assert!(
10528            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
10529            "got {err:?}"
10530        );
10531    }
10532
10533    #[test]
10534    fn distinct_membros_validate() {
10535        // Pin the happy-path: every `:membros` entry has a non-empty
10536        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
10537        // The fixture already satisfies this; this test makes the
10538        // invariant explicit so a future refactor of the fixture can't
10539        // silently break the guarantee.
10540        three_member_spec().validate().unwrap();
10541    }
10542
10543    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
10544
10545    #[test]
10546    fn rejects_membro_caixa_with_uppercase() {
10547        // The canonical "I copied the Servico's display name verbatim"
10548        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
10549        // but author tools often round-trip a TitleCase or CamelCase
10550        // identifier from an ADR or a sketch. Pin the diagnostic names
10551        // the offending name and suggests the lower-cased fix in one
10552        // edit, mirroring the `rejects_entrada_host_with_uppercase`
10553        // gate's shape (c7d05ec).
10554        let mut s = three_member_spec();
10555        s.membros[1].caixa = "Cart".into();
10556        let err = s.validate().unwrap_err();
10557        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10558            panic!("expected MembroCaixaInvalid, got other variant");
10559        };
10560        assert_eq!(caixa, "Cart");
10561        assert!(
10562            reason.contains("uppercase"),
10563            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
10564        );
10565        assert!(
10566            reason.contains("\"cart\""),
10567            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
10568        );
10569    }
10570
10571    #[test]
10572    fn rejects_membro_caixa_with_underscore() {
10573        // The canonical "I'm thinking of a Python module / Postgres
10574        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
10575        // label schema. K8s rejects `metadata.name: my_cart` at admission
10576        // time with an opaque `field is invalid` (no source-citing
10577        // diagnostic). The gate moves it to caixa-build time.
10578        let mut s = three_member_spec();
10579        s.membros[0].caixa = "my_cart".into();
10580        let err = s.validate().unwrap_err();
10581        assert!(
10582            matches!(
10583                err,
10584                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10585                    if caixa == "my_cart" && reason.contains('_')
10586            ),
10587            "got {err:?}"
10588        );
10589    }
10590
10591    #[test]
10592    fn rejects_membro_caixa_with_dot() {
10593        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
10594        // subdomain — even though K8s `metadata.name` itself accepts
10595        // dots (DNS-1123 subdomain rule), this string also lands as a
10596        // K8s Service name (DNS-1035 label — no dots) and as a label
10597        // value on identity-based Cilium selectors. The strictest floor
10598        // among the use sites wins. The "I want to namespace my member
10599        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
10600        let mut s = three_member_spec();
10601        s.membros[2].caixa = "team.cart".into();
10602        let err = s.validate().unwrap_err();
10603        assert!(
10604            matches!(
10605                err,
10606                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10607                    if caixa == "team.cart" && reason.contains('.')
10608            ),
10609            "got {err:?}"
10610        );
10611    }
10612
10613    #[test]
10614    fn rejects_membro_caixa_with_leading_hyphen() {
10615        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
10616        // with an alphanumeric. The K8s apiserver rejects `-cart`
10617        // outright; the renderer would emit a `metadata.name: "-cart"`
10618        // that fails admission far from the source caixa.lisp.
10619        let mut s = three_member_spec();
10620        s.membros[0].caixa = "-cart".into();
10621        let err = s.validate().unwrap_err();
10622        assert!(
10623            matches!(
10624                err,
10625                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10626                    if caixa == "-cart" && reason.contains("start and end")
10627            ),
10628            "got {err:?}"
10629        );
10630    }
10631
10632    #[test]
10633    fn rejects_membro_caixa_with_trailing_hyphen() {
10634        // The symmetric arm of the boundary rule. Pin separately so
10635        // both ends of the label are covered against a future relaxation
10636        // that only checks one boundary.
10637        let mut s = three_member_spec();
10638        s.membros[1].caixa = "cart-".into();
10639        let err = s.validate().unwrap_err();
10640        assert!(
10641            matches!(
10642                err,
10643                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10644                    if caixa == "cart-"
10645            ),
10646            "got {err:?}"
10647        );
10648    }
10649
10650    #[test]
10651    fn rejects_membro_caixa_with_unicode() {
10652        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
10653        // (`xn--…`) by the author before it reaches K8s. The byte-by-
10654        // byte ASCII validity check rejects multi-byte UTF-8 sequences
10655        // by the first byte that fails the `[a-z0-9-]` predicate.
10656        let mut s = three_member_spec();
10657        s.membros[2].caixa = "café".into();
10658        let err = s.validate().unwrap_err();
10659        assert!(
10660            matches!(
10661                err,
10662                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10663                    if caixa == "café"
10664            ),
10665            "got {err:?}"
10666        );
10667    }
10668
10669    #[test]
10670    fn rejects_membro_caixa_with_whitespace() {
10671        // Whitespace is the canonical "I pasted from a sketch / doc"
10672        // footgun. The apiserver rejects every `metadata.name` value
10673        // carrying whitespace; pin the gate fires at the right boundary.
10674        let mut s = three_member_spec();
10675        s.membros[0].caixa = "my cart".into();
10676        let err = s.validate().unwrap_err();
10677        assert!(
10678            matches!(
10679                err,
10680                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
10681                    if caixa == "my cart"
10682            ),
10683            "got {err:?}"
10684        );
10685    }
10686
10687    #[test]
10688    fn rejects_membro_caixa_too_long() {
10689        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
10690        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
10691        // exactly. The gate's reason names both the cap and the actual
10692        // length so the author can shorten in one edit.
10693        let mut s = three_member_spec();
10694        let too_long = "a".repeat(64);
10695        s.membros[1].caixa = too_long.clone();
10696        let err = s.validate().unwrap_err();
10697        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10698            panic!("expected MembroCaixaInvalid");
10699        };
10700        assert_eq!(caixa, too_long);
10701        assert!(
10702            reason.contains("63") && reason.contains("64"),
10703            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
10704        );
10705    }
10706
10707    #[test]
10708    fn membro_caixa_max_length_validates() {
10709        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
10710        // so a future tightening (e.g. dropping to 62) surfaces here as
10711        // a regression, mirroring `entrada_host_max_length_validates`
10712        // (c7d05ec).
10713        let mut s = three_member_spec();
10714        s.membros[2].caixa = "a".repeat(63);
10715        s.entrada.as_mut().unwrap().para = "a".repeat(63);
10716        // remove contratos referencing the renamed member; they'd
10717        // raise ContratoMemberMissing otherwise
10718        s.contratos
10719            .retain(|c| c.de != "payment" && c.para != "payment");
10720        s.validate().unwrap();
10721    }
10722
10723    #[test]
10724    fn accepts_canonical_membro_caixa_forms() {
10725        // The DNS-1123 label shapes a caixa author is realistically
10726        // going to write: single-word lowercase, hyphen-joined, ending
10727        // in a digit-suffixed version (`cart-v2`), starting with a
10728        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
10729        // DNS-1035 which requires a letter at position 0), single-
10730        // character (`a` — boundary). Pin every leg so a future
10731        // tightening that bans (e.g.) digit-start identifiers surfaces
10732        // here.
10733        for form in [
10734            "checkout",
10735            "cart",
10736            "cart-v2",
10737            "a",
10738            "c0",
10739            "3rd-party-shim",
10740            "x-1-2-3-4",
10741        ] {
10742            let mut s = three_member_spec();
10743            // Renaming a member also requires updating downstream refs;
10744            // drop everything else and rebuild a minimal spec around
10745            // just the one renamed member.
10746            s.membros = vec![membro(form, "^0.1")];
10747            s.contratos = vec![];
10748            s.entrada = None;
10749            s.validate()
10750                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
10751        }
10752    }
10753
10754    #[test]
10755    fn membro_caixa_empty_takes_precedence_over_invalid() {
10756        // Order pin: the existing `MembroCaixaEmpty` diagnostic
10757        // (which doesn't try to parse) fires before the new
10758        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
10759        // `:caixa` keeps its narrower error message — the new gate
10760        // would also reject `""`, but the empty-string arm is the more
10761        // self-locating diagnostic for the author. Mirrors the
10762        // `entrada_host_empty_takes_precedence_over_invalid` pin
10763        // (c7d05ec).
10764        let mut s = three_member_spec();
10765        s.membros[1].caixa = String::new();
10766        let err = s.validate().unwrap_err();
10767        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
10768    }
10769
10770    #[test]
10771    fn membro_caixa_invalid_fires_before_versao_check() {
10772        // Order pin: an invalid-shape `:caixa` surfaces *its own*
10773        // diagnostic (which names the offending caixa name), even when
10774        // the same entry's `:versao` is also empty/invalid. The shape
10775        // gate runs first because the diagnostic is more self-locating —
10776        // an empty/invalid `:versao` on an invalid-shape caixa name is
10777        // a downstream-fix-after-the-caixa-rename concern.
10778        let mut s = three_member_spec();
10779        s.membros[1].caixa = "Cart".into();
10780        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
10781        let err = s.validate().unwrap_err();
10782        assert!(
10783            matches!(
10784                err,
10785                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
10786            ),
10787            "got {err:?}"
10788        );
10789    }
10790
10791    #[test]
10792    fn membro_caixa_invalid_fires_before_duplicate_check() {
10793        // Order pin: a malformed-shape `:caixa` on an earlier entry
10794        // surfaces *its own* diagnostic, even when a later entry would
10795        // otherwise collapse onto a duplicate name. The per-entry shape
10796        // gate runs inline before the duplicate-key insert, parallel
10797        // to `membro_versao_invalid_fires_before_duplicate_check`.
10798        let mut s = three_member_spec();
10799        s.membros[0].caixa = "Catalog".into();
10800        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
10801        let err = s.validate().unwrap_err();
10802        assert!(
10803            matches!(
10804                err,
10805                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
10806            ),
10807            "got {err:?}"
10808        );
10809    }
10810
10811    #[test]
10812    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
10813        // The diagnostic-shape pin: the error names the offending
10814        // `:caixa` value verbatim so the author can grep their
10815        // caixa.lisp without re-running the build, and carries a
10816        // non-empty `reason` naming the specific violation. Same
10817        // shape every typed-shape gate enshrines (c7d05ec's
10818        // `entrada_host_diagnostic_carries_offending_host`,
10819        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
10820        let mut s = three_member_spec();
10821        s.membros[2].caixa = "BAD_NAME".into();
10822        let err = s.validate().unwrap_err();
10823        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10824            panic!("expected MembroCaixaInvalid");
10825        };
10826        assert_eq!(caixa, "BAD_NAME");
10827        assert!(
10828            !reason.is_empty(),
10829            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
10830        );
10831    }
10832
10833    #[test]
10834    fn rejects_contrato_with_unknown_de() {
10835        let mut s = three_member_spec();
10836        s.contratos.push(contract_http("phantom", "catalog", "/x"));
10837        let err = s.validate().unwrap_err();
10838        assert!(
10839            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
10840        );
10841    }
10842
10843    #[test]
10844    fn rejects_contrato_with_unknown_para() {
10845        let mut s = three_member_spec();
10846        s.contratos.push(contract_http("cart", "phantom", "/x"));
10847        let err = s.validate().unwrap_err();
10848        assert!(
10849            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
10850        );
10851    }
10852
10853    #[test]
10854    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
10855        // The read-path pin: the phantom-`:de` refusal arm's
10856        // `ContratoMemberMissing.caixa` carrier must be observed through
10857        // the lifted [`WitContract::source`] accessor, not the raw
10858        // `.de.clone()` field-access `String`-carry. Peer of the sibling
10859        // per-`:contratos` self-loop arm's `.source().to_string()` /
10860        // `.world_ref().to_string()` `String`-carry sites the earlier
10861        // convergence lifted onto the same accessor pair. A future
10862        // silent detour that reintroduced the raw `.de.clone()` at the
10863        // wrap envelope while the shape-gate and membership lookup
10864        // routed through the accessor would surface here as a byte-equal
10865        // miss between the fired diagnostic's `caixa:` field and the
10866        // offending edge's `.source()` — pinning the accessor as the
10867        // sole read path across the phantom-name refusal arm's arg +
10868        // wrap-envelope emit surface.
10869        let mut s = three_member_spec();
10870        let phantom = contract_http("phantom", "catalog", "/x");
10871        s.contratos.push(phantom.clone());
10872        let err = s.validate().unwrap_err();
10873        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
10874            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
10875        };
10876        assert_eq!(
10877            caixa,
10878            phantom.source(),
10879            "ContratoMemberMissing.caixa on the phantom-:de arm must \
10880             byte-equal WitContract::source — the wrap envelope must \
10881             route through the lifted accessor rather than the raw \
10882             .de.clone() field-access String-carry"
10883        );
10884    }
10885
10886    #[test]
10887    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
10888        // The symmetric read-path pin on the `:para` phantom-name
10889        // refusal arm — same shape as the sibling `:de` pin above but
10890        // on the callee-Servico axis. Pins the wrap envelope's
10891        // `caixa:` field is observed through the lifted
10892        // [`WitContract::destination`] accessor, not the raw
10893        // `.para.clone()` field-access `String`-carry.
10894        let mut s = three_member_spec();
10895        let phantom = contract_http("cart", "phantom", "/x");
10896        s.contratos.push(phantom.clone());
10897        let err = s.validate().unwrap_err();
10898        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
10899            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
10900        };
10901        assert_eq!(
10902            caixa,
10903            phantom.destination(),
10904            "ContratoMemberMissing.caixa on the phantom-:para arm must \
10905             byte-equal WitContract::destination — the wrap envelope \
10906             must route through the lifted accessor rather than the raw \
10907             .para.clone() field-access String-carry"
10908        );
10909    }
10910
10911    #[test]
10912    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
10913        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
10914        // refusal arm — the `validate_contrato_caixa` arg must be
10915        // observed through the lifted [`WitContract::source`] accessor,
10916        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
10917        // value routes through the shared
10918        // [`crate::render::require_valid_dns_1123_label`] floor with the
10919        // accessor-projected value; the fired
10920        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
10921        // the offending edge's `.source()`, pinning that the arg + the
10922        // downstream `caixa: caixa.to_string()` wrap route through the
10923        // same accessor's read path.
10924        let mut s = three_member_spec();
10925        let malformed = contract_http("BAD_NAME", "catalog", "/x");
10926        s.contratos.push(malformed.clone());
10927        let err = s.validate().unwrap_err();
10928        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
10929            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
10930        };
10931        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
10932        assert_eq!(
10933            caixa,
10934            malformed.source(),
10935            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
10936             byte-equal WitContract::source — the shape-gate arg + wrap \
10937             envelope must route through the lifted accessor rather \
10938             than the raw &c.de &String-borrow"
10939        );
10940    }
10941
10942    #[test]
10943    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
10944        // Symmetric arm to the sibling `:de` malformed-shape pin above,
10945        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
10946        // route through the lifted [`WitContract::destination`]
10947        // accessor. `:para` runs after the `:de` shape gate in the
10948        // canonical edge-direction order, so the `:de` value must be
10949        // well-shaped for the `:para` gate to fire — the `cart` :de is
10950        // canonical.
10951        let mut s = three_member_spec();
10952        let malformed = contract_http("cart", "BAD_NAME", "/x");
10953        s.contratos.push(malformed.clone());
10954        let err = s.validate().unwrap_err();
10955        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
10956            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
10957        };
10958        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
10959        assert_eq!(
10960            caixa,
10961            malformed.destination(),
10962            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
10963             byte-equal WitContract::destination — the shape-gate arg + \
10964             wrap envelope must route through the lifted accessor \
10965             rather than the raw &c.para &String-borrow"
10966        );
10967    }
10968
10969    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
10970
10971    #[test]
10972    fn rejects_contrato_de_empty() {
10973        // `:de ""` previously fell through to `ContratoMemberMissing`
10974        // (with `caixa: ""`) because the validated `:membros :caixa`
10975        // set never contains the empty string. The narrower
10976        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
10977        // the offending slot.
10978        let mut s = three_member_spec();
10979        s.contratos.push(contract_http("", "catalog", "/x"));
10980        let err = s.validate().unwrap_err();
10981        assert_eq!(
10982            err,
10983            AplicacaoError::ContratoCaixaEmpty {
10984                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
10985            },
10986            "got {err:?}"
10987        );
10988    }
10989
10990    #[test]
10991    fn rejects_contrato_para_empty() {
10992        // Symmetric arm to `:de ""` — `:para ""` previously fell
10993        // through to `ContratoMemberMissing { caixa: "" }`.
10994        let mut s = three_member_spec();
10995        s.contratos.push(contract_http("cart", "", "/x"));
10996        let err = s.validate().unwrap_err();
10997        assert_eq!(
10998            err,
10999            AplicacaoError::ContratoCaixaEmpty {
11000                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
11001            },
11002            "got {err:?}"
11003        );
11004    }
11005
11006    #[test]
11007    fn rejects_contrato_de_with_uppercase() {
11008        // The canonical "I copied the Servico's TitleCase display
11009        // name from an ADR" typo. Until this gate landed `:de "Cart"`
11010        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
11011        // as "this caixa isn't in `:membros`" when the root cause is
11012        // "this `:de` value's shape can never legitimately match a
11013        // validated member (DNS-1123 labels are lowercase)". The
11014        // narrower diagnostic names the offending slot, the value
11015        // verbatim, and the parser-shaped reason.
11016        let mut s = three_member_spec();
11017        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11018        let err = s.validate().unwrap_err();
11019        let AplicacaoError::ContratoCaixaInvalid {
11020            slot,
11021            caixa,
11022            reason,
11023        } = err
11024        else {
11025            panic!("expected ContratoCaixaInvalid, got other variant");
11026        };
11027        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
11028        assert_eq!(caixa, "Cart");
11029        assert!(
11030            reason.contains("uppercase"),
11031            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11032        );
11033    }
11034
11035    #[test]
11036    fn rejects_contrato_para_with_underscore() {
11037        // The canonical "I'm thinking of a Python module" leak —
11038        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
11039        // Pin the `:para` axis surfaces the same diagnostic shape as
11040        // the `:de` axis on the underscore violation.
11041        let mut s = three_member_spec();
11042        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
11043        let err = s.validate().unwrap_err();
11044        assert!(
11045            matches!(
11046                err,
11047                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11048                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
11049            ),
11050            "got {err:?}"
11051        );
11052    }
11053
11054    #[test]
11055    fn rejects_contrato_de_with_dot() {
11056        // A `:contratos :de` value is a single DNS-1123 *label*, not
11057        // a subdomain — mirroring the `:membros :caixa` floor. The
11058        // strictest floor among the use sites wins.
11059        let mut s = three_member_spec();
11060        s.contratos
11061            .push(contract_http("team.cart", "catalog", "/x"));
11062        let err = s.validate().unwrap_err();
11063        assert!(
11064            matches!(
11065                err,
11066                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11067                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
11068            ),
11069            "got {err:?}"
11070        );
11071    }
11072
11073    #[test]
11074    fn rejects_contrato_para_with_unicode() {
11075        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11076        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
11077        // validity check rejects multi-byte UTF-8 by the first
11078        // non-`[a-z0-9-]` byte.
11079        let mut s = three_member_spec();
11080        s.contratos.push(contract_http("cart", "café", "/x"));
11081        let err = s.validate().unwrap_err();
11082        assert!(
11083            matches!(
11084                err,
11085                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11086                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
11087            ),
11088            "got {err:?}"
11089        );
11090    }
11091
11092    #[test]
11093    fn rejects_contrato_de_with_leading_hyphen() {
11094        // DNS-1123 boundary rule: labels must start and end with an
11095        // alphanumeric. K8s rejects `-cart` outright; the narrower
11096        // shape diagnostic now names the violation at caixa-build
11097        // time rather than the misframed membership-lookup arm.
11098        let mut s = three_member_spec();
11099        s.contratos.push(contract_http("-cart", "catalog", "/x"));
11100        let err = s.validate().unwrap_err();
11101        assert!(
11102            matches!(
11103                err,
11104                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11105                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
11106            ),
11107            "got {err:?}"
11108        );
11109    }
11110
11111    #[test]
11112    fn contrato_de_empty_takes_precedence_over_invalid() {
11113        // Order pin: the `ContratoCaixaEmpty` arm fires before the
11114        // `ContratoCaixaInvalid` parse-side arm — same empty-first
11115        // cascade `validate_membro_caixa` / `validate_placement_cluster`
11116        // / `validate_entrada_host` already establish on their peer
11117        // name axes. The empty string is a structurally distinct
11118        // authoring footgun (the author left the field blank, vs.
11119        // typed a malformed value), so it gets its own diagnostic.
11120        let mut s = three_member_spec();
11121        s.contratos.push(contract_http("", "catalog", "/x"));
11122        let err = s.validate().unwrap_err();
11123        assert_eq!(
11124            err,
11125            AplicacaoError::ContratoCaixaEmpty {
11126                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11127            }
11128        );
11129    }
11130
11131    #[test]
11132    fn contrato_de_shape_fires_before_para_shape() {
11133        // Per-axis order pin: within one `:contratos` entry, the `:de`
11134        // shape gate fires before the `:para` shape gate — same
11135        // edge-direction order the existing `ContratoMemberMissing` /
11136        // `ContratoSelfLoop` / target-dispatch checks use, so the
11137        // diagnostic for a contract with both `:de` and `:para`
11138        // malformed is stable. Authors fixing the surfaced `:de`
11139        // first will see `:para`'s diagnostic on re-run.
11140        let mut s = three_member_spec();
11141        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
11142        let err = s.validate().unwrap_err();
11143        assert!(
11144            matches!(
11145                err,
11146                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11147                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11148            ),
11149            "got {err:?}"
11150        );
11151    }
11152
11153    #[test]
11154    fn contrato_shape_fires_before_membership_lookup() {
11155        // The load-bearing pin: an invalid-shape `:de` surfaces its
11156        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
11157        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11158        // an invalid-shape `:de` could never legitimately match any
11159        // member — the prior `ContratoMemberMissing` diagnostic was
11160        // a structural impossibility framed as a graph-membership
11161        // failure. The shape gate now routes every such input through
11162        // the narrower self-locating diagnostic.
11163        let mut s = three_member_spec();
11164        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11165        let err = s.validate().unwrap_err();
11166        assert!(
11167            matches!(
11168                err,
11169                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
11170            ),
11171            "got {err:?}"
11172        );
11173        // And the symmetric case: an invalid-shape `:para` surfaces
11174        // its own diagnostic too, even when `:de` is well-shaped.
11175        let mut s = three_member_spec();
11176        s.contratos.push(contract_http("cart", "Catalog", "/x"));
11177        let err = s.validate().unwrap_err();
11178        assert!(
11179            matches!(
11180                err,
11181                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
11182            ),
11183            "got {err:?}"
11184        );
11185    }
11186
11187    #[test]
11188    fn contrato_shape_fires_before_self_edge_check() {
11189        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
11190        // bugs: the shape violation (uppercase) and the self-edge
11191        // violation. The narrower per-axis shape diagnostic surfaces
11192        // first because fixing the shape may reveal that the author
11193        // also meant to point `:para` at a different member — the
11194        // self-edge framing is only useful once both endpoints have
11195        // valid shape.
11196        let mut s = three_member_spec();
11197        s.contratos.push(contract_http("Cart", "Cart", "/x"));
11198        let err = s.validate().unwrap_err();
11199        assert!(
11200            matches!(
11201                err,
11202                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11203                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11204            ),
11205            "got {err:?}"
11206        );
11207    }
11208
11209    #[test]
11210    fn contrato_well_shaped_phantom_still_raises_member_missing() {
11211        // Strict-improvement pin: a well-shaped `:de` that simply
11212        // isn't in `:membros` (a phantom reference — author meant
11213        // to add the member but didn't, or renamed and missed an
11214        // update) still surfaces `ContratoMemberMissing`, unchanged.
11215        // The shape gate only intercepts inputs that could never
11216        // legitimately match a validated member; legitimately-shaped
11217        // phantom references remain on the graph-membership axis.
11218        let mut s = three_member_spec();
11219        s.contratos
11220            .push(contract_http("phantom-shim", "catalog", "/x"));
11221        let err = s.validate().unwrap_err();
11222        assert!(
11223            matches!(
11224                err,
11225                AplicacaoError::ContratoMemberMissing { ref caixa }
11226                    if caixa == "phantom-shim"
11227            ),
11228            "got {err:?}"
11229        );
11230    }
11231
11232    #[test]
11233    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
11234        // The diagnostic-shape pin: the error names the offending
11235        // slot (`:de` or `:para`) verbatim and the offending value
11236        // verbatim plus a non-empty parser-shaped reason, so the
11237        // author can grep their caixa.lisp for `:de "<name>"` /
11238        // `:para "<name>"` and fix it in one edit. Same diagnostic
11239        // shape as `MembroCaixaInvalid` (3f9d7a0) and
11240        // `PlacementClusterInvalid` (6c8c00b).
11241        let mut s = three_member_spec();
11242        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
11243        let err = s.validate().unwrap_err();
11244        let AplicacaoError::ContratoCaixaInvalid {
11245            slot,
11246            caixa,
11247            reason,
11248        } = err
11249        else {
11250            panic!("expected ContratoCaixaInvalid, got {err:?}");
11251        };
11252        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
11253        assert_eq!(caixa, "BAD_NAME");
11254        assert!(
11255            !reason.is_empty(),
11256            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
11257        );
11258    }
11259
11260    #[test]
11261    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
11262        // Scalar-value pin: the two author-facing kebab-case labels the
11263        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
11264        // admits on the `:contratos` per-entry endpoint-shape axis,
11265        // one arm per typed sub-slot. Mirrors the peer scalar-value
11266        // pin the sibling top-level M2 / M3 / Supervisor
11267        // author-facing-label consts carry
11268        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
11269        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
11270        // slot itself), so every altitude of the typed-slot algebra
11271        // shares the same "one canonical byte-string per arm"
11272        // discipline. A future rebrand (`:de` → `:from` matching the
11273        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
11274        // sibling, `:para` → `:to` matching the same, or
11275        // `:de`/`:para` → `:source`/`:target` matching the WIT
11276        // world's `import`/`export` half-vocabulary) lands as an
11277        // edit to exactly one const, and every consumer that reaches
11278        // for the label picks it up at build time rather than at
11279        // runtime as a downstream `ContratoCaixaEmpty` /
11280        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
11281        // diagnostic mismatch far from the rename's commit.
11282        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
11283        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
11284    }
11285
11286    #[test]
11287    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
11288        // Production-through-const pin: the two per-axis labels the
11289        // per-`:contratos` entry endpoint-shape gate at
11290        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
11291        // argument to [`validate_contrato_caixa`] route through the
11292        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11293        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
11294        // future rebrand that reaches the const but not the gate (or
11295        // vice versa) surfaces here at build time rather than at
11296        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
11297        // `slot: <stale-kebab-case>` diagnostic far from the rename's
11298        // commit. Mirror of the peer
11299        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
11300        // pin (882f498) on the sibling M3 top-level slot axis.
11301        let mut s = three_member_spec();
11302        s.contratos.push(contract_http("", "catalog", "/x"));
11303        assert_eq!(
11304            s.validate().unwrap_err(),
11305            AplicacaoError::ContratoCaixaEmpty {
11306                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11307            }
11308        );
11309        let mut s = three_member_spec();
11310        s.contratos.push(contract_http("cart", "", "/x"));
11311        assert_eq!(
11312            s.validate().unwrap_err(),
11313            AplicacaoError::ContratoCaixaEmpty {
11314                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
11315            }
11316        );
11317    }
11318
11319    #[test]
11320    fn accepts_canonical_contrato_caixa_forms() {
11321        // The DNS-1123 label shapes a caixa author is realistically
11322        // going to write on a `:contratos :de` / `:para`. Pin every
11323        // leg so a future tightening that bans (e.g.) digit-start
11324        // identifiers surfaces here, mirroring
11325        // `accepts_canonical_membro_caixa_forms` on the peer name
11326        // axis.
11327        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11328            let mut s = three_member_spec();
11329            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
11330            s.contratos = vec![contract_http("checkout", form, "/x")];
11331            s.entrada = None;
11332            s.validate().unwrap_or_else(|e| {
11333                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
11334            });
11335
11336            let mut s = three_member_spec();
11337            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11338            s.contratos = vec![contract_http(form, "catalog", "/x")];
11339            s.entrada = None;
11340            s.validate().unwrap_or_else(|e| {
11341                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
11342            });
11343        }
11344    }
11345
11346    #[test]
11347    fn rejects_empty_wit() {
11348        let mut s = three_member_spec();
11349        s.contratos.push(WitContract {
11350            de: "cart".into(),
11351            para: "catalog".into(),
11352            wit: String::new(),
11353            endpoint: None,
11354            subject: None,
11355            slot: None,
11356        });
11357        let err = s.validate().unwrap_err();
11358        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
11359    }
11360
11361    #[test]
11362    fn rejects_entrada_to_unknown_member() {
11363        let mut s = three_member_spec();
11364        s.entrada.as_mut().unwrap().para = "phantom".into();
11365        assert!(matches!(
11366            s.validate().unwrap_err(),
11367            AplicacaoError::EntradaMemberMissing { .. }
11368        ));
11369    }
11370
11371    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
11372
11373    #[test]
11374    fn rejects_entrada_para_empty() {
11375        // `:para ""` previously fell through to
11376        // `EntradaMemberMissing { para: "" }` because the validated
11377        // `:membros :caixa` set never contains the empty string. The
11378        // narrower `EntradaParaEmpty` diagnostic now names the
11379        // offending slot directly — same empty-first cascade
11380        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
11381        // `ContratoCaixaEmpty` establish on the peer name axes.
11382        let mut s = three_member_spec();
11383        s.entrada.as_mut().unwrap().para = String::new();
11384        let err = s.validate().unwrap_err();
11385        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
11386    }
11387
11388    #[test]
11389    fn rejects_entrada_para_with_uppercase() {
11390        // The canonical "I copied the Servico's TitleCase display
11391        // name from an ADR" typo. Until this gate landed `:para "Cart"`
11392        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
11393        // as "this caixa isn't in `:membros`" when the root cause is
11394        // "this `:para` value's shape can never legitimately match a
11395        // validated member (DNS-1123 labels are lowercase)". The
11396        // narrower diagnostic names the value verbatim plus the
11397        // parser-shaped reason.
11398        let mut s = three_member_spec();
11399        s.entrada.as_mut().unwrap().para = "Cart".into();
11400        let err = s.validate().unwrap_err();
11401        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
11402            panic!("expected EntradaParaInvalid, got other variant");
11403        };
11404        assert_eq!(para, "Cart");
11405        assert!(
11406            reason.contains("uppercase"),
11407            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11408        );
11409    }
11410
11411    #[test]
11412    fn rejects_entrada_para_with_underscore() {
11413        // The canonical "I'm thinking of a Python module" leak —
11414        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
11415        let mut s = three_member_spec();
11416        s.entrada.as_mut().unwrap().para = "my_cart".into();
11417        let err = s.validate().unwrap_err();
11418        assert!(
11419            matches!(
11420                err,
11421                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11422                    if para == "my_cart" && reason.contains('_')
11423            ),
11424            "got {err:?}"
11425        );
11426    }
11427
11428    #[test]
11429    fn rejects_entrada_para_with_dot() {
11430        // An `:entrada :para` value is a single DNS-1123 *label*, not
11431        // a subdomain — mirroring the `:membros :caixa` floor. The
11432        // strictest floor among the use sites wins.
11433        let mut s = three_member_spec();
11434        s.entrada.as_mut().unwrap().para = "team.cart".into();
11435        let err = s.validate().unwrap_err();
11436        assert!(
11437            matches!(
11438                err,
11439                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11440                    if para == "team.cart" && reason.contains('.')
11441            ),
11442            "got {err:?}"
11443        );
11444    }
11445
11446    #[test]
11447    fn rejects_entrada_para_with_unicode() {
11448        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11449        // (`xn--…`) before it reaches K8s.
11450        let mut s = three_member_spec();
11451        s.entrada.as_mut().unwrap().para = "café".into();
11452        let err = s.validate().unwrap_err();
11453        assert!(
11454            matches!(
11455                err,
11456                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
11457            ),
11458            "got {err:?}"
11459        );
11460    }
11461
11462    #[test]
11463    fn rejects_entrada_para_with_leading_hyphen() {
11464        // DNS-1123 boundary rule: labels must start and end with an
11465        // alphanumeric. K8s rejects `-cart` outright.
11466        let mut s = three_member_spec();
11467        s.entrada.as_mut().unwrap().para = "-cart".into();
11468        let err = s.validate().unwrap_err();
11469        assert!(
11470            matches!(
11471                err,
11472                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11473                    if para == "-cart" && reason.contains("start and end")
11474            ),
11475            "got {err:?}"
11476        );
11477    }
11478
11479    #[test]
11480    fn rejects_entrada_para_with_trailing_hyphen() {
11481        // Symmetric boundary arm.
11482        let mut s = three_member_spec();
11483        s.entrada.as_mut().unwrap().para = "cart-".into();
11484        let err = s.validate().unwrap_err();
11485        assert!(
11486            matches!(
11487                err,
11488                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11489                    if para == "cart-" && reason.contains("start and end")
11490            ),
11491            "got {err:?}"
11492        );
11493    }
11494
11495    #[test]
11496    fn rejects_entrada_para_too_long() {
11497        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
11498        // bytes per label. K8s rejects longer names at admission on
11499        // every `metadata.name` axis.
11500        let mut s = three_member_spec();
11501        s.entrada.as_mut().unwrap().para = "a".repeat(64);
11502        let err = s.validate().unwrap_err();
11503        assert!(
11504            matches!(
11505                err,
11506                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11507                    if para.len() == 64 && reason.contains("max length")
11508            ),
11509            "got {err:?}"
11510        );
11511    }
11512
11513    #[test]
11514    fn entrada_para_empty_takes_precedence_over_invalid() {
11515        // Order pin: the `EntradaParaEmpty` arm fires before the
11516        // `EntradaParaInvalid` parse-side arm — same empty-first
11517        // cascade `validate_membro_caixa` / `validate_placement_cluster`
11518        // / `validate_contrato_caixa` already establish.
11519        let mut s = three_member_spec();
11520        s.entrada.as_mut().unwrap().para = String::new();
11521        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
11522    }
11523
11524    #[test]
11525    fn entrada_para_shape_fires_before_membership_lookup() {
11526        // The load-bearing pin: an invalid-shape `:para` surfaces its
11527        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
11528        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11529        // an invalid-shape `:para` could never legitimately match any
11530        // member — the prior `EntradaMemberMissing` diagnostic framed
11531        // a structural impossibility as a graph-membership failure.
11532        let mut s = three_member_spec();
11533        s.entrada.as_mut().unwrap().para = "Cart".into();
11534        let err = s.validate().unwrap_err();
11535        assert!(
11536            matches!(
11537                err,
11538                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
11539            ),
11540            "got {err:?}"
11541        );
11542    }
11543
11544    #[test]
11545    fn entrada_para_shape_fires_before_host_gate() {
11546        // Per-`:entrada` order pin: the `:para` shape gate fires
11547        // before the `:host` gate, mirroring the existing
11548        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
11549        // ordering where the member-lookup arm preceded the host gate.
11550        // The shape gate slots ahead of that, so a malformed `:para`
11551        // surfaces its own diagnostic even when `:host` is also wrong.
11552        let mut s = three_member_spec();
11553        let e = s.entrada.as_mut().unwrap();
11554        e.para = "Cart".into();
11555        e.host = "BAD HOST".into();
11556        let err = s.validate().unwrap_err();
11557        assert!(
11558            matches!(
11559                err,
11560                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
11561            ),
11562            "got {err:?}"
11563        );
11564    }
11565
11566    #[test]
11567    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
11568        // Strict-improvement pin: a well-shaped `:para` that simply
11569        // isn't in `:membros` (a phantom reference — author meant to
11570        // add the member but didn't, or renamed and missed an
11571        // update) still surfaces `EntradaMemberMissing`, unchanged.
11572        // The shape gate only intercepts inputs that could never
11573        // legitimately match a validated member.
11574        let mut s = three_member_spec();
11575        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
11576        let err = s.validate().unwrap_err();
11577        assert!(
11578            matches!(
11579                err,
11580                AplicacaoError::EntradaMemberMissing { ref para }
11581                    if para == "phantom-shim"
11582            ),
11583            "got {err:?}"
11584        );
11585    }
11586
11587    #[test]
11588    fn entrada_para_invalid_diagnostic_carries_offending_para() {
11589        // The diagnostic-shape pin: the error names the offending
11590        // `:para` value verbatim plus a non-empty parser-shaped
11591        // reason, so the author can grep their caixa.lisp for
11592        // `:para "<name>"` and fix it in one edit. Same diagnostic
11593        // shape as `MembroCaixaInvalid` (3f9d7a0),
11594        // `PlacementClusterInvalid` (6c8c00b), and
11595        // `ContratoCaixaInvalid` (8d5af6b).
11596        let mut s = three_member_spec();
11597        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
11598        let err = s.validate().unwrap_err();
11599        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
11600            panic!("expected EntradaParaInvalid, got {err:?}");
11601        };
11602        assert_eq!(para, "BAD_NAME");
11603        assert!(
11604            !reason.is_empty(),
11605            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
11606        );
11607    }
11608
11609    #[test]
11610    fn accepts_canonical_entrada_para_forms() {
11611        // Positive-control sweep covering the DNS-1123 label shapes a
11612        // caixa author is realistically going to write on `:entrada
11613        // :para`. Pin every leg so a future tightening that bans
11614        // (e.g.) digit-start identifiers surfaces here, mirroring
11615        // `accepts_canonical_membro_caixa_forms` and
11616        // `accepts_canonical_contrato_caixa_forms` on the peer name
11617        // axes.
11618        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11619            let mut s = three_member_spec();
11620            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11621            s.contratos = vec![contract_http(form, "catalog", "/x")];
11622            s.entrada = Some(Entrada {
11623                host: "checkout.quero.cloud".into(),
11624                para: form.into(),
11625                paths: vec!["/api".into()],
11626                port: 8080,
11627            });
11628            s.validate().unwrap_or_else(|e| {
11629                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
11630            });
11631        }
11632    }
11633
11634    #[test]
11635    fn rejects_replicated_without_clusters() {
11636        let mut s = three_member_spec();
11637        s.placement.clusters = vec![];
11638        assert!(matches!(
11639            s.validate().unwrap_err(),
11640            AplicacaoError::PlacementWithoutClusters { .. }
11641        ));
11642    }
11643
11644    #[test]
11645    fn rejects_sharded_without_key() {
11646        let mut s = three_member_spec();
11647        s.placement.estrategia = PlacementStrategy::Sharded;
11648        s.placement.shard_key = None;
11649        s.placement.clusters = vec!["rio".into()];
11650        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
11651    }
11652
11653    #[test]
11654    fn sharded_with_key_validates() {
11655        let mut s = three_member_spec();
11656        s.placement.estrategia = PlacementStrategy::Sharded;
11657        s.placement.shard_key = Some("$tenantId".into());
11658        s.validate().unwrap();
11659    }
11660
11661    #[test]
11662    fn round_trip_via_json_preserves_shape() {
11663        let s = three_member_spec();
11664        let json = serde_json::to_string(&s.membros).unwrap();
11665        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
11666        assert_eq!(back, s.membros);
11667
11668        let json = serde_json::to_string(&s.contratos).unwrap();
11669        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
11670        assert_eq!(back, s.contratos);
11671
11672        let json = serde_json::to_string(&s.placement).unwrap();
11673        let back: Placement = serde_json::from_str(&json).unwrap();
11674        assert_eq!(back, s.placement);
11675
11676        let json = serde_json::to_string(&s.entrada).unwrap();
11677        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
11678        assert_eq!(back, s.entrada);
11679    }
11680
11681    #[test]
11682    fn rate_limit_round_trip_seconds() {
11683        let policy = MeshPolicy {
11684            rate_limit: Some(RateLimit {
11685                rate: 100,
11686                window: Duration::from_secs(1),
11687            }),
11688            ..Default::default()
11689        };
11690        let json = serde_json::to_string(&policy).unwrap();
11691        assert!(json.contains("\"100/s\""));
11692        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
11693        assert_eq!(back.rate_limit.unwrap().rate, 100);
11694        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
11695    }
11696
11697    #[test]
11698    fn rate_limit_round_trip_minutes() {
11699        let policy = MeshPolicy {
11700            rate_limit: Some(RateLimit {
11701                rate: 5000,
11702                window: Duration::from_secs(60),
11703            }),
11704            ..Default::default()
11705        };
11706        let json = serde_json::to_string(&policy).unwrap();
11707        assert!(json.contains("\"5000/m\""));
11708    }
11709
11710    #[test]
11711    fn circuit_breaker_round_trip() {
11712        let policy = MeshPolicy {
11713            circuit_breaker: Some(CircuitBreaker {
11714                max_failures: 5,
11715                window: Duration::from_secs(60),
11716            }),
11717            ..Default::default()
11718        };
11719        let json = serde_json::to_string(&policy).unwrap();
11720        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
11721        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
11722        assert_eq!(
11723            back.circuit_breaker.unwrap().window,
11724            Duration::from_secs(60)
11725        );
11726    }
11727
11728    #[test]
11729    fn rejects_http_contrato_without_endpoint() {
11730        let mut s = three_member_spec();
11731        s.contratos.push(WitContract {
11732            de: "cart".into(),
11733            para: "catalog".into(),
11734            wit: "wasi:http/proxy".into(),
11735            endpoint: None,
11736            subject: None,
11737            slot: None,
11738        });
11739        let err = s.validate().unwrap_err();
11740        assert!(matches!(
11741            err,
11742            AplicacaoError::ContratoMissingTarget {
11743                expected: WitTarget::HTTP_FIELD_NAME,
11744                ..
11745            }
11746        ));
11747    }
11748
11749    #[test]
11750    fn rejects_http_contrato_with_subject() {
11751        let mut s = three_member_spec();
11752        s.contratos.push(WitContract {
11753            de: "cart".into(),
11754            para: "catalog".into(),
11755            wit: "wasi:http/proxy".into(),
11756            endpoint: Some("/x".into()),
11757            subject: Some("not.allowed.here".into()),
11758            slot: None,
11759        });
11760        let err = s.validate().unwrap_err();
11761        assert!(matches!(
11762            err,
11763            AplicacaoError::ContratoWrongTarget {
11764                expected: WitTarget::HTTP_FIELD_NAME,
11765                ..
11766            }
11767        ));
11768    }
11769
11770    #[test]
11771    fn rejects_pubsub_contrato_without_subject() {
11772        let mut s = three_member_spec();
11773        s.contratos.push(WitContract {
11774            de: "cart".into(),
11775            para: "catalog".into(),
11776            wit: "nats:pub-sub".into(),
11777            endpoint: None,
11778            subject: None,
11779            slot: None,
11780        });
11781        let err = s.validate().unwrap_err();
11782        assert!(matches!(
11783            err,
11784            AplicacaoError::ContratoMissingTarget {
11785                expected: WitTarget::PUBSUB_FIELD_NAME,
11786                ..
11787            }
11788        ));
11789    }
11790
11791    #[test]
11792    fn rejects_pubsub_contrato_with_endpoint() {
11793        let mut s = three_member_spec();
11794        s.contratos.push(WitContract {
11795            de: "cart".into(),
11796            para: "catalog".into(),
11797            wit: "kafka:topic".into(),
11798            endpoint: Some("/wrong".into()),
11799            subject: Some("topic.x".into()),
11800            slot: None,
11801        });
11802        let err = s.validate().unwrap_err();
11803        assert!(matches!(
11804            err,
11805            AplicacaoError::ContratoWrongTarget {
11806                expected: WitTarget::PUBSUB_FIELD_NAME,
11807                ..
11808            }
11809        ));
11810    }
11811
11812    #[test]
11813    fn rejects_store_contrato_without_slot() {
11814        let mut s = three_member_spec();
11815        s.contratos.push(WitContract {
11816            de: "cart".into(),
11817            para: "catalog".into(),
11818            wit: "wasi:keyvalue/store".into(),
11819            endpoint: None,
11820            subject: None,
11821            slot: None,
11822        });
11823        let err = s.validate().unwrap_err();
11824        assert!(matches!(
11825            err,
11826            AplicacaoError::ContratoMissingTarget {
11827                expected: WitTarget::STORE_FIELD_NAME,
11828                ..
11829            }
11830        ));
11831    }
11832
11833    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
11834
11835    #[test]
11836    fn rejects_http_contrato_with_empty_endpoint() {
11837        // `Some("")` for an HTTP endpoint passes the presence check
11838        // (target() previously returned WitTarget::Http { endpoint: "" })
11839        // but renders as a `path: ""` Cilium L7 rule that matches no
11840        // traffic. Same value-shape footgun closed for :entrada :paths
11841        // entries (eb3456d).
11842        let mut s = three_member_spec();
11843        s.contratos.push(WitContract {
11844            de: "cart".into(),
11845            para: "catalog".into(),
11846            wit: "wasi:http/proxy".into(),
11847            endpoint: Some(String::new()),
11848            subject: None,
11849            slot: None,
11850        });
11851        let err = s.validate().unwrap_err();
11852        assert!(
11853            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
11854                if de == "cart" && para == "catalog"),
11855            "got {err:?}"
11856        );
11857    }
11858
11859    #[test]
11860    fn rejects_http_contrato_with_relative_endpoint() {
11861        // Cilium L7 :path + Gateway API PathPrefix both require a
11862        // leading `/`. Same shape required of :entrada :paths
11863        // (eb3456d). Lifted into target() so every consumer of the
11864        // typed WitTarget view inherits the guarantee.
11865        let mut s = three_member_spec();
11866        s.contratos.push(WitContract {
11867            de: "cart".into(),
11868            para: "catalog".into(),
11869            wit: "wasi:http/proxy".into(),
11870            endpoint: Some("products/:id".into()),
11871            subject: None,
11872            slot: None,
11873        });
11874        let err = s.validate().unwrap_err();
11875        assert!(
11876            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
11877                if endpoint == "products/:id"),
11878            "got {err:?}"
11879        );
11880    }
11881
11882    #[test]
11883    fn rejects_pubsub_contrato_with_empty_subject() {
11884        // NATS / Kafka publish without a subject is a no-op subscribe;
11885        // never the author's intent. Same empty-string rejection as
11886        // :membros :caixa, :placement :clusters entries, :entrada
11887        // :paths entries — every value carried by every typed slot is
11888        // value-shape-checked at validate().
11889        let mut s = three_member_spec();
11890        s.contratos.push(WitContract {
11891            de: "cart".into(),
11892            para: "catalog".into(),
11893            wit: "nats:pub-sub".into(),
11894            endpoint: None,
11895            subject: Some(String::new()),
11896            slot: None,
11897        });
11898        let err = s.validate().unwrap_err();
11899        assert!(
11900            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
11901                if de == "cart" && para == "catalog"),
11902            "got {err:?}"
11903        );
11904    }
11905
11906    #[test]
11907    fn rejects_store_contrato_with_empty_slot() {
11908        // An empty slot template addresses the bucket root, defeating
11909        // the per-key isolation the slot exists for — a footgun on
11910        // `wasi:keyvalue/store` whose closest analog is the empty
11911        // shard-key rejected on :placement Sharded (c7c7799).
11912        let mut s = three_member_spec();
11913        s.contratos.push(WitContract {
11914            de: "cart".into(),
11915            para: "catalog".into(),
11916            wit: "wasi:keyvalue/store".into(),
11917            endpoint: None,
11918            subject: None,
11919            slot: Some(String::new()),
11920        });
11921        let err = s.validate().unwrap_err();
11922        assert!(
11923            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
11924                if de == "cart" && para == "catalog"),
11925            "got {err:?}"
11926        );
11927    }
11928
11929    #[test]
11930    fn http_contrato_root_endpoint_validates() {
11931        // Pin the boundary case: a single-`/` endpoint is the catch-all
11932        // form the Gateway HTTPRoute renderer falls back to when
11933        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
11934        // must remain a valid contrato endpoint too.
11935        let mut s = three_member_spec();
11936        s.contratos.push(contract_http("cart", "catalog", "/"));
11937        s.validate().unwrap();
11938    }
11939
11940    // ── :contratos :endpoint value-shape gate ────────────────────────────
11941    //
11942    // Mirrors the `:entrada :paths` value-shape suite on the peer
11943    // HTTP-path axis. Until this gate landed `WitContract::target()`
11944    // only refused the empty string + the missing-leading-`/` form
11945    // (c4213a4); a structurally invalid endpoint passed validate and
11946    // landed verbatim as a Cilium L7 `path:` rule
11947    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
11948    // traffic or was rejected at apply time by Cilium policy admission.
11949    // Every authoring footgun the K8s Gateway API webhook / Cilium
11950    // policy validator would catch on admission now becomes a caixa-
11951    // build-time `ContratoEndpointInvalid` with the offending
11952    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
11953    // shape as `EntradaPathInvalid` on the sibling axis; same shared
11954    // predicate (`crate::render::is_gateway_api_http_path`) ensures
11955    // drift between the two axes' rule enforcement is a build error
11956    // at the predicate.
11957
11958    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
11959        // Fresh spec per call so the would-be-duplicate edge
11960        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
11961        // `three_member_spec`'s pre-existing
11962        // `(cart, catalog, …, /products/:id)` entry — only the
11963        // endpoint payload differs.
11964        let mut s = three_member_spec();
11965        s.contratos.push(contract_http("cart", "catalog", ep));
11966        s.validate().unwrap_err()
11967    }
11968
11969    #[test]
11970    fn rejects_http_contrato_endpoint_with_query() {
11971        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
11972        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
11973        // rule the L7 matcher would never satisfy.
11974        let err = contrato_endpoint_err("/charge?token=X");
11975        assert!(
11976            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11977                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
11978            "got {err:?}"
11979        );
11980    }
11981
11982    #[test]
11983    fn rejects_http_contrato_endpoint_with_fragment() {
11984        let err = contrato_endpoint_err("/charge#frag");
11985        assert!(
11986            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11987                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
11988            "got {err:?}"
11989        );
11990    }
11991
11992    #[test]
11993    fn rejects_http_contrato_endpoint_with_whitespace() {
11994        let err = contrato_endpoint_err("/foo bar");
11995        assert!(
11996            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
11997                if endpoint == "/foo bar" && reason.contains("whitespace")),
11998            "got {err:?}"
11999        );
12000    }
12001
12002    #[test]
12003    fn rejects_http_contrato_endpoint_with_control_char() {
12004        let err = contrato_endpoint_err("/api/\x01bar");
12005        assert!(
12006            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12007                if endpoint == "/api/\x01bar" && reason.contains("control character")),
12008            "got {err:?}"
12009        );
12010    }
12011
12012    #[test]
12013    fn rejects_http_contrato_endpoint_with_non_ascii() {
12014        let err = contrato_endpoint_err("/api/café");
12015        assert!(
12016            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12017                if endpoint == "/api/café" && reason.contains("non-ASCII")),
12018            "got {err:?}"
12019        );
12020    }
12021
12022    #[test]
12023    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
12024        let err = contrato_endpoint_err("/api//cart");
12025        assert!(
12026            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12027                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
12028            "got {err:?}"
12029        );
12030    }
12031
12032    #[test]
12033    fn rejects_http_contrato_endpoint_with_dot_segment() {
12034        let err = contrato_endpoint_err("/api/./cart");
12035        assert!(
12036            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12037                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
12038            "got {err:?}"
12039        );
12040    }
12041
12042    #[test]
12043    fn rejects_http_contrato_endpoint_with_parent_segment() {
12044        // Path-traversal in a contrato endpoint is the canonical
12045        // "L7 rule that the workload's HTTP server's path-resolution
12046        // logic interprets differently than the policy enforcer"
12047        // footgun. Rejected outright at validate time.
12048        let err = contrato_endpoint_err("/api/../etc");
12049        assert!(
12050            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12051                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
12052            "got {err:?}"
12053        );
12054    }
12055
12056    #[test]
12057    fn rejects_http_contrato_endpoint_too_long() {
12058        // 1025-byte endpoint — one over the Gateway API
12059        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
12060        // path matcher has no inherent length limit but the policy
12061        // CR itself rides through the K8s apiserver, which enforces
12062        // ConfigMap-shaped limits; sharing the Gateway API cap is the
12063        // conservative floor.
12064        let big = format!("/api/{}", "a".repeat(1020));
12065        assert_eq!(big.len(), 1025);
12066        let err = contrato_endpoint_err(&big);
12067        assert!(
12068            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12069                if endpoint == &big && reason.contains("max length of 1024")),
12070            "got {err:?}"
12071        );
12072    }
12073
12074    #[test]
12075    fn http_contrato_endpoint_max_length_validates() {
12076        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
12077        // in the cap surfaces here and at
12078        // `rejects_http_contrato_endpoint_too_long` simultaneously,
12079        // mirroring `entrada_path_max_length_validates` on the peer
12080        // axis.
12081        let big = format!("/api/{}", "a".repeat(1019));
12082        assert_eq!(big.len(), 1024);
12083        let mut s = three_member_spec();
12084        s.contratos.push(contract_http("cart", "catalog", &big));
12085        s.validate().unwrap();
12086    }
12087
12088    #[test]
12089    fn http_contrato_endpoint_accepts_canonical_forms() {
12090        // Positive-set sweep: every canonical HTTP-path shape the
12091        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
12092        // plain paths, hidden-file-style `.config` segments distinct
12093        // from the `.` segment, digit-bearing segments, the canonical
12094        // route-template `:param` form, trailing-slash form,
12095        // percent-encoded segments, the `/foo..bar` interior-`..`-
12096        // substring forms that are NOT `..` segments) must remain a
12097        // valid contrato endpoint too. Drift between this list and
12098        // the entrada path positive sweep surfaces at the shared
12099        // `is_gateway_api_http_path` substrate-side suite — one
12100        // source of truth. Uses a fresh `(payment, catalog)` edge so
12101        // none of the swept endpoints collide with the pre-existing
12102        // `(cart, catalog, /products/:id)` / `(cart, payment,
12103        // /charge)` entries in `three_member_spec`.
12104        for ep in [
12105            "/",
12106            "/charge",
12107            "/v1/charge",
12108            "/api/.config",
12109            "/products/:id",
12110            "/api/cart/",
12111            "/api/caf%C3%A9",
12112            "/foo..bar",
12113            "/...",
12114        ] {
12115            let mut s = three_member_spec();
12116            s.contratos.push(contract_http("payment", "catalog", ep));
12117            s.validate()
12118                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
12119        }
12120    }
12121
12122    #[test]
12123    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
12124        // Ordering pin: `ContratoEndpointEmpty` is the more self-
12125        // locating diagnostic on `""` and must lead — the value-
12126        // shape gate is only reached after the empty-check fires.
12127        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
12128        // on the peer axis.
12129        let mut s = three_member_spec();
12130        s.contratos.push(WitContract {
12131            de: "cart".into(),
12132            para: "catalog".into(),
12133            wit: "wasi:http/proxy".into(),
12134            endpoint: Some(String::new()),
12135            subject: None,
12136            slot: None,
12137        });
12138        let err = s.validate().unwrap_err();
12139        assert!(
12140            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12141            "got {err:?}"
12142        );
12143    }
12144
12145    #[test]
12146    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
12147        // Ordering pin: an endpoint without a leading `/` surfaces the
12148        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
12149        // value-shape gate is only consulted on endpoints that already
12150        // satisfy the absolute-prefix invariant. Mirrors
12151        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
12152        let err = contrato_endpoint_err("bad path");
12153        assert!(
12154            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12155                if endpoint == "bad path"),
12156            "got {err:?}"
12157        );
12158    }
12159
12160    #[test]
12161    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
12162        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
12163        // `:para` + a non-empty reason flow through verbatim so the
12164        // author can grep their caixa.lisp for the offending contrato
12165        // block and fix it in one edit. Same shape as
12166        // `entrada_path_diagnostic_carries_offending_path`.
12167        let err = contrato_endpoint_err("/api?q=1");
12168        match err {
12169            AplicacaoError::ContratoEndpointInvalid {
12170                de,
12171                para,
12172                endpoint,
12173                reason,
12174            } => {
12175                assert_eq!(de, "cart");
12176                assert_eq!(para, "catalog");
12177                assert_eq!(endpoint, "/api?q=1");
12178                assert!(!reason.is_empty(), "reason field must be non-empty");
12179            }
12180            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
12181        }
12182    }
12183
12184    #[test]
12185    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
12186        // The compounding theorem: every &str inside a WitTarget
12187        // returned by target() is non-empty (and absolute, for Http).
12188        // Renderers downstream of typed_view() can rely on this
12189        // without re-checking — the type system carries the proof.
12190        let http = contract_http("cart", "catalog", "/x");
12191        match http.target().unwrap() {
12192            WitTarget::Http { endpoint } => {
12193                assert!(!endpoint.is_empty());
12194                assert!(endpoint.starts_with('/'));
12195            }
12196            other => panic!("expected Http, got {other:?}"),
12197        }
12198        let nats = WitContract {
12199            de: "a".into(),
12200            para: "b".into(),
12201            wit: "nats:pub-sub".into(),
12202            endpoint: None,
12203            subject: Some("topic.x".into()),
12204            slot: None,
12205        };
12206        match nats.target().unwrap() {
12207            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
12208            other => panic!("expected PubSub, got {other:?}"),
12209        }
12210        let kv = WitContract {
12211            de: "a".into(),
12212            para: "b".into(),
12213            wit: "wasi:keyvalue/store".into(),
12214            endpoint: None,
12215            subject: None,
12216            slot: Some("checkout/$orderId".into()),
12217        };
12218        match kv.target().unwrap() {
12219            WitTarget::Store { slot } => assert!(!slot.is_empty()),
12220            other => panic!("expected Store, got {other:?}"),
12221        }
12222    }
12223
12224    #[test]
12225    fn target_diagnostic_names_offending_endpoint_value() {
12226        // When the malformed endpoint string is non-trivial, the
12227        // diagnostic carries the actual value back to the author —
12228        // not a generic "endpoint malformed" error.
12229        let bad = WitContract {
12230            de: "src".into(),
12231            para: "dst".into(),
12232            wit: "wasi:http/proxy".into(),
12233            endpoint: Some("api/v1/charge".into()),
12234            subject: None,
12235            slot: None,
12236        };
12237        match bad.target().unwrap_err() {
12238            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
12239                assert_eq!(de, "src");
12240                assert_eq!(para, "dst");
12241                assert_eq!(endpoint, "api/v1/charge");
12242            }
12243            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
12244        }
12245    }
12246
12247    #[test]
12248    fn rejects_unknown_wit_with_target_set() {
12249        let mut s = three_member_spec();
12250        s.contratos.push(WitContract {
12251            de: "cart".into(),
12252            para: "catalog".into(),
12253            wit: "custom:exchange".into(),
12254            endpoint: Some("/leaked".into()),
12255            subject: None,
12256            slot: None,
12257        });
12258        let err = s.validate().unwrap_err();
12259        assert!(matches!(
12260            err,
12261            AplicacaoError::ContratoWrongTarget {
12262                expected: WitTarget::CAPABILITY_EXPECTED,
12263                ..
12264            }
12265        ));
12266    }
12267
12268    #[test]
12269    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
12270        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
12271        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
12272        // fourth arm of the same "which payload field name goes in the
12273        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
12274        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12275        // consts cover on the peer HTTP / PubSub / Store arms
12276        // (`wit_target_field_name_pins_per_variant`). Until this lift
12277        // landed the byte-string sat twice — once inline in the
12278        // [`WitContract::target`] Capability-arm rejection at the
12279        // production dispatch, once in `rejects_unknown_wit_with_target_set`
12280        // pinning against the same literal — with no compile-time link
12281        // between them. Same "one canonical declaration, next to the
12282        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
12283        // lift established for the payload-less arm's human-readable
12284        // label axis; this test is the shape peer of
12285        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
12286        // pair (routes-through-const + scalar-value pin) on the
12287        // wrong-target diagnostic-scalar axis.
12288        //
12289        // Fail-before-pass-after was verified locally by mutating the
12290        // const declaration to `"capability"` — the scalar-value pin
12291        // below fires (`"capability" != "none"`) and the routes-through
12292        // assertion below still holds (production and const walk in
12293        // lockstep), which is the correct behavior: a rename on the
12294        // const drifts here first, not at a downstream consumer.
12295        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
12296
12297        let mut s = three_member_spec();
12298        s.contratos.push(WitContract {
12299            de: "cart".into(),
12300            para: "catalog".into(),
12301            wit: "custom:exchange".into(),
12302            endpoint: Some("/leaked".into()),
12303            subject: None,
12304            slot: None,
12305        });
12306        match s.validate().unwrap_err() {
12307            AplicacaoError::ContratoWrongTarget { expected, .. } => {
12308                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
12309            }
12310            other => panic!("expected ContratoWrongTarget, got {other:?}"),
12311        }
12312    }
12313
12314    #[test]
12315    fn unknown_wit_capability_only_validates() {
12316        let mut s = three_member_spec();
12317        s.contratos.push(WitContract {
12318            de: "cart".into(),
12319            para: "catalog".into(),
12320            // A WIT world we haven't yet shaped — accept it as a typed
12321            // capability edge so authors aren't blocked while the WIT
12322            // registry catches up. No payload field may be carried.
12323            wit: "custom:exchange".into(),
12324            endpoint: None,
12325            subject: None,
12326            slot: None,
12327        });
12328        s.validate().unwrap();
12329        let added = s.contratos.last().unwrap();
12330        assert_eq!(added.target().unwrap(), WitTarget::Capability);
12331    }
12332
12333    #[test]
12334    fn target_typed_view_round_trips_each_shape() {
12335        let http = contract_http("cart", "catalog", "/products/:id");
12336        assert_eq!(
12337            http.target().unwrap(),
12338            WitTarget::Http {
12339                endpoint: "/products/:id"
12340            }
12341        );
12342        let nats = WitContract {
12343            de: "a".into(),
12344            para: "b".into(),
12345            wit: "nats:pub-sub".into(),
12346            endpoint: None,
12347            subject: Some("topic.x".into()),
12348            slot: None,
12349        };
12350        assert_eq!(
12351            nats.target().unwrap(),
12352            WitTarget::PubSub { subject: "topic.x" }
12353        );
12354        let kv = WitContract {
12355            de: "a".into(),
12356            para: "b".into(),
12357            wit: "wasi:keyvalue/store".into(),
12358            endpoint: None,
12359            subject: None,
12360            slot: Some("checkout/$orderId".into()),
12361        };
12362        assert_eq!(
12363            kv.target().unwrap(),
12364            WitTarget::Store {
12365                slot: "checkout/$orderId"
12366            }
12367        );
12368    }
12369
12370    #[test]
12371    fn wit_contract_kind_predicates() {
12372        let http = contract_http("a", "b", "/x");
12373        assert!(http.is_http());
12374        assert!(!http.is_pubsub());
12375        assert!(!http.is_store());
12376        assert!(!http.is_capability());
12377
12378        let nats = WitContract {
12379            de: "a".into(),
12380            para: "b".into(),
12381            wit: "nats:pub-sub".into(),
12382            endpoint: None,
12383            subject: Some("topic.x".into()),
12384            slot: None,
12385        };
12386        assert!(nats.is_pubsub());
12387        assert!(!nats.is_http());
12388        assert!(!nats.is_capability());
12389
12390        let kv = WitContract {
12391            de: "a".into(),
12392            para: "b".into(),
12393            wit: "wasi:keyvalue/store".into(),
12394            endpoint: None,
12395            subject: None,
12396            slot: Some("checkout/$orderId".into()),
12397        };
12398        assert!(kv.is_store());
12399        assert!(!kv.is_http());
12400        assert!(!kv.is_capability());
12401
12402        // Fourth arm on the paired closed-set predicate family: the
12403        // payload-less capability edge that projects to the payload-
12404        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
12405        // Extends the 3-arm predicate sweep this test opened to cover
12406        // the closed 4-way partition [`WitContract::is_capability`]
12407        // closes on the pre-projection WIT-shape axis, matched with the
12408        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
12409        // 4-arm predicate set.
12410        let cap = WitContract {
12411            de: "a".into(),
12412            para: "b".into(),
12413            wit: "custom:capability-only".into(),
12414            endpoint: None,
12415            subject: None,
12416            slot: None,
12417        };
12418        assert!(cap.is_capability());
12419        assert!(!cap.is_http());
12420        assert!(!cap.is_pubsub());
12421        assert!(!cap.is_store());
12422    }
12423
12424    // ── :contratos :wit value-shape gate ─────────────────────────────────
12425    //
12426    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
12427    // dispatch-discriminator axis. Until this gate landed
12428    // `WitContract::target()` accepted any non-empty string and
12429    // silently demoted unrecognized shapes to a capability-only L4
12430    // edge — the canonical "I thought I had L7 HTTP routing, got
12431    // L4-only" footgun. Every authoring footgun the WIT registry's
12432    // own grammar rejects (uppercase, hyphen-for-colon typo,
12433    // whitespace, empty package, doubled `@`, …) now becomes a
12434    // caixa-build-time `ContratoWitInvalid` with the offending
12435    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
12436    // as `ContratoEndpointInvalid` on the sibling axis; same shared
12437    // predicate (`crate::render::is_wit_world_ref`) ensures drift
12438    // between any two axes' rule enforcement is a build error at the
12439    // predicate, not piecemeal across renderers.
12440
12441    fn contrato_wit_err(wit: &str) -> AplicacaoError {
12442        // Fresh spec per call so the new contract doesn't collide on
12443        // identity with `three_member_spec`'s pre-existing entries.
12444        // The new edge uses `(payment, catalog)` — a pair the fixture
12445        // doesn't already declare — with no payload field set, so the
12446        // wit-shape gate fires before any payload-shape arm.
12447        let mut s = three_member_spec();
12448        s.contratos.push(WitContract {
12449            de: "payment".into(),
12450            para: "catalog".into(),
12451            wit: wit.into(),
12452            endpoint: None,
12453            subject: None,
12454            slot: None,
12455        });
12456        s.validate().unwrap_err()
12457    }
12458
12459    #[test]
12460    fn rejects_wit_with_uppercase_namespace() {
12461        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
12462        // didn't match the lowercase `wasi:http/` prefix is_http() keys
12463        // off, so the dispatch fell through to the capability arm and
12464        // the contract silently rendered as an L4-only Cilium edge.
12465        // The new gate surfaces the uppercase typo at validate time
12466        // with the offending `:wit` named.
12467        let err = contrato_wit_err("WASI:http/proxy");
12468        assert!(
12469            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12470                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
12471            "got {err:?}"
12472        );
12473    }
12474
12475    #[test]
12476    fn rejects_wit_with_hyphen_for_colon_typo() {
12477        // The canonical "I forgot the `:` separator" typo — pre-gate
12478        // this passed as Capability silently, so the renderer emitted
12479        // an L4-only policy where the author expected L7 HTTP rules.
12480        let err = contrato_wit_err("wasi-http/proxy");
12481        assert!(
12482            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12483                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
12484            "got {err:?}"
12485        );
12486    }
12487
12488    #[test]
12489    fn rejects_wit_with_multiple_colons() {
12490        // Doubled `:` — the namespace/package split has nowhere to
12491        // anchor, so the dispatch silently demotes to Capability.
12492        let err = contrato_wit_err("wasi:http:proxy");
12493        assert!(
12494            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12495                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
12496            "got {err:?}"
12497        );
12498    }
12499
12500    #[test]
12501    fn rejects_wit_with_empty_package() {
12502        // `wasi:` — namespace alone with no package. Pre-gate this
12503        // failed neither the is_http nor is_pubsub nor is_store
12504        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
12505        // a bare `wasi:`), so it silently demoted to Capability.
12506        let err = contrato_wit_err("wasi:");
12507        assert!(
12508            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12509                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
12510            "got {err:?}"
12511        );
12512    }
12513
12514    #[test]
12515    fn rejects_wit_with_underscore() {
12516        // Underscore — WIT identifiers are kebab-case, same rule
12517        // DNS-1123 enforces on its peer axes. The diagnostic carries
12518        // the explicit "use `-` instead" remediation.
12519        let err = contrato_wit_err("wasi:http_proxy");
12520        assert!(
12521            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12522                if wit == "wasi:http_proxy" && reason.contains('_')),
12523            "got {err:?}"
12524        );
12525    }
12526
12527    #[test]
12528    fn rejects_wit_with_whitespace() {
12529        // Whitespace mid-token — the prefix check matches but the
12530        // package-and-onward parse silently demoted to Capability.
12531        let err = contrato_wit_err("wasi:http proxy");
12532        assert!(
12533            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12534                if wit == "wasi:http proxy" && reason.contains("whitespace")),
12535            "got {err:?}"
12536        );
12537    }
12538
12539    #[test]
12540    fn rejects_wit_with_non_ascii() {
12541        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12542        // the package name from a doc with smart quotes / accented
12543        // characters" footgun.
12544        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
12545        assert!(
12546            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12547                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
12548            "got {err:?}"
12549        );
12550    }
12551
12552    #[test]
12553    fn rejects_wit_with_consecutive_hyphens() {
12554        // `pub--sub` — WIT identifiers join words with single hyphens.
12555        let err = contrato_wit_err("nats:pub--sub");
12556        assert!(
12557            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12558                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
12559            "got {err:?}"
12560        );
12561    }
12562
12563    #[test]
12564    fn rejects_wit_with_trailing_at_no_version() {
12565        // `wasi:http/proxy@` — the version-suffix author started to
12566        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
12567        // parser would reject this; surface it at validate time.
12568        let err = contrato_wit_err("wasi:http/proxy@");
12569        assert!(
12570            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12571                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
12572            "got {err:?}"
12573        );
12574    }
12575
12576    #[test]
12577    fn rejects_wit_too_long() {
12578        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
12579        // The legitimate-shape arms all pass (lowercase, single `:`,
12580        // kebab-case identifiers); only the cap arm fires. Surfaces
12581        // the paste-from-binary / accidental-multi-line-blob landing
12582        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12583        // on the peer axis.
12584        let big = format!("wasi:{}", "a".repeat(124));
12585        assert_eq!(big.len(), 129);
12586        let err = contrato_wit_err(&big);
12587        assert!(
12588            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12589                if wit == &big && reason.contains("max length of 128")),
12590            "got {err:?}"
12591        );
12592    }
12593
12594    #[test]
12595    fn wit_max_length_validates() {
12596        // 128-byte WIT reference — exactly the cap. Boundary pin:
12597        // drift in the cap surfaces here and at `rejects_wit_too_long`
12598        // simultaneously, mirroring
12599        // `http_contrato_endpoint_max_length_validates` on the peer
12600        // axis.
12601        let big = format!("wasi:{}", "a".repeat(123));
12602        assert_eq!(big.len(), 128);
12603        let mut s = three_member_spec();
12604        s.contratos.push(WitContract {
12605            de: "payment".into(),
12606            para: "catalog".into(),
12607            wit: big,
12608            endpoint: None,
12609            subject: None,
12610            slot: None,
12611        });
12612        s.validate().unwrap();
12613    }
12614
12615    #[test]
12616    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
12617        // Positive-set sweep through the AplicacaoSpec::validate
12618        // surface (rather than the substrate-side predicate directly)
12619        // — pins every shape the existing test fixtures + the
12620        // checkout-aplicacao example carry, so the gate's accept-set
12621        // matches the substrate's emit-set. Drift between this list
12622        // and `render::tests::wit_world_ref_accepts_canonical_forms`
12623        // surfaces at the substrate layer's positive sweep — one
12624        // source of truth for the rule.
12625        for wit in [
12626            "wasi:http/proxy",
12627            "wasi:keyvalue/store",
12628            "nats:pub-sub",
12629            "kafka:topic",
12630            "custom:exchange",
12631            "pleme:cap/audit",
12632            "wasi:http/proxy@0.2.0",
12633        ] {
12634            // Payload field paired to the dispatched WIT shape so the
12635            // shape-↔-target arm doesn't fire instead of the wit-shape
12636            // arm we're exercising. Routes off the same
12637            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
12638            // `wit_shape_is_store` free functions the production
12639            // `WitContract::is_http` / `is_pubsub` / `is_store`
12640            // methods delegate to (both consult the lifted
12641            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
12642            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
12643            // future prefix addition to the routing accept-set
12644            // reaches this test's payload-dispatch arm by
12645            // construction — no per-test-site drift can hide a
12646            // shape-→-target-slot mismatch that would silently
12647            // demote a canonical `:wit` value to the
12648            // `(None, None, None)` capability-only arm and let the
12649            // `AplicacaoSpec::validate` positive sweep pass on a
12650            // shape it should exercise as HTTP / pub-sub / store.
12651            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
12652                (Some("/x".into()), None, None)
12653            } else if wit_shape_is_pubsub(wit) {
12654                (None, Some("topic.x".into()), None)
12655            } else if wit_shape_is_store(wit) {
12656                (None, None, Some("bucket/$key".into()))
12657            } else {
12658                (None, None, None)
12659            };
12660            let mut s = three_member_spec();
12661            s.contratos.push(WitContract {
12662                de: "payment".into(),
12663                para: "catalog".into(),
12664                wit: wit.into(),
12665                endpoint,
12666                subject,
12667                slot,
12668            });
12669            s.validate()
12670                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
12671        }
12672    }
12673
12674    #[test]
12675    fn wit_shape_predicates_accept_canonical_prefix_set() {
12676        // Positive-set sweep pinning every prefix in
12677        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
12678        // WIT_STORE_SHAPE_PREFIXES against the three free-function
12679        // dispatch predicates. The six prefixes are the load-bearing
12680        // routing keys the substrate's WIT-shape dispatch consults
12681        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
12682        // key/value-store-slot admission); any drift between the
12683        // free-function accept-set and this list surfaces here
12684        // rather than at apply time as a silent
12685        // shape-→-capability-only demotion.
12686        assert!(wit_shape_is_http("wasi:http/proxy"));
12687        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
12688        assert!(wit_shape_is_http("http:incoming"));
12689
12690        assert!(wit_shape_is_pubsub("nats:pub-sub"));
12691        assert!(wit_shape_is_pubsub("kafka:topic"));
12692
12693        assert!(wit_shape_is_store("wasi:keyvalue/store"));
12694        assert!(wit_shape_is_store("kv:cache/session"));
12695    }
12696
12697    #[test]
12698    fn wit_shape_predicates_reject_uncanonical_forms() {
12699        // Negative-set pin: the six canonical prefixes are
12700        // lowercase-only (mirrors the `is_wit_world_ref` substrate
12701        // predicate's lowercase invariant — see its docstring on the
12702        // "I thought I had L7 HTTP routing, got L4-only" footgun).
12703        // The empty string, an uppercase-prefixed form, a hyphen-
12704        // instead-of-colon typo, and a bare kebab identifier all miss
12705        // every shape arm — reachable-by-construction only via the
12706        // `is_wit_world_ref` gate that admission-checks the `:wit`
12707        // value first, but pinned here so any future
12708        // free-function change (e.g. a case-insensitive
12709        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
12710        // this unit level.
12711        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
12712            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
12713            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
12714            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
12715        }
12716    }
12717
12718    #[test]
12719    fn wit_shape_predicates_partition_canonical_set() {
12720        // Every canonical prefix routes to exactly one shape arm —
12721        // the three prefix sets are pairwise disjoint. Pins the
12722        // routing property [`WitContract::target`] relies on: an
12723        // `is_http()` return of `true` guarantees `is_pubsub()` and
12724        // `is_store()` return `false`, so the shape-→-target-slot
12725        // dispatch (endpoint vs subject vs slot) is unambiguous.
12726        // Drift (e.g. a future `"kv:"` moved into the HTTP set
12727        // without removal from the store set) would silently route
12728        // one prefix to two arms and the first-matching-arm order
12729        // becomes load-bearing — this pin surfaces it as a build
12730        // error instead.
12731        for prefix in WIT_HTTP_SHAPE_PREFIXES {
12732            let sample = format!("{prefix}x");
12733            assert!(wit_shape_is_http(&sample));
12734            assert!(!wit_shape_is_pubsub(&sample));
12735            assert!(!wit_shape_is_store(&sample));
12736        }
12737        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
12738            let sample = format!("{prefix}x");
12739            assert!(!wit_shape_is_http(&sample));
12740            assert!(wit_shape_is_pubsub(&sample));
12741            assert!(!wit_shape_is_store(&sample));
12742        }
12743        for prefix in WIT_STORE_SHAPE_PREFIXES {
12744            let sample = format!("{prefix}x");
12745            assert!(!wit_shape_is_http(&sample));
12746            assert!(!wit_shape_is_pubsub(&sample));
12747            assert!(wit_shape_is_store(&sample));
12748        }
12749    }
12750
12751    #[test]
12752    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
12753        // Positive pin: [`wit_shape_matches`] is exactly the
12754        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
12755        // parameterized on the accept-set. Two-prefix accept-set,
12756        // one-prefix accept-set, and empty accept-set (which must
12757        // reject everything, including the empty string — an empty
12758        // `any()` fold returns `false`) all pinned so a future
12759        // reimplementation that swaps `starts_with` for `contains`,
12760        // `==`, or a case-folded comparator surfaces at unit-test
12761        // time.
12762        let two = &["wasi:http/", "http:"];
12763        assert!(wit_shape_matches("wasi:http/proxy", two));
12764        assert!(wit_shape_matches("http:incoming", two));
12765        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
12766
12767        let one = &["nats:"];
12768        assert!(wit_shape_matches("nats:pub-sub", one));
12769        assert!(!wit_shape_matches("kafka:topic", one));
12770
12771        // Empty accept-set matches nothing — the identity element
12772        // for the disjunctive `any()` fold across the prefix set.
12773        // Reachable via a future `wit_shape_is_<name>` const paired
12774        // to a still-empty prefix table on a nascent shape-arm draft.
12775        let empty: &[&str] = &[];
12776        assert!(!wit_shape_matches("wasi:http/proxy", empty));
12777        assert!(!wit_shape_matches("", empty));
12778
12779        // starts_with, not contains: a prefix embedded mid-string
12780        // never matches. Pins the routing invariant [`WitContract::target`]
12781        // relies on (an authored `:wit "custom:wasi:http/"` string
12782        // does not silently route through the HTTP arm just because
12783        // it happens to contain the canonical HTTP prefix).
12784        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
12785    }
12786
12787    #[test]
12788    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
12789        // Equivalence pin: each per-shape predicate is exactly
12790        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
12791        // every canonical prefix + the empty string + one negative
12792        // sample against every peer so a future predicate that grew
12793        // its own inline `iter().any(starts_with)` (rather than
12794        // delegating through the lifted combinator) drifts loudly here
12795        // — the peer-const table's contents must agree with the
12796        // predicate's accept-set by construction.
12797        let samples = [
12798            String::new(),
12799            "wasi:http/proxy".to_string(),
12800            "http:incoming".to_string(),
12801            "nats:pub-sub".to_string(),
12802            "kafka:topic".to_string(),
12803            "wasi:keyvalue/store".to_string(),
12804            "kv:cache/session".to_string(),
12805            "custom-shape".to_string(),
12806            "WASI:HTTP/proxy".to_string(),
12807        ];
12808        for wit in &samples {
12809            assert_eq!(
12810                wit_shape_is_http(wit),
12811                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
12812                "wit_shape_is_http drifted from combinator on {wit:?}",
12813            );
12814            assert_eq!(
12815                wit_shape_is_pubsub(wit),
12816                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
12817                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
12818            );
12819            assert_eq!(
12820                wit_shape_is_store(wit),
12821                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
12822                "wit_shape_is_store drifted from combinator on {wit:?}",
12823            );
12824        }
12825    }
12826
12827    #[test]
12828    fn wit_contract_shape_methods_delegate_to_free_functions() {
12829        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
12830        // `is_store` are `&self` conveniences on top of the free
12831        // functions — for every canonical prefix the method's return
12832        // matches its free-function peer. Sweeps the union of the
12833        // three prefix sets so a future method that grew its own
12834        // inline prefix logic (rather than delegating) drifts loudly
12835        // here on the first prefix the free function accepts and the
12836        // method doesn't.
12837        for shape_set in [
12838            WIT_HTTP_SHAPE_PREFIXES,
12839            WIT_PUBSUB_SHAPE_PREFIXES,
12840            WIT_STORE_SHAPE_PREFIXES,
12841        ] {
12842            for prefix in shape_set {
12843                let c = WitContract {
12844                    de: "cart".into(),
12845                    para: "catalog".into(),
12846                    wit: format!("{prefix}x"),
12847                    endpoint: None,
12848                    subject: None,
12849                    slot: None,
12850                };
12851                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
12852                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
12853                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
12854                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
12855            }
12856        }
12857        // Capability-arm delegation sweep: two representative
12858        // Capability-shaped `:wit` values (a bare non-prefix-matching
12859        // WIT world, the deliberately-shaped empty string
12860        // [`WitContract::is_capability`]'s docstring calls out as
12861        // syntactically Capability). Extends the free-function
12862        // delegation pin onto the fourth arm so a future
12863        // [`WitContract::is_capability`] rewrite that grew an inline
12864        // prefix-set scan (rather than delegating through
12865        // [`wit_shape_is_capability`]) drifts loudly here on the first
12866        // Capability-shaped sample.
12867        for wit in ["custom:capability-only", ""] {
12868            let c = WitContract {
12869                de: "cart".into(),
12870                para: "catalog".into(),
12871                wit: wit.into(),
12872                endpoint: None,
12873                subject: None,
12874                slot: None,
12875            };
12876            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
12877        }
12878    }
12879
12880    #[test]
12881    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
12882        // 4-way partition-witness pin on the raw `&str` axis: for every
12883        // canonical prefix in the three payload-arm accept-sets,
12884        // exactly one of the four [`wit_shape_is_http`] /
12885        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
12886        // [`wit_shape_is_capability`] free functions returns `true` and
12887        // the other three return `false` — the four-arm partition
12888        // witness that locks the free-function WIT-shape-classifier
12889        // family into a partition of the `:contratos :wit` axis
12890        // load-bearing. Peer of the sibling [`WitContract`]-surface
12891        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
12892        // partition pin — extends the discipline onto the raw `&str`
12893        // axis so any future arm addition (a hypothetical
12894        // `wasi:sockets/*` transport-layer shape, an `oci:*`
12895        // capability-import carrier per the sibling
12896        // [`wit_shape_matches`] docstring's trajectory bullet) that
12897        // landed on one of the payload-arm free functions without
12898        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
12899        // here as two arms returning `true` simultaneously at
12900        // caixa-core build time rather than a silent per-consumer
12901        // misclassification at renderer emit time.
12902        for shape_set in [
12903            WIT_HTTP_SHAPE_PREFIXES,
12904            WIT_PUBSUB_SHAPE_PREFIXES,
12905            WIT_STORE_SHAPE_PREFIXES,
12906        ] {
12907            for prefix in shape_set {
12908                let wit = format!("{prefix}x");
12909                let hits = [
12910                    wit_shape_is_http(&wit),
12911                    wit_shape_is_pubsub(&wit),
12912                    wit_shape_is_store(&wit),
12913                    wit_shape_is_capability(&wit),
12914                ]
12915                .iter()
12916                .filter(|&&b| b)
12917                .count();
12918                assert_eq!(
12919                    hits,
12920                    1,
12921                    "raw-&str WIT-shape 4-way predicate partition must \
12922                     admit exactly one arm per canonical prefix; got {hits} \
12923                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
12924                     is_capability={})",
12925                    wit_shape_is_http(&wit),
12926                    wit_shape_is_pubsub(&wit),
12927                    wit_shape_is_store(&wit),
12928                    wit_shape_is_capability(&wit),
12929                );
12930            }
12931        }
12932        // Capability-arm sweep on the raw `&str` axis: two
12933        // representative Capability-shaped `:wit` values (a bare non-
12934        // prefix-matching WIT world, the deliberately-shaped empty
12935        // string the pure classifier still admits per
12936        // [`wit_shape_is_capability`]'s docstring). Both must land on
12937        // the fourth arm exclusively so the partition witness holds
12938        // across the full 4-arm closure on the raw `&str` axis.
12939        for wit in ["custom:capability-only", ""] {
12940            let hits = [
12941                wit_shape_is_http(wit),
12942                wit_shape_is_pubsub(wit),
12943                wit_shape_is_store(wit),
12944                wit_shape_is_capability(wit),
12945            ]
12946            .iter()
12947            .filter(|&&b| b)
12948            .count();
12949            assert_eq!(
12950                hits, 1,
12951                "raw-&str WIT-shape 4-way predicate partition must \
12952                 admit exactly one arm on Capability-shaped wit={wit:?}"
12953            );
12954            assert!(
12955                wit_shape_is_capability(wit),
12956                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
12957            );
12958        }
12959    }
12960
12961    #[test]
12962    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
12963        // Composition-witness pin: [`wit_shape_is_capability`] is the
12964        // exact-inverse disjunction of the sibling payload-arm free-
12965        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
12966        // / [`wit_shape_is_store`]. A future reimplementation that
12967        // grew its own prefix-set scan (e.g. inlining a fourth
12968        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
12969        // not own today) rather than delegating to the sibling trio
12970        // would drift loudly here — the composition contract binds the
12971        // fourth-arm free-function predicate to the exact-inverse of
12972        // the three payload-arm free-function predicates, so any
12973        // rebrand of any prefix-set const flows through
12974        // [`wit_shape_is_capability`] by construction without a
12975        // coordinated per-consumer rewrite. Peer of the sibling
12976        // [`WitContract`]-surface
12977        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
12978        // composition pin — extends the discipline onto the raw
12979        // `&str` axis.
12980        let mut cases: Vec<String> = Vec::new();
12981        for shape_set in [
12982            WIT_HTTP_SHAPE_PREFIXES,
12983            WIT_PUBSUB_SHAPE_PREFIXES,
12984            WIT_STORE_SHAPE_PREFIXES,
12985        ] {
12986            for prefix in shape_set {
12987                cases.push(format!("{prefix}x"));
12988            }
12989        }
12990        cases.push("custom:capability-only".to_string());
12991        cases.push(String::new());
12992        for wit in cases {
12993            assert_eq!(
12994                wit_shape_is_capability(&wit),
12995                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
12996                "wit_shape_is_capability must equal \
12997                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
12998                 at wit={wit:?}"
12999            );
13000        }
13001    }
13002
13003    #[test]
13004    fn wit_shape_classifier_family_is_const_fn() {
13005        // Fail-before-pass-after pin on the 4-arm free-function WIT-
13006        // shape classifier family's `const`-eval posture. Each of the
13007        // four peer classifiers ([`wit_shape_is_http`] /
13008        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
13009        // [`wit_shape_is_capability`]) and the underlying combinator
13010        // [`wit_shape_matches`] must be `pub const fn` — any future
13011        // accidental downgrade to non-`const` fails the `const fn`
13012        // wrappers below at caixa-core build time with E0015
13013        // (`cannot call non-const function`), strictly stronger than
13014        // a runtime `assert!` and strictly stronger than the module-
13015        // scope `const _: () = assert!(…)` pins immediately after the
13016        // classifier declarations (those anchor specific accept-set
13017        // truth-table entries; this pin anchors the `const` posture
13018        // itself via `const fn` wrappers that are only well-formed
13019        // when the callee is itself `const fn`).
13020        //
13021        // Verified fail-before-pass-after by locally reverting
13022        // `pub const fn` → `pub fn` on each classifier and observing
13023        // E0015 at every corresponding wrapper call site (build
13024        // error, no test-time surface), then restoring `pub const fn`
13025        // and observing the pin pass at test time. Peer of the
13026        // sibling M3
13027        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
13028        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
13029        // M2
13030        // [`child_spec_restart_accessor_is_const_fn`] /
13031        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
13032        // and M3
13033        // [`placement_estrategia_accessor_is_const_fn`] /
13034        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
13035        // sibling `const`-eval-surface-pass axes.
13036        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
13037            wit_shape_matches(wit, prefixes)
13038        }
13039        const fn http_via_const_fn(wit: &str) -> bool {
13040            wit_shape_is_http(wit)
13041        }
13042        const fn pubsub_via_const_fn(wit: &str) -> bool {
13043            wit_shape_is_pubsub(wit)
13044        }
13045        const fn store_via_const_fn(wit: &str) -> bool {
13046            wit_shape_is_store(wit)
13047        }
13048        const fn capability_via_const_fn(wit: &str) -> bool {
13049            wit_shape_is_capability(wit)
13050        }
13051        // Sweep one canonical accept-set sample per arm plus the
13052        // payload-less/empty capability samples, asserting the
13053        // wrapper and direct dispatches agree byte-for-byte across
13054        // the closed 4-arm partition.
13055        let cases: [(&str, bool, bool, bool, bool); 6] = [
13056            ("wasi:http/proxy", true, false, false, false),
13057            ("http:incoming", true, false, false, false),
13058            ("nats:events", false, true, false, false),
13059            ("kafka:topic", false, true, false, false),
13060            ("wasi:keyvalue/store", false, false, true, false),
13061            ("kv:cache", false, false, true, false),
13062        ];
13063        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
13064            assert_eq!(
13065                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
13066                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
13067                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
13068            );
13069            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
13070            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
13071            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
13072            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
13073            assert_eq!(wit_shape_is_http(wit), is_http);
13074            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
13075            assert_eq!(wit_shape_is_store(wit), is_store);
13076        }
13077        // Payload-less capability arm (the 4th partition arm).
13078        let capability_samples: [&str; 3] =
13079            ["wasi:filesystem/preopens", "custom:capability-only", ""];
13080        for wit in capability_samples {
13081            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
13082            assert!(wit_shape_is_capability(wit));
13083            assert!(!wit_shape_is_http(wit));
13084            assert!(!wit_shape_is_pubsub(wit));
13085            assert!(!wit_shape_is_store(wit));
13086        }
13087    }
13088
13089    #[test]
13090    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
13091        // Composition-witness pin: [`wit_shape_matches`] agrees with
13092        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
13093        // dispatch (the prior non-`const` implementation) across
13094        // boundary lengths — empty `wit`, empty prefix, one-byte
13095        // slack, prefix longer than `wit`, one-byte trailing slack.
13096        // The rewrite to a byte-level manual starts_with loop (the
13097        // enabler for the `pub const fn` posture) must not change any
13098        // truth-table entry on the canonical accept-set — this pin
13099        // sweeps a targeted boundary corpus and asserts byte-for-byte
13100        // agreement, locking the const-fn rewrite's semantics against
13101        // the prior iterator body by construction.
13102        let prefixes = &["wasi:http/", "http:"][..];
13103        let cases: [(&str, bool); 12] = [
13104            ("wasi:http/proxy", true),
13105            ("wasi:http/", true), // exact-length match on prefix
13106            ("wasi:http", false), // one byte short
13107            ("http:", true),
13108            ("http:incoming", true),
13109            ("http", false), // one byte short
13110            ("", false),
13111            ("wasi:https/proxy", false),
13112            ("nats:events", false),
13113            ("HTTPS:", false), // uppercase — no case-fold in classifier
13114            ("wasi:HTTP/proxy", false),
13115            ("wasi:http", false),
13116        ];
13117        for (wit, expected) in cases {
13118            assert_eq!(
13119                wit_shape_matches(wit, prefixes),
13120                expected,
13121                "wit_shape_matches disagrees with reference at wit={wit:?}",
13122            );
13123            // Byte-equal to the iterator body it replaced.
13124            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
13125            assert_eq!(
13126                wit_shape_matches(wit, prefixes),
13127                via_iter,
13128                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
13129            );
13130        }
13131        // Empty prefix set → always false regardless of `wit`.
13132        let empty: &[&str] = &[];
13133        assert!(!wit_shape_matches("", empty));
13134        assert!(!wit_shape_matches("wasi:http/proxy", empty));
13135        // Empty prefix inside a non-empty set → always true (every
13136        // string starts with the empty string, matching the
13137        // iterator body's semantics on `str::starts_with("")`).
13138        let contains_empty: &[&str] = &["nats:", ""];
13139        assert!(wit_shape_matches("", contains_empty));
13140        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
13141    }
13142
13143    #[test]
13144    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
13145        // 4-way partition-witness pin: for every canonical prefix in
13146        // the payload-arm accept-sets, exactly one of the four
13147        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13148        // [`WitContract::is_store`] / [`WitContract::is_capability`]
13149        // predicates returns `true` and the other three return `false`
13150        // — the four-arm partition witness that locks the substrate's
13151        // WIT-shape-space closure on the pre-projection axis load-
13152        // bearing. A future arm addition (a hypothetical fourth
13153        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
13154        // shape) that landed on one of the payload-arm predicates
13155        // without shrinking [`WitContract::is_capability`]'s accept-set
13156        // would surface here as two arms returning `true` simultaneously
13157        // — a partition-witness break the pin catches at caixa-core
13158        // build time rather than a silent per-consumer misclassification
13159        // at renderer emit time. Peer of the sibling `WitTarget`-side
13160        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
13161        // partition-witness pin on the post-projection payload-scalar
13162        // arm-set — extends the discipline onto the pre-projection
13163        // 4-arm shape-space.
13164        for shape_set in [
13165            WIT_HTTP_SHAPE_PREFIXES,
13166            WIT_PUBSUB_SHAPE_PREFIXES,
13167            WIT_STORE_SHAPE_PREFIXES,
13168        ] {
13169            for prefix in shape_set {
13170                let c = WitContract {
13171                    de: "cart".into(),
13172                    para: "catalog".into(),
13173                    wit: format!("{prefix}x"),
13174                    endpoint: None,
13175                    subject: None,
13176                    slot: None,
13177                };
13178                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13179                    .iter()
13180                    .filter(|&&b| b)
13181                    .count();
13182                assert_eq!(
13183                    hits,
13184                    1,
13185                    "WitContract WIT-shape 4-way predicate partition must \
13186                     admit exactly one arm per canonical prefix; got {hits} \
13187                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
13188                     is_capability={})",
13189                    c.wit,
13190                    c.is_http(),
13191                    c.is_pubsub(),
13192                    c.is_store(),
13193                    c.is_capability(),
13194                );
13195            }
13196        }
13197        // Capability-arm sweep: two representative capability shapes
13198        // (a bare WIT world outside the three payload-arm prefix sets,
13199        // and the deliberately-shaped empty string that
13200        // [`crate::render::is_wit_world_ref`] rejects at
13201        // [`WitContract::target`] time but which the pure classifier
13202        // still admits — see the method docstring's "purely syntactic
13203        // classification" note). Both must land on the fourth arm
13204        // exclusively, so the partition witness holds across the full
13205        // 4-arm closure.
13206        for wit in ["custom:capability-only", ""] {
13207            let c = WitContract {
13208                de: "cart".into(),
13209                para: "catalog".into(),
13210                wit: wit.into(),
13211                endpoint: None,
13212                subject: None,
13213                slot: None,
13214            };
13215            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13216                .iter()
13217                .filter(|&&b| b)
13218                .count();
13219            assert_eq!(
13220                hits, 1,
13221                "WitContract WIT-shape 4-way predicate partition must \
13222                 admit exactly one arm on Capability-shaped wit={wit:?}"
13223            );
13224            assert!(
13225                c.is_capability(),
13226                "wit={wit:?} must project onto the Capability arm"
13227            );
13228        }
13229    }
13230
13231    #[test]
13232    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
13233        // Composition-witness pin: [`WitContract::is_capability`] is the
13234        // exact-inverse disjunction of the sibling payload-arm predicate
13235        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13236        // [`WitContract::is_store`]. A future reimplementation that
13237        // grew its own prefix-set scan (e.g. inlining a fourth
13238        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
13239        // own today) rather than delegating to the sibling trio would
13240        // drift loudly here — the composition contract binds the
13241        // fourth-arm predicate to the exact-inverse of the three
13242        // payload-arm predicates, so any rebrand of any prefix-set const
13243        // flows through this method by construction without a
13244        // coordinated per-consumer rewrite. Sweeps the union of the
13245        // three payload-arm prefix sets plus two Capability-shaped
13246        // shapes (a bare non-prefix-matching WIT world, the deliberately-
13247        // empty string the pure classifier still admits per the method
13248        // docstring's "purely syntactic classification" note).
13249        let mut cases: Vec<String> = Vec::new();
13250        for shape_set in [
13251            WIT_HTTP_SHAPE_PREFIXES,
13252            WIT_PUBSUB_SHAPE_PREFIXES,
13253            WIT_STORE_SHAPE_PREFIXES,
13254        ] {
13255            for prefix in shape_set {
13256                cases.push(format!("{prefix}x"));
13257            }
13258        }
13259        cases.push("custom:capability-only".to_string());
13260        cases.push(String::new());
13261        for wit in cases {
13262            let c = WitContract {
13263                de: "cart".into(),
13264                para: "catalog".into(),
13265                wit: wit.clone(),
13266                endpoint: None,
13267                subject: None,
13268                slot: None,
13269            };
13270            assert_eq!(
13271                c.is_capability(),
13272                !c.is_http() && !c.is_pubsub() && !c.is_store(),
13273                "WitContract::is_capability must equal \
13274                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
13275            );
13276        }
13277    }
13278
13279    #[test]
13280    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
13281        // Cross-projection-witness pin: whenever [`WitContract::target`]
13282        // succeeds, the pre-projection [`WitContract::is_capability`]
13283        // classification agrees with the post-projection
13284        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
13285        // predicate — the 4-arm typed partition on the substrate's
13286        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
13287        // partition on the pre-projection axis line up by construction.
13288        // A future divergence between the two axes (a peer
13289        // [`WitTarget`] variant addition that landed on the typed-view
13290        // surface without a peer prefix-set + [`WitContract`] predicate
13291        // extension, or vice versa) would surface here at caixa-core
13292        // build time rather than a silent per-consumer split at renderer
13293        // emit time. Peer of the sibling pre-/post-projection
13294        // agreement pins the payload-carrier trio
13295        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13296        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
13297        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
13298        // post-projection — b11bb49 trio lift) already carry across the
13299        // three payload arms — this pin closes the pair on the fourth
13300        // payload-less arm.
13301        let http = WitContract {
13302            de: "cart".into(),
13303            para: "catalog".into(),
13304            wit: "wasi:http/proxy".into(),
13305            endpoint: Some("/x".into()),
13306            subject: None,
13307            slot: None,
13308        };
13309        assert!(!http.is_capability());
13310        assert!(!http.target().unwrap().is_capability());
13311
13312        let nats = WitContract {
13313            de: "cart".into(),
13314            para: "catalog".into(),
13315            wit: "nats:pub-sub".into(),
13316            endpoint: None,
13317            subject: Some("events.x".into()),
13318            slot: None,
13319        };
13320        assert!(!nats.is_capability());
13321        assert!(!nats.target().unwrap().is_capability());
13322
13323        let kv = WitContract {
13324            de: "cart".into(),
13325            para: "catalog".into(),
13326            wit: "wasi:keyvalue/store".into(),
13327            endpoint: None,
13328            subject: None,
13329            slot: Some("checkout/$orderId".into()),
13330        };
13331        assert!(!kv.is_capability());
13332        assert!(!kv.target().unwrap().is_capability());
13333
13334        let cap = WitContract {
13335            de: "cart".into(),
13336            para: "catalog".into(),
13337            wit: "custom:capability-only".into(),
13338            endpoint: None,
13339            subject: None,
13340            slot: None,
13341        };
13342        assert!(cap.is_capability());
13343        assert!(cap.target().unwrap().is_capability());
13344    }
13345
13346    #[test]
13347    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
13348        // Fail-before-pass-after pin on the [`WitContract`] pre-
13349        // projection accessor family's `const`-eval-surface posture.
13350        // Each of the three per-`:contratos` byte-string scalar
13351        // accessors ([`WitContract::source`] / [`WitContract::destination`]
13352        // / [`WitContract::world_ref`], each projecting through
13353        // `String::as_str` — const-stable since Rust 1.87, well within
13354        // the workspace MSRV) and each of the four peer WIT-shape
13355        // predicates ([`WitContract::is_http`] /
13356        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
13357        // [`WitContract::is_capability`], each composing
13358        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
13359        // free-function classifier family the sibling
13360        // [`wit_shape_classifier_family_is_const_fn`] pin already
13361        // anchors on the raw `&str → bool` axis) must be `pub const fn`
13362        // — any future accidental downgrade to non-`const` fails the
13363        // `const fn` wrappers below at caixa-core build time with E0015
13364        // (`cannot call non-const function`), strictly stronger than a
13365        // runtime `assert!` and strictly stronger than a
13366        // module-scope `const _: () = assert!(…)` pin (which cannot be
13367        // formed on a `&WitContract` fixture because the type's
13368        // `String` / `Option<String>` carriers rule out `const`-context
13369        // construction; the `const fn` wrapper is the load-bearing
13370        // shape that side-steps the destructor-in-const restriction on
13371        // the value axis while still pinning the `const`-fn posture on
13372        // the callee).
13373        //
13374        // Peer of the sibling free-function classifier pin
13375        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
13376        // raw `&str → bool` axis — this pin extends the same
13377        // `const`-eval-surface discipline onto the peer method surface
13378        // that composes through those free-function classifiers, and
13379        // simultaneously onto the underlying per-`:contratos`
13380        // byte-string scalar-accessor trio each predicate reads
13381        // through. Sibling of the peer M3
13382        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
13383        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
13384        // M2
13385        // [`child_spec_restart_accessor_is_const_fn`] /
13386        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
13387        // and M3
13388        // [`placement_estrategia_accessor_is_const_fn`] /
13389        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
13390        // sibling `const`-eval-surface-pass axes.
13391        const fn source_via_const_fn(c: &WitContract) -> &str {
13392            c.source()
13393        }
13394        const fn destination_via_const_fn(c: &WitContract) -> &str {
13395            c.destination()
13396        }
13397        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
13398            c.world_ref()
13399        }
13400        const fn is_http_via_const_fn(c: &WitContract) -> bool {
13401            c.is_http()
13402        }
13403        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
13404            c.is_pubsub()
13405        }
13406        const fn is_store_via_const_fn(c: &WitContract) -> bool {
13407            c.is_store()
13408        }
13409        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
13410            c.is_capability()
13411        }
13412        // Sweep one canonical accept-set sample per WIT-shape arm plus
13413        // a payload-less capability sample, asserting the wrapper and
13414        // direct dispatches agree byte-for-byte across the closed
13415        // 4-arm partition on both the scalar-accessor trio and the
13416        // WIT-shape-predicate family.
13417        for (wit, is_http, is_pubsub, is_store, is_capability) in [
13418            ("wasi:http/proxy", true, false, false, false),
13419            ("http:incoming", true, false, false, false),
13420            ("nats:events", false, true, false, false),
13421            ("kafka:topic", false, true, false, false),
13422            ("wasi:keyvalue/store", false, false, true, false),
13423            ("kv:cache", false, false, true, false),
13424            ("custom:capability-only", false, false, false, true),
13425            ("", false, false, false, true),
13426        ] {
13427            let c = WitContract {
13428                de: "cart".into(),
13429                para: "catalog".into(),
13430                wit: wit.into(),
13431                endpoint: None,
13432                subject: None,
13433                slot: None,
13434            };
13435            assert_eq!(source_via_const_fn(&c), c.source());
13436            assert_eq!(destination_via_const_fn(&c), c.destination());
13437            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
13438            assert_eq!(is_http_via_const_fn(&c), c.is_http());
13439            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
13440            assert_eq!(is_store_via_const_fn(&c), c.is_store());
13441            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
13442            assert_eq!(c.source(), "cart");
13443            assert_eq!(c.destination(), "catalog");
13444            assert_eq!(c.world_ref(), wit);
13445            assert_eq!(c.is_http(), is_http);
13446            assert_eq!(c.is_pubsub(), is_pubsub);
13447            assert_eq!(c.is_store(), is_store);
13448            assert_eq!(c.is_capability(), is_capability);
13449        }
13450    }
13451
13452    #[test]
13453    fn wit_contract_identity_projection_accessor_is_const_fn() {
13454        // Fail-before-pass-after pin on the [`WitContract::identity`]
13455        // six-arm composite-projection accessor's `const`-eval-surface
13456        // posture. The accessor projects the typed edge's six identity
13457        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
13458        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
13459        // every callee is itself `pub const fn` ([`WitContract::source`]
13460        // / [`WitContract::destination`] / [`WitContract::world_ref`]
13461        // through `String::as_str`, const-stable since Rust 1.87;
13462        // [`WitContract::endpoint`] / [`WitContract::subject`] /
13463        // [`WitContract::slot`] through the sibling `match &self
13464        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
13465        // 0650f64 closed the const-eval surface on) and the tuple
13466        // constructor from borrowed-reference / `Option`-of-borrowed-
13467        // reference arms is trivially const. Any future accidental
13468        // downgrade fails the `identity_via_const_fn` wrapper at
13469        // caixa-core build time with E0015 (`cannot call non-const
13470        // method`), strictly stronger than a runtime `assert!` and
13471        // strictly stronger than a module-scope `const _: () =
13472        // assert!(…)` pin (which cannot be formed on a `&WitContract`
13473        // fixture because the type's `String` / `Option<String>`
13474        // carriers rule out `const`-context value construction; the
13475        // `const fn` wrapper is the load-bearing shape that side-steps
13476        // the destructor-in-const restriction on the value axis while
13477        // still pinning the `const`-fn posture on the callee — mirror
13478        // of the sibling
13479        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13480        // pin's discipline verbatim on the peer scalar-accessor
13481        // surface).
13482        //
13483        // Peer of the sibling
13484        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13485        // (279823b) pin on the six per-`:contratos` scalar-accessor
13486        // callees this composite-projection reads through — where that
13487        // pin anchors the const-eval surface at the six individual
13488        // scalar-accessor arms, this pin extends the same posture onto
13489        // the composite six-tuple projection every consumer that dedups
13490        // typed edges on the [`ContratoIdentity`] axis keys off (the
13491        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
13492        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
13493        // materializer's per-edge identity-based admission webhook; a
13494        // future L7 policy-emitter that shards CNPs by identity-tuple
13495        // rather than by name). Same fail-before-pass-after wrapper
13496        // discipline as the peer M2 / M3 accessor-family pins on the
13497        // sibling `const`-eval-surface passes.
13498        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
13499            c.identity()
13500        }
13501        // Sweep one canonical WIT-shape sample per payload-carrier arm
13502        // plus a payload-less capability sample so the pin exercises
13503        // both `Some(_)`-carrying and `None`-carrying arms on all three
13504        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
13505        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
13506        // with the direct method call on every arm of the closed WIT-
13507        // shape partition.
13508        for (wit, endpoint, subject, slot) in [
13509            ("wasi:http/proxy", Some("/checkout"), None, None),
13510            ("http:incoming", Some("/api"), None, None),
13511            ("nats:events", None, Some("orders.placed"), None),
13512            ("kafka:topic", None, Some("orders.stream"), None),
13513            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
13514            ("kv:cache", None, None, Some("session/{token}")),
13515            ("custom:capability-only", None, None, None),
13516        ] {
13517            let c = WitContract {
13518                de: "cart".into(),
13519                para: "catalog".into(),
13520                wit: wit.into(),
13521                endpoint: endpoint.map(str::to_string),
13522                subject: subject.map(str::to_string),
13523                slot: slot.map(str::to_string),
13524            };
13525            assert_eq!(identity_via_const_fn(&c), c.identity());
13526            assert_eq!(
13527                c.identity(),
13528                ("cart", "catalog", wit, endpoint, subject, slot,),
13529            );
13530        }
13531    }
13532
13533    #[test]
13534    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
13535        // Fail-before-pass-after pin on the four M3 mesh-slot
13536        // `String → &str` scalar accessors ([`Membro::nome`] /
13537        // [`Membro::versao_requirement`] on the per-`:membros` axis,
13538        // [`Entrada::hostname`] / [`Entrada::destination`] on the
13539        // per-`:entrada` axis) — each projects the typed slot's
13540        // [`String`] storage through the `pub const fn`
13541        // [`String::as_str`] (const-stable since Rust 1.87, well
13542        // within the workspace MSRV) and any future accidental
13543        // downgrade to non-`const` fails the corresponding
13544        // `<name>_via_const_fn` wrapper at caixa-core build time with
13545        // E0015 (`cannot call non-const method`), strictly stronger
13546        // than a runtime `assert!` and strictly stronger than a
13547        // module-scope `const _: () = assert!(…)` pin (which cannot
13548        // be formed on `&Membro` / `&Entrada` fixtures because the
13549        // types' `String` carriers rule out `const`-context value
13550        // construction; the `const fn` wrapper is the load-bearing
13551        // shape that side-steps the destructor-in-const restriction
13552        // on the value axis while still pinning the `const`-fn
13553        // posture on the callee — mirror of the sibling
13554        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13555        // (279823b) pin on the per-`:contratos` axis). Peer of the
13556        // sibling per-M2/M3/universal-axis `String → &str` accessor
13557        // family pins on the sibling `const`-eval-surface passes
13558        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
13559        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
13560        // typed-newtype wrapper,
13561        // [`crate::supervisor::ChildSpec::nome`] /
13562        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
13563        // M2 supervisor-tree axis,
13564        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
13565        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
13566        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
13567        // axis, and the sibling per-`:contratos`
13568        // [`WitContract::source`] / [`WitContract::destination`] /
13569        // [`WitContract::world_ref`] trio at 279823b).
13570        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
13571            m.nome()
13572        }
13573        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
13574            m.versao_requirement()
13575        }
13576        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
13577            e.hostname()
13578        }
13579        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
13580            e.destination()
13581        }
13582        for (caixa, versao) in [
13583            ("cart", "^0.1"),
13584            ("catalog-v2", "~0.2.3"),
13585            ("checkout", "*"),
13586        ] {
13587            let m = Membro {
13588                caixa: caixa.into(),
13589                versao: versao.into(),
13590            };
13591            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
13592            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
13593            assert_eq!(m.nome(), caixa);
13594            assert_eq!(m.versao_requirement(), versao);
13595        }
13596        for (host, para) in [
13597            ("cart.example.com", "cart"),
13598            ("api.checkout.io", "checkout"),
13599        ] {
13600            let e = Entrada {
13601                host: host.into(),
13602                para: para.into(),
13603                paths: vec![],
13604                port: DEFAULT_SERVICO_PORT,
13605            };
13606            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
13607            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
13608            assert_eq!(e.hostname(), host);
13609            assert_eq!(e.destination(), para);
13610        }
13611    }
13612
13613    #[test]
13614    fn m3_option_string_scalar_accessor_family_is_const_fn() {
13615        // Fail-before-pass-after pin on the five M3 mesh-slot
13616        // `Option<String> → Option<&str>` scalar accessors
13617        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13618        // [`WitContract::slot`] on the per-`:contratos` HTTP /
13619        // pub-sub / key-value payload-carrier trio,
13620        // [`Placement::shard_key`] / [`Placement::affinity`] on the
13621        // per-`:placement` Akka-sharding-key + Adaptive-compression-
13622        // hint pair). Each accessor destructures the typed slot's
13623        // `Option<String>` storage through the `match &self.<field> {
13624        // Some(s) => Some(s.as_str()), None => None }` shape —
13625        // routing through [`String::as_str`] (const-stable since Rust
13626        // 1.87, well within the workspace MSRV) rather than the
13627        // non-const [`Option::as_deref`] the pre-lift bodies carried
13628        // — and any future accidental downgrade to non-`const` fails
13629        // the corresponding `<name>_via_const_fn` wrapper at
13630        // caixa-core build time with E0015 (`cannot call non-const
13631        // method`), strictly stronger than a runtime `assert!` and
13632        // strictly stronger than a module-scope `const _: () =
13633        // assert!(…)` pin (which cannot be formed on `&WitContract`
13634        // / `&Placement` fixtures because the types' `String` /
13635        // `Option<String>` carriers rule out `const`-context value
13636        // construction; the `const fn` wrapper is the load-bearing
13637        // shape that side-steps the destructor-in-const restriction
13638        // on the value axis while still pinning the `const`-fn
13639        // posture on the callee — mirror of the sibling
13640        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13641        // (279823b) and
13642        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
13643        // (29c5d7e) pins on the peer `String → &str` axes at the same
13644        // structs).
13645        //
13646        // Peer of the sibling per-`Caixa` `Option<String> →
13647        // Option<&str>` accessor family pin
13648        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
13649        // on the top-level manifest's optional universal-axis surface
13650        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
13651        // `:restart-window`).
13652        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
13653            w.endpoint()
13654        }
13655        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
13656            w.subject()
13657        }
13658        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
13659            w.slot()
13660        }
13661        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
13662            p.shard_key()
13663        }
13664        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
13665            p.affinity()
13666        }
13667        // Sweep every closed shape-arm partition on the
13668        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
13669        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
13670        // pair None), key-value (`:slot` Some, sibling pair None),
13671        // and Capability (all three None) so each accessor's
13672        // Some/None arm carries a pin through the const dispatch.
13673        for (wit, endpoint, subject, slot) in [
13674            ("wasi:http/proxy", Some("/api"), None, None),
13675            ("nats:pub-sub", None, Some("orders.paid"), None),
13676            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
13677            ("custom:capability-only", None, None, None),
13678        ] {
13679            let c = WitContract {
13680                de: "cart".into(),
13681                para: "catalog".into(),
13682                wit: wit.into(),
13683                endpoint: endpoint.map(str::to_string),
13684                subject: subject.map(str::to_string),
13685                slot: slot.map(str::to_string),
13686            };
13687            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
13688            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
13689            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
13690            assert_eq!(c.endpoint(), endpoint);
13691            assert_eq!(c.subject(), subject);
13692            assert_eq!(c.slot(), slot);
13693        }
13694        // Sweep both `Some`/`None` arms on each per-`:placement`
13695        // optional-scalar so the shard-key + affinity pair carries a
13696        // const-dispatch pin on both arms.
13697        for (shard_key, affinity) in [
13698            (Some("tenantId"), Some("data-locality")),
13699            (Some("$tenantId"), None),
13700            (None, Some("low-latency")),
13701            (None, None),
13702        ] {
13703            let p = Placement {
13704                estrategia: PlacementStrategy::default(),
13705                clusters: vec![],
13706                affinity: affinity.map(str::to_string),
13707                shard_key: shard_key.map(str::to_string),
13708            };
13709            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
13710            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
13711            assert_eq!(p.shard_key(), shard_key);
13712            assert_eq!(p.affinity(), affinity);
13713        }
13714    }
13715
13716    #[test]
13717    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
13718        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
13719        // composite `Vec → &[String]` slice-return accessors on
13720        // [`Placement::clusters`] and [`Entrada::paths`]. Each
13721        // destructures the typed slot's `Vec<String>` storage through
13722        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
13723        // 1.66, well within the workspace MSRV) — any future accidental
13724        // downgrade to non-`const` fails the corresponding
13725        // `<name>_via_const_fn` wrapper at caixa-core build time with
13726        // E0015 (`cannot call non-const method`), strictly stronger
13727        // than a runtime `assert!`. Sibling of the peer
13728        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
13729        // pin on the outer-`AplicacaoSpec` reference-return family
13730        // (`:membros` / `:contratos` slice-return + `:politicas` /
13731        // `:placement` / `:entrada` composite-reference), and of the
13732        // peer M2 slice-return axis pins
13733        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
13734        // (on `SupervisorSpec::children`) and
13735        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
13736        // (on `UpgradeFromEntry::instructions`). Together the four
13737        // pins close the last unlifted reference-return accessor
13738        // family across the substrate primitive.
13739        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
13740            p.clusters()
13741        }
13742        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
13743            e.paths()
13744        }
13745        // Sweep both the empty-Vec (no author-declared entries) and
13746        // the populated-Vec arms on every slice-return accessor so
13747        // each carries a const-dispatch pin on both arms.
13748        let p_empty = Placement {
13749            estrategia: PlacementStrategy::default(),
13750            clusters: vec![],
13751            affinity: None,
13752            shard_key: None,
13753        };
13754        let p_full = Placement {
13755            estrategia: PlacementStrategy::default(),
13756            clusters: vec!["prod-a".into(), "prod-b".into()],
13757            affinity: None,
13758            shard_key: None,
13759        };
13760        assert_eq!(
13761            placement_clusters_via_const_fn(&p_empty),
13762            p_empty.clusters()
13763        );
13764        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
13765        assert!(p_empty.clusters().is_empty());
13766        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
13767        let e_empty = Entrada {
13768            host: "web.example.com".into(),
13769            para: "web".into(),
13770            paths: vec![],
13771            port: DEFAULT_SERVICO_PORT,
13772        };
13773        let e_full = Entrada {
13774            host: "web.example.com".into(),
13775            para: "web".into(),
13776            paths: vec!["/api".into(), "/health".into()],
13777            port: DEFAULT_SERVICO_PORT,
13778        };
13779        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
13780        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
13781        assert!(e_empty.paths().is_empty());
13782        assert_eq!(e_full.paths(), &["/api", "/health"]);
13783    }
13784
13785    #[test]
13786    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
13787        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
13788        // reference-return accessors — the two `Vec → &[T]` slice-
13789        // return accessors on [`AplicacaoSpec::membros`] and
13790        // [`AplicacaoSpec::contratos`] (each routes through the
13791        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
13792        // 1.66), the two `&Composite` composite-reference accessors
13793        // on [`AplicacaoSpec::politicas`] and
13794        // [`AplicacaoSpec::placement`] (each routes through a raw
13795        // `&self.<field>` borrow, trivially const), and the one
13796        // `Option<&Composite>` optional-composite-reference accessor
13797        // on [`AplicacaoSpec::entrada`] (routes through the
13798        // `pub const fn` [`Option::as_ref`], const-stable since Rust
13799        // 1.83). Any future accidental downgrade to non-`const` fails
13800        // the corresponding `<name>_via_const_fn` wrapper at caixa-
13801        // core build time with E0015 (`cannot call non-const
13802        // method`), strictly stronger than a runtime `assert!`.
13803        // Sibling of the peer inner-composite pin
13804        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
13805        // on the `Placement::clusters` + `Entrada::paths` slice-
13806        // return pair, and of the peer M2 axis pins on
13807        // [`crate::supervisor::SupervisorSpec::children`] and
13808        // [`crate::upgrade::UpgradeFromEntry::instructions`].
13809        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
13810            s.membros()
13811        }
13812        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
13813            s.contratos()
13814        }
13815        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
13816            s.politicas()
13817        }
13818        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
13819            s.placement()
13820        }
13821        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
13822            s.entrada()
13823        }
13824        // Construct both a minimal "no :entrada" (internal-only
13825        // mesh) and a full "with :entrada" (external-gateway)
13826        // fixture so the family pins both the `None`-arm (author-
13827        // omitted `:entrada`) and the `Some`-arm (author-declared
13828        // `:entrada`) on the optional-composite axis.
13829        let membro = Membro {
13830            caixa: "web".into(),
13831            versao: "^0.1".into(),
13832        };
13833        let entrada_full = Entrada {
13834            host: "web.example.com".into(),
13835            para: "web".into(),
13836            paths: vec!["/api".into()],
13837            port: DEFAULT_SERVICO_PORT,
13838        };
13839        let internal_only = AplicacaoSpec {
13840            membros: vec![membro.clone()],
13841            contratos: vec![],
13842            politicas: MeshPolicy::default(),
13843            placement: Placement::default(),
13844            entrada: None,
13845        };
13846        let with_entrada = AplicacaoSpec {
13847            membros: vec![membro],
13848            contratos: vec![],
13849            politicas: MeshPolicy::default(),
13850            placement: Placement::default(),
13851            entrada: Some(entrada_full),
13852        };
13853        assert_eq!(
13854            aplicacao_membros_via_const_fn(&internal_only),
13855            internal_only.membros()
13856        );
13857        assert_eq!(
13858            aplicacao_membros_via_const_fn(&with_entrada),
13859            with_entrada.membros()
13860        );
13861        assert_eq!(
13862            aplicacao_contratos_via_const_fn(&internal_only),
13863            internal_only.contratos()
13864        );
13865        assert!(std::ptr::eq(
13866            aplicacao_politicas_via_const_fn(&internal_only),
13867            internal_only.politicas(),
13868        ));
13869        assert!(std::ptr::eq(
13870            aplicacao_placement_via_const_fn(&internal_only),
13871            internal_only.placement(),
13872        ));
13873        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
13874        match (
13875            aplicacao_entrada_via_const_fn(&with_entrada),
13876            with_entrada.entrada(),
13877        ) {
13878            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
13879            _ => panic!(
13880                "aplicacao_entrada_via_const_fn must agree with \
13881                 AplicacaoSpec::entrada on the Some-arm reference"
13882            ),
13883        }
13884    }
13885
13886    #[test]
13887    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
13888        // Load-bearing contract pin: on every canonical
13889        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
13890        // [`WitContract::target_projected`] returns byte-equal to
13891        // [`WitContract::target`]`().unwrap()` — the post-validation
13892        // projection accessor is a thin panicking wrapper over the
13893        // pre-validation validator, no extra work in the projection
13894        // path. Any future divergence (a validator-side normalization
13895        // the projection doesn't route through, an accessor-side
13896        // caching layer the validator doesn't populate) would surface
13897        // here at caixa-core build time rather than a silent per-consumer
13898        // split at renderer emit time. Sweeps the closed 4-arm
13899        // [`WitTarget`] partition ([`WitTarget::Http`] /
13900        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
13901        // [`WitTarget::Capability`]) so every arm carries a byte-equality
13902        // pin on the two-accessor pair.
13903        for (wit, endpoint, subject, slot) in [
13904            ("wasi:http/proxy", Some("/x"), None, None),
13905            ("nats:pub-sub", None, Some("events.x"), None),
13906            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
13907            ("custom:capability-only", None, None, None),
13908        ] {
13909            let c = WitContract {
13910                de: "cart".into(),
13911                para: "catalog".into(),
13912                wit: wit.into(),
13913                endpoint: endpoint.map(str::to_string),
13914                subject: subject.map(str::to_string),
13915                slot: slot.map(str::to_string),
13916            };
13917            assert_eq!(
13918                c.target_projected(),
13919                c.target().unwrap(),
13920                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
13921            );
13922        }
13923    }
13924
13925    #[test]
13926    #[should_panic(expected = "validated by typed_view")]
13927    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
13928        // Panic-path pin: [`WitContract::target_projected`] threads the
13929        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
13930        // through its expect-panic when called on a contract whose
13931        // (`:wit`, payload) shape has not been crossed by
13932        // [`AplicacaoSpec::validate`] — a contract with a structurally-
13933        // invalid `:wit` (hyphen-for-colon typo) that would surface
13934        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
13935        // A future rebrand on the panic-message axis would land at one
13936        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
13937        // and this pin's [`should_panic(expected = …)`] literal would
13938        // migrate alongside — the pin catches drift between the const
13939        // and the accessor's `expect(…)` call by construction.
13940        let c = WitContract {
13941            de: "cart".into(),
13942            para: "catalog".into(),
13943            // Hyphen-for-colon typo: `WitContract::target` returns
13944            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
13945            // driving the [`WitContract::target_projected`] expect-panic.
13946            wit: "wasi-http/proxy".into(),
13947            endpoint: Some("/x".into()),
13948            subject: None,
13949            slot: None,
13950        };
13951        let _ = c.target_projected();
13952    }
13953
13954    #[test]
13955    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
13956        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
13957        // carries the exact byte-string the two prior open-coded
13958        // `.target().expect("validated by typed_view")` production
13959        // consumers threaded through inline before this lift converged
13960        // them onto [`WitContract::target_projected`] — the caixa-mesh
13961        // per-`(:de, :para)` CNP L7 introspection branch at
13962        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
13963        // graph` per-`:contratos` payload-column printer at
13964        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
13965        // byte-string load-bearing so a well-meaning const-side rebrand
13966        // that didn't carry a matched pin migration would surface here
13967        // at caixa-core build time rather than a silent per-consumer
13968        // panic-message drift at cluster-apply time. Peer of the
13969        // sibling [`WitTarget::CAPABILITY_LABEL`] /
13970        // [`WitTarget::CAPABILITY_EXPECTED`] /
13971        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
13972        // the paired payload-less-arm scalar-const family.
13973        assert_eq!(
13974            WitContract::PROJECTED_INVARIANT_MSG,
13975            "validated by typed_view"
13976        );
13977    }
13978
13979    #[test]
13980    fn empty_wit_takes_precedence_over_invalid() {
13981        // Ordering pin: `EmptyWit` is the more self-locating
13982        // diagnostic on `""` and must lead — the value-shape gate is
13983        // only reached after the empty-check fires. Mirrors
13984        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
13985        // the peer payload axis.
13986        let mut s = three_member_spec();
13987        s.contratos.push(WitContract {
13988            de: "payment".into(),
13989            para: "catalog".into(),
13990            wit: String::new(),
13991            endpoint: None,
13992            subject: None,
13993            slot: None,
13994        });
13995        let err = s.validate().unwrap_err();
13996        assert!(
13997            matches!(err, AplicacaoError::EmptyWit { .. }),
13998            "got {err:?}"
13999        );
14000    }
14001
14002    #[test]
14003    fn wit_invalid_fires_before_payload_shape_arm() {
14004        // Ordering pin: a malformed `:wit` surfaces *its own*
14005        // diagnostic (which names the offending wit verbatim) before
14006        // any payload-field check — a contrato whose wit is
14007        // structurally invalid AND carries a wrong target field
14008        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
14009        // because the dispatch on the wit is what decides which
14010        // payload field is "right" in the first place. Without this
14011        // ordering, the author would see "wrong target field" for a
14012        // wit that hasn't even been parsed, which doesn't name the
14013        // root cause.
14014        let mut s = three_member_spec();
14015        s.contratos.push(WitContract {
14016            de: "payment".into(),
14017            para: "catalog".into(),
14018            // Hyphen-for-colon typo + endpoint set: pre-gate this
14019            // raised `ContratoWrongTarget { expected: "none" }` (the
14020            // Capability arm rejecting the endpoint), masking the
14021            // real authoring mistake (the wit isn't `wasi:http/proxy`).
14022            wit: "wasi-http/proxy".into(),
14023            endpoint: Some("/x".into()),
14024            subject: None,
14025            slot: None,
14026        });
14027        let err = s.validate().unwrap_err();
14028        assert!(
14029            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
14030                if wit == "wasi-http/proxy"),
14031            "got {err:?}"
14032        );
14033    }
14034
14035    #[test]
14036    fn wit_invalid_diagnostic_carries_offending_wit() {
14037        // Diagnostic-shape pin — the offending `:wit` + `:de` +
14038        // `:para` + a non-empty reason flow through verbatim so the
14039        // author can grep their caixa.lisp for the offending contrato
14040        // block and fix it in one edit. Same shape as
14041        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
14042        let err = contrato_wit_err("WASI:HTTP/proxy");
14043        match err {
14044            AplicacaoError::ContratoWitInvalid {
14045                de,
14046                para,
14047                wit,
14048                reason,
14049            } => {
14050                assert_eq!(de, "payment");
14051                assert_eq!(para, "catalog");
14052                assert_eq!(wit, "WASI:HTTP/proxy");
14053                assert!(!reason.is_empty(), "reason field must be non-empty");
14054            }
14055            other => panic!("expected ContratoWitInvalid, got {other:?}"),
14056        }
14057    }
14058
14059    // ── :contratos :subject value-shape gate ─────────────────────────────
14060    //
14061    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
14062    // suites on the peer payload axes. Until this gate landed
14063    // `WitContract::target()` only refused the empty string; a
14064    // structurally invalid subject silently passed validate and the
14065    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
14066    // Subject'` on publish / subscribe, or as a silent message drop,
14067    // far from the source caixa.lisp. Every authoring footgun the
14068    // NATS server's subject parser would catch on admission now
14069    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
14070    // offending `:subject` + `:de` + `:para` named verbatim. Same
14071    // diagnostic shape as `ContratoEndpointInvalid` /
14072    // `ContratoWitInvalid` on the peer payload axes; same shared
14073    // predicate (`crate::render::is_nats_subject`) ensures drift
14074    // between any two axes' rule enforcement is a build error at the
14075    // predicate, not piecemeal across renderers.
14076
14077    fn contrato_subject_err(subject: &str) -> AplicacaoError {
14078        // Fresh spec per call so the new contract doesn't collide on
14079        // identity with `three_member_spec`'s pre-existing entries.
14080        // The new edge uses `(payment, catalog)` — a pair the fixture
14081        // doesn't already declare — with `:wit "nats:pub-sub"` and the
14082        // varying `:subject`, so the subject-shape gate fires cleanly
14083        // after the wit-shape gate (which `"nats:pub-sub"` passes).
14084        let mut s = three_member_spec();
14085        s.contratos.push(WitContract {
14086            de: "payment".into(),
14087            para: "catalog".into(),
14088            wit: "nats:pub-sub".into(),
14089            endpoint: None,
14090            subject: Some(subject.into()),
14091            slot: None,
14092        });
14093        s.validate().unwrap_err()
14094    }
14095
14096    #[test]
14097    fn rejects_pubsub_contrato_subject_with_whitespace() {
14098        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
14099        // landed at the NATS server as a malformed subject the parser
14100        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
14101        // source caixa.lisp.
14102        let err = contrato_subject_err("foo bar");
14103        assert!(
14104            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14105                if subject == "foo bar" && reason.contains("whitespace")),
14106            "got {err:?}"
14107        );
14108    }
14109
14110    #[test]
14111    fn rejects_pubsub_contrato_subject_with_control_char() {
14112        let err = contrato_subject_err("foo\x01bar");
14113        assert!(
14114            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14115                if subject == "foo\x01bar" && reason.contains("control character")),
14116            "got {err:?}"
14117        );
14118    }
14119
14120    #[test]
14121    fn rejects_pubsub_contrato_subject_with_non_ascii() {
14122        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14123        // the subject from a doc with smart quotes / accented
14124        // characters" footgun.
14125        let err = contrato_subject_err("foo.caf\u{e9}");
14126        assert!(
14127            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14128                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
14129            "got {err:?}"
14130        );
14131    }
14132
14133    #[test]
14134    fn rejects_pubsub_contrato_subject_with_leading_dot() {
14135        // Empty leading token — NATS rejects.
14136        let err = contrato_subject_err(".foo");
14137        assert!(
14138            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14139                if subject == ".foo" && reason.contains("must not start with `.`")),
14140            "got {err:?}"
14141        );
14142    }
14143
14144    #[test]
14145    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
14146        // Empty trailing token — NATS rejects. The remediation
14147        // (use `>` instead) is in the reason string.
14148        let err = contrato_subject_err("foo.");
14149        assert!(
14150            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14151                if subject == "foo." && reason.contains("must not end with `.`")),
14152            "got {err:?}"
14153        );
14154    }
14155
14156    #[test]
14157    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
14158        // The canonical "I forgot to fill in the middle segment"
14159        // typo — `"foo..bar"`. NATS rejects empty tokens.
14160        let err = contrato_subject_err("foo..bar");
14161        assert!(
14162            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14163                if subject == "foo..bar" && reason.contains("consecutive `.`")),
14164            "got {err:?}"
14165        );
14166    }
14167
14168    #[test]
14169    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
14170        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
14171        // as the final segment. Pre-gate this passed as a typed edge
14172        // and surfaced at runtime as a NATS subscribe rejection.
14173        let err = contrato_subject_err("foo.>.bar");
14174        assert!(
14175            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14176                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
14177            "got {err:?}"
14178        );
14179    }
14180
14181    #[test]
14182    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
14183        // `foo*.bar` — NATS wildcards are standalone tokens. The
14184        // remediation is in the reason string.
14185        let err = contrato_subject_err("foo*.bar");
14186        assert!(
14187            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14188                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
14189            "got {err:?}"
14190        );
14191    }
14192
14193    #[test]
14194    fn rejects_pubsub_contrato_subject_with_invalid_char() {
14195        // `foo,bar` — comma is not a valid NATS subject character.
14196        // Pinned separately from the wildcard arms so the invalid-
14197        // character diagnostic is in force.
14198        let err = contrato_subject_err("foo,bar");
14199        assert!(
14200            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14201                if subject == "foo,bar" && reason.contains("invalid character")),
14202            "got {err:?}"
14203        );
14204    }
14205
14206    #[test]
14207    fn rejects_pubsub_contrato_subject_too_long() {
14208        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
14209        // The legitimate-shape arms all pass (one all-`a` token, no
14210        // `.`, no wildcards); only the cap arm fires. Surfaces the
14211        // paste-from-binary / accidental-multi-line-blob landing
14212        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
14213        // on the peer axis.
14214        let big = "a".repeat(257);
14215        assert_eq!(big.len(), 257);
14216        let err = contrato_subject_err(&big);
14217        assert!(
14218            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14219                if subject == &big && reason.contains("max length of 256")),
14220            "got {err:?}"
14221        );
14222    }
14223
14224    #[test]
14225    fn pubsub_contrato_subject_max_length_validates() {
14226        // 256-byte subject — exactly the cap. Boundary pin: drift in
14227        // the cap surfaces here and at
14228        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
14229        // mirroring `http_contrato_endpoint_max_length_validates` and
14230        // `wit_max_length_validates` on the peer axes.
14231        let big = "a".repeat(256);
14232        assert_eq!(big.len(), 256);
14233        let mut s = three_member_spec();
14234        s.contratos.push(WitContract {
14235            de: "payment".into(),
14236            para: "catalog".into(),
14237            wit: "nats:pub-sub".into(),
14238            endpoint: None,
14239            subject: Some(big),
14240            slot: None,
14241        });
14242        s.validate().unwrap();
14243    }
14244
14245    #[test]
14246    fn pubsub_contrato_subject_accepts_canonical_forms() {
14247        // Positive-set sweep: every canonical NATS subject shape the
14248        // substrate-side `is_nats_subject` predicate accepts (the
14249        // multi-dot `events.order.charged`, the snake_case / kebab-
14250        // case / mixed-case tokens, the digit-bearing tokens, the
14251        // single-token wildcard `*` at every segment position, and
14252        // the trailing `>` multi-token wildcard) must remain a valid
14253        // contrato subject too. Drift between this list and the
14254        // substrate-side `nats_subject_accepts_canonical_forms` sweep
14255        // surfaces at the shared predicate — one source of truth.
14256        // Uses a fresh `(payment, catalog)` edge so none of the swept
14257        // subjects collide with the pre-existing entries in
14258        // `three_member_spec`.
14259        for subject in [
14260            "checkout.events.charge.failed",
14261            "rio.events.order.charged",
14262            "orders",
14263            "orders.123",
14264            "snake_case.token",
14265            "kebab-case.token",
14266            "MixedCase.Token",
14267            "orders.*.charged",
14268            "*.events.*",
14269            "orders.>",
14270        ] {
14271            let mut s = three_member_spec();
14272            s.contratos.push(WitContract {
14273                de: "payment".into(),
14274                para: "catalog".into(),
14275                wit: "nats:pub-sub".into(),
14276                endpoint: None,
14277                subject: Some(subject.into()),
14278                slot: None,
14279            });
14280            s.validate()
14281                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
14282        }
14283    }
14284
14285    #[test]
14286    fn contrato_subject_empty_takes_precedence_over_invalid() {
14287        // Ordering pin: `ContratoSubjectEmpty` is the more self-
14288        // locating diagnostic on `""` and must lead — the value-shape
14289        // gate is only reached after the empty-check fires. Mirrors
14290        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14291        // the peer payload axis.
14292        let mut s = three_member_spec();
14293        s.contratos.push(WitContract {
14294            de: "payment".into(),
14295            para: "catalog".into(),
14296            wit: "nats:pub-sub".into(),
14297            endpoint: None,
14298            subject: Some(String::new()),
14299            slot: None,
14300        });
14301        let err = s.validate().unwrap_err();
14302        assert!(
14303            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
14304            "got {err:?}"
14305        );
14306    }
14307
14308    #[test]
14309    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
14310        // Diagnostic-shape pin — the offending `:subject` + `:de` +
14311        // `:para` + a non-empty reason flow through verbatim so the
14312        // author can grep their caixa.lisp for the offending contrato
14313        // block and fix it in one edit. Same shape as
14314        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
14315        // and `wit_invalid_diagnostic_carries_offending_wit`.
14316        let err = contrato_subject_err("foo..bar");
14317        match err {
14318            AplicacaoError::ContratoSubjectInvalid {
14319                de,
14320                para,
14321                subject,
14322                reason,
14323            } => {
14324                assert_eq!(de, "payment");
14325                assert_eq!(para, "catalog");
14326                assert_eq!(subject, "foo..bar");
14327                assert!(!reason.is_empty(), "reason field must be non-empty");
14328            }
14329            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
14330        }
14331    }
14332
14333    #[test]
14334    fn target_view_pubsub_subject_passes_through_to_typed_view() {
14335        // The compounding theorem on the pub-sub axis: every
14336        // `WitTarget::PubSub { subject }` returned by `target()` carries
14337        // a NATS-server-accepted subject. Renderers downstream of
14338        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
14339        // NATS Stream/Consumer CR emitter, the future `feira app graph`
14340        // view's subject labeller) can rely on this without re-checking
14341        // — the type system carries the proof. Mirrors
14342        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
14343        // on the peer axes.
14344        let nats = WitContract {
14345            de: "a".into(),
14346            para: "b".into(),
14347            wit: "nats:pub-sub".into(),
14348            endpoint: None,
14349            subject: Some("orders.events.*.charged".into()),
14350            slot: None,
14351        };
14352        match nats.target().unwrap() {
14353            WitTarget::PubSub { subject } => {
14354                assert_eq!(subject, "orders.events.*.charged");
14355            }
14356            other => panic!("expected PubSub, got {other:?}"),
14357        }
14358    }
14359
14360    // ── :contratos :slot value-shape gate ────────────────────────────────
14361    //
14362    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
14363    // (63e18a0) value-shape suites on the peer payload axes. Until this
14364    // gate landed `WitContract::target()` only refused the empty string
14365    // for the Store arm; a structurally invalid slot (raw whitespace,
14366    // control character, non-ASCII byte, paste-from-binary multi-line
14367    // blob) silently passed validate and surfaced at runtime as a
14368    // per-backend kv write rejection or a silent next-read corruption,
14369    // far from the source caixa.lisp with no field naming which
14370    // `:contratos` edge carried the typo. Every authoring footgun the
14371    // kv backend intersection-floor would catch on write now becomes a
14372    // caixa-build-time `ContratoSlotInvalid` with the offending
14373    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
14374    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
14375    // peer payload axes; same shared predicate
14376    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
14377    // any two axes' rule enforcement is a build error at the
14378    // predicate, not piecemeal across renderers. Closes the typed
14379    // payload-axis value-shape trajectory across all three legs of the
14380    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
14381
14382    fn contrato_slot_err(slot: &str) -> AplicacaoError {
14383        // Fresh spec per call so the new contract doesn't collide on
14384        // identity with `three_member_spec`'s pre-existing entries
14385        // and doesn't close a synchronous cycle the cycle detector
14386        // would reject before the slot-shape gate fires. The new edge
14387        // uses `(payment, catalog)` — a pair the fixture doesn't
14388        // already declare in either direction (the fixture carries
14389        // `cart -> catalog` and `cart -> payment`, so `payment ->
14390        // catalog` doesn't form a cycle on the sync subgraph) — with
14391        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
14392        // slot-shape gate fires cleanly after the wit-shape gate
14393        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
14394        // peer `contrato_subject_err` helper uses (63e18a0).
14395        let mut s = three_member_spec();
14396        s.contratos.push(WitContract {
14397            de: "payment".into(),
14398            para: "catalog".into(),
14399            wit: "wasi:keyvalue/store".into(),
14400            endpoint: None,
14401            subject: None,
14402            slot: Some(slot.into()),
14403        });
14404        s.validate().unwrap_err()
14405    }
14406
14407    #[test]
14408    fn rejects_store_contrato_slot_with_whitespace() {
14409        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
14410        // silently landed at the kv backend with whitespace whose
14411        // runtime behavior varies unpredictably across backends (etcd
14412        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
14413        // rejects on write). Now caught at the source caixa.lisp.
14414        let err = contrato_slot_err("check out/$order");
14415        assert!(
14416            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14417                if slot == "check out/$order" && reason.contains("whitespace")),
14418            "got {err:?}"
14419        );
14420    }
14421
14422    #[test]
14423    fn rejects_store_contrato_slot_with_tab() {
14424        // Tab byte arm-pinned separately from the space arm so a
14425        // future relaxation that admits one but not the other surfaces
14426        // here.
14427        let err = contrato_slot_err("check\tout");
14428        assert!(
14429            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14430                if slot == "check\tout" && reason.contains("whitespace")),
14431            "got {err:?}"
14432        );
14433    }
14434
14435    #[test]
14436    fn rejects_store_contrato_slot_with_control_char() {
14437        // SOH (0x01) — distinct from the whitespace arm. Redis admits
14438        // and corrupts on RESP protocol framing; DynamoDB rejects on
14439        // write.
14440        let err = contrato_slot_err("checkout/\x01order");
14441        assert!(
14442            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14443                if slot == "checkout/\x01order" && reason.contains("control character")),
14444            "got {err:?}"
14445        );
14446    }
14447
14448    #[test]
14449    fn rejects_store_contrato_slot_with_newline() {
14450        // Embedded newline — the canonical "the paste-from-binary slug
14451        // spans multiple lines" footgun. Distinct from the whitespace
14452        // arm because `\n` is a control character (0x0A).
14453        let err = contrato_slot_err("checkout\norder");
14454        assert!(
14455            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14456                if slot == "checkout\norder" && reason.contains("control character")),
14457            "got {err:?}"
14458        );
14459    }
14460
14461    #[test]
14462    fn rejects_store_contrato_slot_with_non_ascii() {
14463        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14464        // the slot from a doc with accented characters" footgun. Each
14465        // kv backend re-encodes non-ASCII differently (etcd preserves
14466        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
14467        // rejects), so the typed slot's value set is the intersection-
14468        // floor every backend admits identically (printable ASCII).
14469        let err = contrato_slot_err("ch\u{e9}ckout/$order");
14470        assert!(
14471            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14472                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
14473            "got {err:?}"
14474        );
14475    }
14476
14477    #[test]
14478    fn rejects_store_contrato_slot_too_long() {
14479        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
14480        // legitimate-shape arms all pass (a single all-`a` token, no
14481        // separators); only the cap arm fires. Surfaces the paste-
14482        // from-binary / accidental-multi-line-blob landing footgun.
14483        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
14484        // `rejects_http_contrato_endpoint_too_long` on the peer
14485        // payload axes.
14486        let big = "a".repeat(513);
14487        assert_eq!(big.len(), 513);
14488        let err = contrato_slot_err(&big);
14489        assert!(
14490            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14491                if slot == &big && reason.contains("max length of 512")),
14492            "got {err:?}"
14493        );
14494    }
14495
14496    #[test]
14497    fn store_contrato_slot_max_length_validates() {
14498        // 512-byte slot — exactly the cap. Boundary pin: drift in the
14499        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
14500        // simultaneously, mirroring
14501        // `pubsub_contrato_subject_max_length_validates` and
14502        // `http_contrato_endpoint_max_length_validates` on the peer
14503        // payload axes.
14504        let big = "a".repeat(512);
14505        assert_eq!(big.len(), 512);
14506        let mut s = three_member_spec();
14507        s.contratos.push(WitContract {
14508            de: "payment".into(),
14509            para: "catalog".into(),
14510            wit: "wasi:keyvalue/store".into(),
14511            endpoint: None,
14512            subject: None,
14513            slot: Some(big),
14514        });
14515        s.validate().unwrap();
14516    }
14517
14518    #[test]
14519    fn store_contrato_slot_accepts_canonical_forms() {
14520        // Positive-set sweep: every canonical kv slot template the
14521        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
14522        // (single-token identifiers, path-namespaced `$`-templates,
14523        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
14524        // snake_case / kebab-case / MixedCase tokens, digit-bearing
14525        // tokens, percent-encoded fragments) must remain valid
14526        // contrato slots too. Drift between this list and the
14527        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
14528        // surfaces at the shared predicate — one source of truth.
14529        // Uses a fresh `(payment, catalog)` edge so none of the swept
14530        // slots collide with the pre-existing entries in
14531        // `three_member_spec`.
14532        for slot in [
14533            "checkout",
14534            "checkout/$orderId",
14535            "users:{tenant}/{id}",
14536            "session.<sid>",
14537            "session.tokens.<sid>",
14538            "snake_case_key",
14539            "kebab-case-key",
14540            "MixedCase",
14541            "shard0",
14542            "v2/key",
14543            "users/caf%C3%A9",
14544        ] {
14545            let mut s = three_member_spec();
14546            s.contratos.push(WitContract {
14547                de: "payment".into(),
14548                para: "catalog".into(),
14549                wit: "wasi:keyvalue/store".into(),
14550                endpoint: None,
14551                subject: None,
14552                slot: Some(slot.into()),
14553            });
14554            s.validate()
14555                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
14556        }
14557    }
14558
14559    #[test]
14560    fn contrato_slot_empty_takes_precedence_over_invalid() {
14561        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
14562        // diagnostic on `""` and must lead — the value-shape gate is
14563        // only reached after the empty-check fires. Mirrors
14564        // `contrato_subject_empty_takes_precedence_over_invalid` and
14565        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14566        // the peer payload axes.
14567        let mut s = three_member_spec();
14568        s.contratos.push(WitContract {
14569            de: "payment".into(),
14570            para: "catalog".into(),
14571            wit: "wasi:keyvalue/store".into(),
14572            endpoint: None,
14573            subject: None,
14574            slot: Some(String::new()),
14575        });
14576        let err = s.validate().unwrap_err();
14577        assert!(
14578            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
14579            "got {err:?}"
14580        );
14581    }
14582
14583    #[test]
14584    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
14585        // Diagnostic-shape pin — the offending `:slot` + `:de` +
14586        // `:para` + a non-empty reason flow through verbatim so the
14587        // author can grep their caixa.lisp for the offending contrato
14588        // block and fix it in one edit. Same shape as
14589        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
14590        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
14591        // on the peer payload axes.
14592        let err = contrato_slot_err("check out/$order");
14593        match err {
14594            AplicacaoError::ContratoSlotInvalid {
14595                de,
14596                para,
14597                slot,
14598                reason,
14599            } => {
14600                assert_eq!(de, "payment");
14601                assert_eq!(para, "catalog");
14602                assert_eq!(slot, "check out/$order");
14603                assert!(!reason.is_empty(), "reason field must be non-empty");
14604            }
14605            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
14606        }
14607    }
14608
14609    #[test]
14610    fn target_view_store_slot_passes_through_to_typed_view() {
14611        // The compounding theorem on the store axis: every
14612        // `WitTarget::Store { slot }` returned by `target()` carries a
14613        // kv-backend-accepted slot template. Renderers downstream of
14614        // `typed_view()` (the future per-Servico `:capabilities
14615        // wasi:keyvalue/store` axis emitter, the future `feira app
14616        // graph` view's slot labeller, the future kv-provider CR
14617        // materializer) can rely on this without re-checking — the
14618        // type system carries the proof. Mirrors
14619        // `target_view_pubsub_subject_passes_through_to_typed_view` on
14620        // the peer payload axis.
14621        let store = WitContract {
14622            de: "a".into(),
14623            para: "b".into(),
14624            wit: "wasi:keyvalue/store".into(),
14625            endpoint: None,
14626            subject: None,
14627            slot: Some("checkout/$orderId".into()),
14628        };
14629        match store.target().unwrap() {
14630            WitTarget::Store { slot } => {
14631                assert_eq!(slot, "checkout/$orderId");
14632            }
14633            other => panic!("expected Store, got {other:?}"),
14634        }
14635    }
14636
14637    #[test]
14638    fn rejects_self_loop_in_synchronous_contratos() {
14639        // A synchronous self-edge (`cart → cart` over HTTP) is now
14640        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
14641        // "this edge is degenerate" diagnostic — rather than incidentally
14642        // by the cycle detector framing it as a `["cart", "cart"]`
14643        // multi-node deadlock.
14644        let mut s = three_member_spec();
14645        s.contratos.push(contract_http("cart", "cart", "/loop"));
14646        let err = s.validate().unwrap_err();
14647        match err {
14648            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
14649                assert_eq!(caixa, "cart");
14650                assert_eq!(wit, "wasi:http/proxy");
14651            }
14652            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14653        }
14654    }
14655
14656    #[test]
14657    fn rejects_self_loop_in_pubsub_contratos() {
14658        // The cycle detector excludes pub-sub edges (acyclic by
14659        // construction), so before the explicit gate a `nats:pub-sub`
14660        // self-edge silently validated and rendered a self-allow CNP.
14661        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
14662        let mut s = three_member_spec();
14663        s.contratos.push(WitContract {
14664            de: "payment".into(),
14665            para: "payment".into(),
14666            wit: "nats:pub-sub".into(),
14667            endpoint: None,
14668            subject: Some("rio.events.payment".into()),
14669            slot: None,
14670        });
14671        let err = s.validate().unwrap_err();
14672        match err {
14673            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
14674                assert_eq!(caixa, "payment");
14675                assert_eq!(wit, "nats:pub-sub");
14676            }
14677            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14678        }
14679    }
14680
14681    #[test]
14682    fn self_loop_fires_before_payload_shape_check() {
14683        // The structural "this edge can't exist" error precedes the
14684        // narrower payload-shape diagnostics: a self-edge carrying an
14685        // otherwise-malformed endpoint still reports ContratoSelfLoop,
14686        // not ContratoEndpointInvalid.
14687        let mut s = three_member_spec();
14688        s.contratos.push(WitContract {
14689            de: "cart".into(),
14690            para: "cart".into(),
14691            wit: "wasi:http/proxy".into(),
14692            endpoint: Some("not-absolute".into()),
14693            subject: None,
14694            slot: None,
14695        });
14696        match s.validate().unwrap_err() {
14697            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
14698            other => panic!("expected ContratoSelfLoop, got {other:?}"),
14699        }
14700    }
14701
14702    #[test]
14703    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
14704        // A self-edge naming a non-member reports the more fundamental
14705        // ContratoMemberMissing first (the member doesn't exist), so the
14706        // self-loop gate is reached only once both endpoints resolve.
14707        let mut s = three_member_spec();
14708        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
14709        match s.validate().unwrap_err() {
14710            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
14711            other => panic!("expected ContratoMemberMissing, got {other:?}"),
14712        }
14713    }
14714
14715    #[test]
14716    fn rejects_two_node_synchronous_cycle() {
14717        let mut s = three_member_spec();
14718        // existing edges: cart → catalog, cart → payment
14719        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
14720        s.contratos
14721            .push(contract_http("catalog", "cart", "/refresh"));
14722        let err = s.validate().unwrap_err();
14723        match err {
14724            AplicacaoError::ContratoCycle { cycle } => {
14725                // Cycle traversal should mention both endpoints, with
14726                // the back-edge target appearing as both first and last
14727                // element to close the loop.
14728                assert!(cycle.len() >= 3);
14729                assert_eq!(cycle.first(), cycle.last());
14730                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
14731                assert!(body.contains("cart"));
14732                assert!(body.contains("catalog"));
14733            }
14734            other => panic!("expected ContratoCycle, got {other:?}"),
14735        }
14736    }
14737
14738    #[test]
14739    fn rejects_three_node_synchronous_cycle() {
14740        let mut s = three_member_spec();
14741        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
14742        s.contratos = vec![
14743            contract_http("catalog", "cart", "/x"),
14744            contract_http("cart", "payment", "/y"),
14745            contract_http("payment", "catalog", "/z"),
14746        ];
14747        let err = s.validate().unwrap_err();
14748        match err {
14749            AplicacaoError::ContratoCycle { cycle } => {
14750                assert_eq!(cycle.first(), cycle.last());
14751                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
14752                assert_eq!(body.len(), 3);
14753                assert!(body.contains("cart"));
14754                assert!(body.contains("catalog"));
14755                assert!(body.contains("payment"));
14756            }
14757            other => panic!("expected ContratoCycle, got {other:?}"),
14758        }
14759    }
14760
14761    #[test]
14762    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
14763        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
14764        // "acyclic by construction" — so a cycle whose closing edge
14765        // is pub-sub should NOT raise ContratoCycle.
14766        let mut s = three_member_spec();
14767        s.contratos = vec![
14768            contract_http("catalog", "cart", "/x"),
14769            contract_http("cart", "payment", "/y"),
14770            // Closing edge is pub-sub — async; not a sync deadlock.
14771            WitContract {
14772                de: "payment".into(),
14773                para: "catalog".into(),
14774                wit: "nats:pub-sub".into(),
14775                endpoint: None,
14776                subject: Some("checkout.events.charge.completed".into()),
14777                slot: None,
14778            },
14779        ];
14780        s.validate().expect("pub-sub edge breaks the sync cycle");
14781    }
14782
14783    #[test]
14784    fn store_edge_counts_as_synchronous_for_cycle_detection() {
14785        // wasi:keyvalue/store is request/response; a cycle through one
14786        // *is* a sync deadlock, just like HTTP.
14787        let mut s = three_member_spec();
14788        s.contratos = vec![
14789            contract_http("catalog", "cart", "/x"),
14790            WitContract {
14791                de: "cart".into(),
14792                para: "catalog".into(),
14793                wit: "wasi:keyvalue/store".into(),
14794                endpoint: None,
14795                subject: None,
14796                slot: Some("session/$id".into()),
14797            },
14798        ];
14799        let err = s.validate().unwrap_err();
14800        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
14801    }
14802
14803    #[test]
14804    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
14805        // Capability-only edges (unknown WIT shape, no payload) default
14806        // to synchronous — safer; authors with truly async capability
14807        // semantics can model them as pub-sub explicitly.
14808        let mut s = three_member_spec();
14809        s.contratos = vec![
14810            contract_http("catalog", "cart", "/x"),
14811            WitContract {
14812                de: "cart".into(),
14813                para: "catalog".into(),
14814                wit: "custom:exchange".into(),
14815                endpoint: None,
14816                subject: None,
14817                slot: None,
14818            },
14819        ];
14820        let err = s.validate().unwrap_err();
14821        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
14822    }
14823
14824    #[test]
14825    fn long_acyclic_chain_validates() {
14826        // A long sync chain (no back-edges) must validate even when
14827        // every node is reachable from the first.
14828        let mut s = three_member_spec();
14829        s.membros = vec![
14830            membro("a", "^0.1"),
14831            membro("b", "^0.1"),
14832            membro("c", "^0.1"),
14833            membro("d", "^0.1"),
14834            membro("e", "^0.1"),
14835        ];
14836        s.contratos = vec![
14837            contract_http("a", "b", "/1"),
14838            contract_http("b", "c", "/2"),
14839            contract_http("c", "d", "/3"),
14840            contract_http("d", "e", "/4"),
14841        ];
14842        s.entrada.as_mut().unwrap().para = "a".into();
14843        s.validate().unwrap();
14844    }
14845
14846    #[test]
14847    fn diamond_acyclic_validates() {
14848        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
14849        let mut s = three_member_spec();
14850        s.membros = vec![
14851            membro("a", "^0.1"),
14852            membro("b", "^0.1"),
14853            membro("c", "^0.1"),
14854            membro("d", "^0.1"),
14855        ];
14856        s.contratos = vec![
14857            contract_http("a", "b", "/1"),
14858            contract_http("a", "c", "/2"),
14859            contract_http("b", "d", "/3"),
14860            contract_http("c", "d", "/4"),
14861        ];
14862        s.entrada.as_mut().unwrap().para = "a".into();
14863        s.validate().unwrap();
14864    }
14865
14866    // ── duplicate-`:contratos` build-error gate ──────────────────────────
14867
14868    #[test]
14869    fn rejects_duplicate_http_contrato() {
14870        // Fail-before-pass-after pin: the fixture's `cart → catalog`
14871        // HTTP edge appears once. Push an identical entry — same
14872        // (de, para, wit, endpoint) — and validate() must reject it.
14873        // Until this gate landed the typed surface accepted the
14874        // duplicate silently and caixa-mesh's `cilium_network_policies`
14875        // emitted two ``CiliumNetworkPolicy`` objects with identical
14876        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
14877        // admission rejects on `kubectl apply` far from the source.
14878        let mut s = three_member_spec();
14879        s.contratos
14880            .push(contract_http("cart", "catalog", "/products/:id"));
14881        let err = s.validate().unwrap_err();
14882        assert!(
14883            matches!(
14884                err,
14885                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14886                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
14887            ),
14888            "got {err:?}"
14889        );
14890    }
14891
14892    #[test]
14893    fn rejects_duplicate_pubsub_contrato() {
14894        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
14895        // edges with identical (de, para, subject) are degenerate;
14896        // pin that the typed surface refuses both at validate time.
14897        let mut s = three_member_spec();
14898        let pubsub = WitContract {
14899            de: "payment".into(),
14900            para: "cart".into(),
14901            wit: "nats:pub-sub".into(),
14902            endpoint: None,
14903            subject: Some("checkout.events.charge.failed".into()),
14904            slot: None,
14905        };
14906        s.contratos.push(pubsub.clone());
14907        s.contratos.push(pubsub);
14908        let err = s.validate().unwrap_err();
14909        assert!(
14910            matches!(
14911                err,
14912                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14913                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
14914            ),
14915            "got {err:?}"
14916        );
14917    }
14918
14919    #[test]
14920    fn rejects_duplicate_store_contrato() {
14921        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
14922        // edges with identical (de, para, slot) collapse to one mesh-
14923        // policy edge; pin the build error.
14924        let mut s = three_member_spec();
14925        let store = WitContract {
14926            de: "cart".into(),
14927            para: "payment".into(),
14928            wit: "wasi:keyvalue/store".into(),
14929            endpoint: None,
14930            subject: None,
14931            slot: Some("checkout/$orderId".into()),
14932        };
14933        // Drop the conflicting HTTP `cart → payment` edge from the
14934        // fixture so the duplicate-store pair is the only one
14935        // distinguishable on this pair.
14936        s.contratos
14937            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14938        s.contratos.push(store.clone());
14939        s.contratos.push(store);
14940        let err = s.validate().unwrap_err();
14941        assert!(
14942            matches!(
14943                err,
14944                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
14945                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
14946            ),
14947            "got {err:?}"
14948        );
14949    }
14950
14951    #[test]
14952    fn rejects_duplicate_capability_contrato() {
14953        // Same gate on the pure-capability axis (no payload selector).
14954        // Two contracts with identical (de, para, wit) and no
14955        // endpoint/subject/slot are duplicate edges; pin so a future
14956        // `target_label` change can't accidentally collapse the
14957        // capability arm into a None-shaped key that compares equal
14958        // to a populated one.
14959        let mut s = three_member_spec();
14960        let capability = WitContract {
14961            de: "cart".into(),
14962            para: "catalog".into(),
14963            wit: "pleme:cap/audit".into(),
14964            endpoint: None,
14965            subject: None,
14966            slot: None,
14967        };
14968        s.contratos.push(capability.clone());
14969        s.contratos.push(capability);
14970        let err = s.validate().unwrap_err();
14971        match err {
14972            AplicacaoError::ContratoDuplicate {
14973                de,
14974                para,
14975                wit,
14976                target,
14977            } => {
14978                assert_eq!(de, "cart");
14979                assert_eq!(para, "catalog");
14980                assert_eq!(wit, "pleme:cap/audit");
14981                assert!(
14982                    target.contains("capability"),
14983                    "capability-edge duplicate diagnostic must surface the \
14984                     no-payload shape (got target = {target:?})"
14985                );
14986            }
14987            other => panic!("expected ContratoDuplicate, got {other:?}"),
14988        }
14989    }
14990
14991    #[test]
14992    fn accepts_distinct_http_paths_between_same_pair() {
14993        // Negative pin: two HTTP contracts cart → catalog at distinct
14994        // endpoints (`/products/:id` and `/search`) are *not*
14995        // duplicates — they're distinct typed edges differing on the
14996        // payload axis. The duplicate-gate must not over-match here,
14997        // since the cart-calls-catalog-on-multiple-paths shape is the
14998        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
14999        // example: cart calls catalog at /products/:id, payment at
15000        // /charge — same shape extends to two paths on one para).
15001        let mut s = three_member_spec();
15002        s.contratos
15003            .push(contract_http("cart", "catalog", "/search"));
15004        s.validate()
15005            .expect("distinct endpoints between same (de, para) must validate");
15006    }
15007
15008    #[test]
15009    fn accepts_same_endpoint_on_different_pairs() {
15010        // Negative pin: the same `/charge` endpoint reused on two
15011        // different (de, para) pairs is two distinct edges, not a
15012        // duplicate. Pinning this shape so the gate's identity key
15013        // includes both `de` and `para` (not just `(wit, endpoint)`).
15014        let mut s = three_member_spec();
15015        s.contratos
15016            .push(contract_http("payment", "catalog", "/charge"));
15017        s.validate()
15018            .expect("same endpoint reused on distinct (de, para) must validate");
15019    }
15020
15021    #[test]
15022    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
15023        // Pin the diagnostic shape: the duplicate-edge error names
15024        // *which* target field carried the conflict, so the author
15025        // doesn't have to re-grep the source caixa.lisp to find it.
15026        // Same self-locating diagnostic discipline as
15027        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
15028        let mut s = three_member_spec();
15029        s.contratos
15030            .push(contract_http("cart", "catalog", "/products/:id"));
15031        let err = s.validate().unwrap_err();
15032        let msg = format!("{err}");
15033        assert!(
15034            msg.contains("\"/products/:id\""),
15035            "duplicate-contrato diagnostic must name the offending \
15036             :endpoint payload (got: {msg:?})"
15037        );
15038        assert!(
15039            msg.contains("cart") && msg.contains("catalog"),
15040            "diagnostic must name both endpoints of the duplicate edge \
15041             (got: {msg:?})"
15042        );
15043    }
15044
15045    #[test]
15046    fn duplicate_contrato_gate_runs_after_membership_check() {
15047        // Order pin: a duplicate contract whose `:de` is *also* not in
15048        // `:membros` surfaces the membership error first — the
15049        // missing-member diagnostic is more locating than the
15050        // duplicate-edge one (the author has to fix the membership
15051        // before the duplicate is meaningful). Same ordering
15052        // discipline as `membros_validation_runs_before_contratos_membership_check`.
15053        let mut s = three_member_spec();
15054        s.contratos.push(contract_http("phantom", "catalog", "/x"));
15055        s.contratos.push(contract_http("phantom", "catalog", "/x"));
15056        let err = s.validate().unwrap_err();
15057        assert!(
15058            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
15059            "membership-missing must fire before duplicate-edge (got {err:?})"
15060        );
15061    }
15062
15063    #[test]
15064    fn duplicate_contrato_gate_runs_after_target_shape_check() {
15065        // Order pin: a contract with a malformed target (e.g. an HTTP
15066        // wit world with an empty :endpoint) surfaces the target-shape
15067        // error first, not the duplicate one. Even when two such
15068        // malformed entries are identical, the per-contract `target()`
15069        // check fires inside the loop *before* the duplicate-key
15070        // insert, so the diagnostic remains the most-locating one.
15071        let mut s = three_member_spec();
15072        let malformed = WitContract {
15073            de: "cart".into(),
15074            para: "catalog".into(),
15075            wit: "wasi:http/proxy".into(),
15076            endpoint: Some(String::new()),
15077            subject: None,
15078            slot: None,
15079        };
15080        s.contratos.push(malformed.clone());
15081        s.contratos.push(malformed);
15082        let err = s.validate().unwrap_err();
15083        assert!(
15084            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
15085            "endpoint-empty must fire before duplicate-edge (got {err:?})"
15086        );
15087    }
15088
15089    #[test]
15090    fn wit_target_label_pins_per_variant_format() {
15091        // Label format is the single source of truth every duplicate-
15092        // `:contratos` diagnostic + every future `feira app graph`
15093        // consumer routes through. Pin the shape per variant so a
15094        // future edit to `WitTarget::label` (e.g. a JSON emitter that
15095        // strips the leading `:`, or a rename from `endpoint` →
15096        // `path`) surfaces as a red-red test rather than as a silent
15097        // downstream diagnostic drift. Together with the exhaustive
15098        // `match` on `WitTarget` inside `label()`, adding a future
15099        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
15100        // peer, per-edge WIT registry variants) is a compile error at
15101        // the label site — not a fall-through into the `Capability`
15102        // "no payload" default the prior raw-field-probe helper
15103        // silently landed on.
15104        assert_eq!(
15105            WitTarget::Http {
15106                endpoint: "/charge",
15107            }
15108            .label(),
15109            "\
15110:endpoint \"/charge\""
15111        );
15112        assert_eq!(
15113            WitTarget::PubSub {
15114                subject: "events.checkout.paid",
15115            }
15116            .label(),
15117            "\
15118:subject \"events.checkout.paid\""
15119        );
15120        assert_eq!(
15121            WitTarget::Store {
15122                slot: "checkout/$order",
15123            }
15124            .label(),
15125            "\
15126:slot \"checkout/$order\""
15127        );
15128        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
15129        // Capability-arm label routes through the lifted
15130        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
15131        // declaration per arm, next to the variant" discipline the
15132        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
15133        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15134        // consts already carry extends to the payload-less arm; the
15135        // byte-string equality pin below plus this label-routes-
15136        // through-the-const pin make a future rebrand on either the
15137        // const declaration or the `label()` template a build error
15138        // here rather than a downstream consumer surprise.
15139        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
15140        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
15141    }
15142
15143    #[test]
15144    fn wit_target_display_routes_through_label_helper() {
15145        // Fail-before-pass-after pin on the fourth (and only remaining)
15146        // typed-shape-discriminator axis to converge onto the
15147        // three-path-convergence discipline the sibling M3
15148        // [`PlacementStrategy`] (0a2f653) and M2
15149        // [`crate::supervisor::RestartStrategy`] /
15150        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
15151        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
15152        // through [`WitTarget::label`], so every consumer reaching for
15153        // `format!("{v}")` on a typed payload target lands on the same
15154        // stable author-facing byte-string [`WitTarget::label`] returns
15155        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
15156        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
15157        // `:contratos` gate seeds via [`WitTarget::label`] at
15158        // aplicacao.rs:5491 already threads through.
15159        //
15160        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
15161        // through to the `Debug` derive's structural output
15162        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
15163        // rather than the [`WitTarget::label`] helper's stable byte-
15164        // string (`:endpoint "/charge"` — the author-facing `:contratos`
15165        // keyword form). Every future consumer that reaches for
15166        // `format!("{target}")` — the canonical shape every user-facing
15167        // pretty-print site on the sibling typed-enum axes
15168        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
15169        // [`crate::supervisor::RestartPolicy`]) already uses — would
15170        // silently land under a different byte-string than the
15171        // [`WitTarget::label`] callers that the duplicate-`:contratos`
15172        // diagnostic already threads through, with the mismatch
15173        // surfacing as a downstream diagnostic / graph / audit line
15174        // reading one spelling while the substrate's own gate emitted
15175        // another.
15176        //
15177        // Pin the routing here so a future
15178        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
15179        // that hand-rolls the per-arm formatting instead of delegating
15180        // to [`WitTarget::label`] fails at caixa-core build time.
15181        for variant in [
15182            WitTarget::Http {
15183                endpoint: "/charge",
15184            },
15185            WitTarget::PubSub {
15186                subject: "events.checkout.paid",
15187            },
15188            WitTarget::Store {
15189                slot: "checkout/$order",
15190            },
15191            WitTarget::Capability,
15192        ] {
15193            assert_eq!(
15194                variant.to_string(),
15195                variant.label(),
15196                "WitTarget::{variant:?} Display must route through \
15197                 WitTarget::label (single source of truth: the lifted \
15198                 payload_pair 4-arm dispatch the label helper already \
15199                 threads through)"
15200            );
15201        }
15202    }
15203
15204    #[test]
15205    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
15206        // Consumer-side pin on the three-path convergence:
15207        // [`std::fmt::Display`] agrees byte-for-byte with the
15208        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
15209        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
15210        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
15211        // Pre-lift the two paths were structurally independent — the
15212        // substrate-side gate reached for `target_view.label()` while a
15213        // future downstream diagnostic / graph / audit line reaching
15214        // for `format!("{target}")` would silently land on the `Debug`
15215        // derive's structural output. Pin the two paths byte-for-byte
15216        // here so any future variant addition (M4 `Rest`/`Grpc` split
15217        // of [`WitTarget::Http`], `Queue`-shaped peer of
15218        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
15219        // match error at [`WitTarget::payload_pair`] rather than a
15220        // silent per-consumer dispatch miss.
15221        for variant in [
15222            WitTarget::Http {
15223                endpoint: "/charge",
15224            },
15225            WitTarget::PubSub {
15226                subject: "events.checkout.paid",
15227            },
15228            WitTarget::Store {
15229                slot: "checkout/$order",
15230            },
15231            WitTarget::Capability,
15232        ] {
15233            assert_eq!(
15234                format!("{variant}"),
15235                variant.label(),
15236                "WitTarget::{variant:?} Display byte-string must match \
15237                 the AplicacaoError::ContratoDuplicate `target:` carrier \
15238                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
15239                 seeds via WitTarget::label — three-path convergence: \
15240                 Display + label + payload_pair all resolve to the same \
15241                 per-arm byte-string"
15242            );
15243        }
15244    }
15245
15246    #[test]
15247    fn wit_target_payload_pair_pins_per_variant() {
15248        // Pin the per-arm `(field-name, payload)` pair single-sourced
15249        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
15250        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
15251        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
15252        // and [`WitTarget::field_name`] (returns the first component)
15253        // route through. Until this lift landed [`WitTarget::label`]
15254        // dispatched on the same three arms with a per-arm
15255        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
15256        // paired [`WitTarget::HTTP_FIELD_NAME`] /
15257        // [`WitTarget::PUBSUB_FIELD_NAME`] /
15258        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
15259        // canonical "same shape, written N times" duplication
15260        // THEORY.md §I.3.5 promotes to a build-time concern. A future
15261        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
15262        // [`WitTarget::Http`], `Queue`-shaped peer of
15263        // [`WitTarget::Store`]) is one match-arm edit at
15264        // [`WitTarget::payload_pair`], visible here as a compile-time
15265        // exhaustiveness error on both this pin and the label-format
15266        // pin above.
15267        assert_eq!(
15268            WitTarget::Http {
15269                endpoint: "/charge"
15270            }
15271            .payload_pair(),
15272            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
15273        );
15274        assert_eq!(
15275            WitTarget::PubSub {
15276                subject: "events.x",
15277            }
15278            .payload_pair(),
15279            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
15280        );
15281        assert_eq!(
15282            WitTarget::Store {
15283                slot: "checkout/$order",
15284            }
15285            .payload_pair(),
15286            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
15287        );
15288        assert_eq!(WitTarget::Capability.payload_pair(), None);
15289    }
15290
15291    #[test]
15292    fn wit_target_field_name_pins_per_variant() {
15293        // Pin the per-arm author-facing `:contratos` payload field
15294        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
15295        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15296        // + returned by [`WitTarget::field_name`]. Every downstream
15297        // consumer (the [`WitContract::target`] gate's `expected:`
15298        // scalar, the [`WitTarget::label`] template's keyword prefix,
15299        // the `feira app graph` verb's `endpoint=…` prefix) routes
15300        // through the same three peer consts, so a rename on the
15301        // author-surface `(defcaixa … :contratos ((:de … :para …
15302        // :wit … :endpoint …)))` field lands in exactly one place.
15303        assert_eq!(
15304            WitTarget::Http {
15305                endpoint: "/charge"
15306            }
15307            .field_name(),
15308            Some(WitTarget::HTTP_FIELD_NAME),
15309        );
15310        assert_eq!(
15311            WitTarget::PubSub {
15312                subject: "events.x",
15313            }
15314            .field_name(),
15315            Some(WitTarget::PUBSUB_FIELD_NAME),
15316        );
15317        assert_eq!(
15318            WitTarget::Store {
15319                slot: "checkout/$order",
15320            }
15321            .field_name(),
15322            Some(WitTarget::STORE_FIELD_NAME),
15323        );
15324        // Capability arm carries no payload field — the diagnostic
15325        // never reports `expected: "capability"` because the gate's
15326        // Capability arm accepts no payload at all (it fires the
15327        // "expected: none" WrongTarget error instead), so the field-
15328        // name method returns None here rather than a placeholder.
15329        assert_eq!(WitTarget::Capability.field_name(), None);
15330
15331        // Peer const scalar values pinned so a rename on either side
15332        // (author-surface field name in the `(defcaixa …)` DSL, or
15333        // the diagnostic's `expected:` scalar) can't drift without
15334        // failing here first.
15335        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
15336        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
15337        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
15338    }
15339
15340    #[test]
15341    fn wit_target_payload_pins_per_variant() {
15342        // Pin the per-arm payload scalar single-sourced onto the
15343        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
15344        // [`WitTarget::payload`] — the peer per-half projection to
15345        // [`WitTarget::field_name`] on the paired sub-selector axis. The
15346        // three payload-carrying arms round-trip their author-declared
15347        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
15348        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
15349        // the payload-less [`WitTarget::Capability`] arm returns `None`.
15350        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
15351        // (c6ec2af) pin on the Component-0 projection axis, extended
15352        // onto the Component-1 projection axis so both per-half readers
15353        // on the paired dispatch carry their own byte-shape pin.
15354        assert_eq!(
15355            WitTarget::Http {
15356                endpoint: "/charge",
15357            }
15358            .payload(),
15359            Some("/charge"),
15360        );
15361        assert_eq!(
15362            WitTarget::PubSub {
15363                subject: "events.x",
15364            }
15365            .payload(),
15366            Some("events.x"),
15367        );
15368        assert_eq!(
15369            WitTarget::Store {
15370                slot: "checkout/$order",
15371            }
15372            .payload(),
15373            Some("checkout/$order"),
15374        );
15375        assert_eq!(WitTarget::Capability.payload(), None);
15376    }
15377
15378    #[test]
15379    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
15380        // Per-variant equivalence pin: for every arm of [`WitTarget`],
15381        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
15382        // byte-for-byte. Guards the drift surface where a future refactor
15383        // that split one accessor off the shared match onto its own
15384        // dispatch — a well-meaning "inline the pair back into per-half
15385        // fields for one crate-internal caller who only wanted one half"
15386        // or a scratch `impl` shadowing the derived projection — would
15387        // silently desynchronize [`WitTarget::payload`] from the
15388        // authoritative [`WitTarget::payload_pair`] dispatch, and every
15389        // downstream consumer that thinks "the payload half of the pair"
15390        // would drift from the diagnostic / graph consumers reading the
15391        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
15392        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
15393        // per-half projection pin (`gitrefspec_ref_pair_projects_
15394        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
15395        // FluxCD source-controller `spec.ref.<field>` axis — same "one
15396        // paired dispatch, both per-half projections agree byte-for-
15397        // byte" discipline extended onto the M3 `:contratos` payload-
15398        // arm surface.
15399        for variant in [
15400            WitTarget::Http {
15401                endpoint: "/charge",
15402            },
15403            WitTarget::PubSub {
15404                subject: "events.checkout.paid",
15405            },
15406            WitTarget::Store {
15407                slot: "checkout/$order",
15408            },
15409            WitTarget::Capability,
15410        ] {
15411            let via_projection = variant.payload();
15412            let via_pair = variant.payload_pair().map(|(_, p)| p);
15413            assert_eq!(
15414                via_projection, via_pair,
15415                "WitTarget::{variant:?} payload() must equal \
15416                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
15417                 regression that splits the two per-half projections off \
15418                 their shared match would silently desynchronize the \
15419                 payload accessor from the paired dispatch every \
15420                 diagnostic / graph consumer reads through",
15421            );
15422        }
15423    }
15424
15425    #[test]
15426    fn wit_target_http_endpoint_pins_per_variant() {
15427        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
15428        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
15429        // substrate-primitive per-arm post-projection accessor every
15430        // L7-HTTP-facing consumer routes through, sibling to the peer
15431        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
15432        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
15433        // arm round-trips its author-declared endpoint verbatim as
15434        // `Some("/charge")`; the three sibling arms
15435        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
15436        // [`WitTarget::Capability`]) each return `None` because they
15437        // carry no HTTP endpoint by definition. Same fail-before-pass-
15438        // after per-variant discipline as the sibling
15439        // `wit_target_payload_pins_per_variant` (5d6dc92) /
15440        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
15441        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
15442        // the peer pan-arm / per-half projection axes — extended onto
15443        // the per-arm HTTP-shape post-projection axis so a future
15444        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
15445        // [`WitTarget::Http`], a `Queue`-shaped peer of
15446        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
15447        // error on the sibling [`WitTarget::http_endpoint`] match arms
15448        // whose payload the L7-HTTP-shape accept-set is meant to bound.
15449        assert_eq!(
15450            WitTarget::Http {
15451                endpoint: "/charge",
15452            }
15453            .http_endpoint(),
15454            Some("/charge"),
15455        );
15456        assert_eq!(
15457            WitTarget::PubSub {
15458                subject: "events.checkout.paid",
15459            }
15460            .http_endpoint(),
15461            None,
15462        );
15463        assert_eq!(
15464            WitTarget::Store {
15465                slot: "checkout/$order",
15466            }
15467            .http_endpoint(),
15468            None,
15469        );
15470        assert_eq!(WitTarget::Capability.http_endpoint(), None);
15471    }
15472
15473    #[test]
15474    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
15475        // Per-variant coherence pin: for every arm of [`WitTarget`],
15476        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
15477        // arm (both project the same author-declared request-path
15478        // scalar), and returns `None` on every sibling arm regardless of
15479        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
15480        // Store carry their own payload the pan-arm accessor surfaces,
15481        // but that payload is not an HTTP endpoint — the per-arm
15482        // accessor must not leak it through the HTTP-shape channel).
15483        // Guards the drift surface where a future refactor that
15484        // conflated the per-arm HTTP projection with the pan-arm
15485        // [`WitTarget::payload`] projection — a well-meaning "one
15486        // accessor for the L7 branch, one for the graph" collapse that
15487        // routes both through the same 4-arm dispatch — would silently
15488        // widen the L7-HTTP-shape accept-set onto pub-sub / store
15489        // payloads at the caixa-mesh L7 emit branch, admitting a
15490        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
15491        // rule with the operator-side apply-time symptom (Cilium's
15492        // eBPF data-plane rejects every ingress edge whose L7 filter
15493        // doesn't match the wire-format HTTP request line) far from
15494        // the source refactor. Sibling to the peer
15495        // `wit_target_payload_matches_payload_pair_second_component_
15496        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
15497        // extended onto the per-arm HTTP specialization axis so both
15498        // the pan-arm and the per-arm projections carry their own
15499        // byte-shape coherence witness against the substrate's typed
15500        // arm-family accept-set.
15501        for variant in [
15502            WitTarget::Http {
15503                endpoint: "/charge",
15504            },
15505            WitTarget::PubSub {
15506                subject: "events.checkout.paid",
15507            },
15508            WitTarget::Store {
15509                slot: "checkout/$order",
15510            },
15511            WitTarget::Capability,
15512        ] {
15513            let per_arm = variant.http_endpoint();
15514            let pan_arm = variant.payload();
15515            if variant.is_http() {
15516                assert_eq!(
15517                    per_arm, pan_arm,
15518                    "WitTarget::{variant:?} http_endpoint() must equal \
15519                     payload() on the Http arm — a per-arm-vs-pan-arm \
15520                     split would silently drift the L7 emit branch's \
15521                     path-scalar source from the graph verb's payload \
15522                     scalar source",
15523                );
15524            } else {
15525                assert_eq!(
15526                    per_arm, None,
15527                    "WitTarget::{variant:?} http_endpoint() must return \
15528                     None on non-Http arms — a leak that surfaced a \
15529                     pub-sub :subject or a key/value :slot through the \
15530                     HTTP-endpoint accessor would silently widen the \
15531                     Cilium L7 HTTP `path:` rule accept-set onto \
15532                     protocol shapes Cilium's eBPF data-plane can't \
15533                     introspect",
15534                );
15535            }
15536        }
15537    }
15538
15539    #[test]
15540    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
15541        // Per-variant coherence pin: for every arm of [`WitTarget`],
15542        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
15543        // drift surface where a future extension of the
15544        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
15545        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
15546        // accessor to cover both peers) landed without a paired
15547        // extension of the [`gen_platform::IsVariant`]-derived
15548        // `is_http()` predicate's accept-set, or vice versa — a
15549        // regression that split the "which arms count as HTTP-shaped
15550        // for L7-path emission?" answer between two dispatch surfaces
15551        // the substrate ships. Sibling to the peer
15552        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
15553        // on the paired dispatch axis — extended onto the per-arm
15554        // predicate-vs-accessor coherence axis so the gen-platform
15555        // IsVariant predicate and the substrate-lifted per-arm
15556        // accessor carry one shared answer to "is this the HTTP arm?".
15557        for variant in [
15558            WitTarget::Http {
15559                endpoint: "/charge",
15560            },
15561            WitTarget::PubSub {
15562                subject: "events.checkout.paid",
15563            },
15564            WitTarget::Store {
15565                slot: "checkout/$order",
15566            },
15567            WitTarget::Capability,
15568        ] {
15569            assert_eq!(
15570                variant.http_endpoint().is_some(),
15571                variant.is_http(),
15572                "WitTarget::{variant:?} http_endpoint().is_some() must \
15573                 equal is_http() — a drift would split the L7 emit \
15574                 branch's arm-set gate from the substrate-derived \
15575                 shape-discrimination predicate on the same axis",
15576            );
15577        }
15578    }
15579
15580    #[test]
15581    fn wit_target_pubsub_subject_pins_per_variant() {
15582        // Fail-before-pass-after pin: the substrate-canonical per-arm
15583        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
15584        // is the single dispatch every future pub-sub-facing consumer
15585        // routes through, sibling to the peer [`WitContract::subject`]
15586        // (63e18a0) pre-projection scalar accessor on the raw-field
15587        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
15588        // post-projection per-arm accessor on the sibling HTTP-shape
15589        // axis. The [`WitTarget::PubSub`] arm round-trips its
15590        // author-declared subject verbatim as
15591        // `Some("events.checkout.paid")`; the three sibling arms each
15592        // return `None` because they carry no NATS-shaped subject by
15593        // definition. Same fail-before-pass-after per-variant discipline
15594        // as the sibling `wit_target_http_endpoint_pins_per_variant`
15595        // pin on the peer per-arm axis — extended onto the per-arm
15596        // pub-sub-shape post-projection axis so a future [`WitTarget`]
15597        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
15598        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
15599        // compile-time exhaustiveness error on the sibling
15600        // [`WitTarget::pubsub_subject`] match arms whose payload the
15601        // pub-sub-shape accept-set is meant to bound.
15602        assert_eq!(
15603            WitTarget::PubSub {
15604                subject: "events.checkout.paid",
15605            }
15606            .pubsub_subject(),
15607            Some("events.checkout.paid"),
15608        );
15609        assert_eq!(
15610            WitTarget::Http {
15611                endpoint: "/charge",
15612            }
15613            .pubsub_subject(),
15614            None,
15615        );
15616        assert_eq!(
15617            WitTarget::Store {
15618                slot: "checkout/$order",
15619            }
15620            .pubsub_subject(),
15621            None,
15622        );
15623        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
15624    }
15625
15626    #[test]
15627    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
15628        // Per-variant coherence pin: for every arm of [`WitTarget`],
15629        // `.pubsub_subject()` equals `.payload()` on the
15630        // [`WitTarget::PubSub`] arm (both project the same
15631        // author-declared subject scalar), and returns `None` on every
15632        // sibling arm regardless of whether [`WitTarget::payload`]
15633        // itself returns `Some` (Http / Store carry their own payload
15634        // the pan-arm accessor surfaces, but that payload is not a
15635        // pub-sub subject — the per-arm accessor must not leak it
15636        // through the pub-sub-shape channel). Sibling to the peer
15637        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
15638        // coherence pin on the per-arm HTTP-shape axis — extended onto
15639        // the per-arm pub-sub specialization axis so both per-arm
15640        // projections carry their own byte-shape coherence witness
15641        // against the substrate's typed arm-family accept-set.
15642        for variant in [
15643            WitTarget::Http {
15644                endpoint: "/charge",
15645            },
15646            WitTarget::PubSub {
15647                subject: "events.checkout.paid",
15648            },
15649            WitTarget::Store {
15650                slot: "checkout/$order",
15651            },
15652            WitTarget::Capability,
15653        ] {
15654            let per_arm = variant.pubsub_subject();
15655            let pan_arm = variant.payload();
15656            if variant.is_pubsub() {
15657                assert_eq!(
15658                    per_arm, pan_arm,
15659                    "WitTarget::{variant:?} pubsub_subject() must equal \
15660                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
15661                     split would silently drift the pub-sub-shape emit \
15662                     branch's subject-scalar source from the graph verb's \
15663                     payload scalar source",
15664                );
15665            } else {
15666                assert_eq!(
15667                    per_arm, None,
15668                    "WitTarget::{variant:?} pubsub_subject() must return \
15669                     None on non-PubSub arms — a leak that surfaced an \
15670                     HTTP :endpoint or a key/value :slot through the \
15671                     pub-sub-subject accessor would silently widen the \
15672                     downstream NATS-shape accept-set onto protocol \
15673                     shapes NATS servers can't route",
15674                );
15675            }
15676        }
15677    }
15678
15679    #[test]
15680    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
15681        // Per-variant coherence pin: for every arm of [`WitTarget`],
15682        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
15683        // drift surface where a future extension of the
15684        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
15685        // without a paired extension of the [`gen_platform::IsVariant`]-
15686        // derived `is_pubsub()` predicate's accept-set, or vice versa
15687        // — a regression that split the "which arms count as pub-sub-
15688        // shaped for subject emission?" answer between two dispatch
15689        // surfaces the substrate ships. Sibling to the peer
15690        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
15691        // pin on the per-arm HTTP-shape axis — extended onto the
15692        // per-arm pub-sub predicate-vs-accessor coherence axis so the
15693        // gen-platform IsVariant predicate and the substrate-lifted
15694        // per-arm accessor carry one shared answer to "is this the
15695        // PubSub arm?".
15696        for variant in [
15697            WitTarget::Http {
15698                endpoint: "/charge",
15699            },
15700            WitTarget::PubSub {
15701                subject: "events.checkout.paid",
15702            },
15703            WitTarget::Store {
15704                slot: "checkout/$order",
15705            },
15706            WitTarget::Capability,
15707        ] {
15708            assert_eq!(
15709                variant.pubsub_subject().is_some(),
15710                variant.is_pubsub(),
15711                "WitTarget::{variant:?} pubsub_subject().is_some() must \
15712                 equal is_pubsub() — a drift would split the pub-sub \
15713                 emit branch's arm-set gate from the substrate-derived \
15714                 shape-discrimination predicate on the same axis",
15715            );
15716        }
15717    }
15718
15719    #[test]
15720    fn wit_target_store_slot_pins_per_variant() {
15721        // Fail-before-pass-after pin: the substrate-canonical per-arm
15722        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
15723        // is the single dispatch every future store-facing consumer
15724        // routes through, sibling to the peer [`WitContract::slot`]
15725        // pre-projection scalar accessor on the raw-field axis and to
15726        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
15727        // [`WitTarget::pubsub_subject`] post-projection per-arm
15728        // accessors on the sibling per-payload-arm axes. The
15729        // [`WitTarget::Store`] arm round-trips its author-declared
15730        // slot verbatim as `Some("checkout/$order")`; the three
15731        // sibling arms each return `None` because they carry no
15732        // WASI-key/value slot by definition. Same fail-before-pass-
15733        // after per-variant discipline as the sibling
15734        // `wit_target_http_endpoint_pins_per_variant` +
15735        // `wit_target_pubsub_subject_pins_per_variant` pins on the
15736        // peer per-arm axes — extended onto the per-arm store-shape
15737        // post-projection axis so a future [`WitTarget`] variant
15738        // addition trips a compile-time exhaustiveness error on the
15739        // sibling [`WitTarget::store_slot`] match arms whose payload
15740        // the store-shape accept-set is meant to bound.
15741        assert_eq!(
15742            WitTarget::Store {
15743                slot: "checkout/$order",
15744            }
15745            .store_slot(),
15746            Some("checkout/$order"),
15747        );
15748        assert_eq!(
15749            WitTarget::Http {
15750                endpoint: "/charge",
15751            }
15752            .store_slot(),
15753            None,
15754        );
15755        assert_eq!(
15756            WitTarget::PubSub {
15757                subject: "events.checkout.paid",
15758            }
15759            .store_slot(),
15760            None,
15761        );
15762        assert_eq!(WitTarget::Capability.store_slot(), None);
15763    }
15764
15765    #[test]
15766    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
15767        // Per-variant coherence pin: for every arm of [`WitTarget`],
15768        // `.store_slot()` equals `.payload()` on the
15769        // [`WitTarget::Store`] arm (both project the same
15770        // author-declared slot scalar), and returns `None` on every
15771        // sibling arm regardless of whether [`WitTarget::payload`]
15772        // itself returns `Some`. Sibling to the peer
15773        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
15774        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
15775        // pins on the per-arm HTTP and PubSub axes — closes the
15776        // per-arm-vs-pan-arm byte-shape coherence trio across all
15777        // three payload arms.
15778        for variant in [
15779            WitTarget::Http {
15780                endpoint: "/charge",
15781            },
15782            WitTarget::PubSub {
15783                subject: "events.checkout.paid",
15784            },
15785            WitTarget::Store {
15786                slot: "checkout/$order",
15787            },
15788            WitTarget::Capability,
15789        ] {
15790            let per_arm = variant.store_slot();
15791            let pan_arm = variant.payload();
15792            if variant.is_store() {
15793                assert_eq!(
15794                    per_arm, pan_arm,
15795                    "WitTarget::{variant:?} store_slot() must equal \
15796                     payload() on the Store arm — a per-arm-vs-pan-arm \
15797                     split would silently drift the store-shape emit \
15798                     branch's slot-scalar source from the graph verb's \
15799                     payload scalar source",
15800                );
15801            } else {
15802                assert_eq!(
15803                    per_arm, None,
15804                    "WitTarget::{variant:?} store_slot() must return \
15805                     None on non-Store arms — a leak that surfaced an \
15806                     HTTP :endpoint or a NATS :subject through the \
15807                     key/value-slot accessor would silently widen the \
15808                     downstream WASI-key/value slot accept-set onto \
15809                     protocol shapes the kv backends can't route",
15810                );
15811            }
15812        }
15813    }
15814
15815    #[test]
15816    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
15817        // Per-variant coherence pin: for every arm of [`WitTarget`],
15818        // `.store_slot().is_some()` iff `.is_store()`. Guards the
15819        // drift surface where a future extension of the
15820        // [`WitTarget::store_slot`] accessor's accept-set landed
15821        // without a paired extension of the [`gen_platform::IsVariant`]-
15822        // derived `is_store()` predicate's accept-set. Sibling to the
15823        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
15824        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
15825        // pins — closes the per-arm predicate-vs-accessor coherence
15826        // trio across all three payload arms so the gen-platform
15827        // IsVariant predicate and the substrate-lifted per-arm
15828        // accessor carry one shared answer to "is this the Store arm?".
15829        for variant in [
15830            WitTarget::Http {
15831                endpoint: "/charge",
15832            },
15833            WitTarget::PubSub {
15834                subject: "events.checkout.paid",
15835            },
15836            WitTarget::Store {
15837                slot: "checkout/$order",
15838            },
15839            WitTarget::Capability,
15840        ] {
15841            assert_eq!(
15842                variant.store_slot().is_some(),
15843                variant.is_store(),
15844                "WitTarget::{variant:?} store_slot().is_some() must \
15845                 equal is_store() — a drift would split the store-shape \
15846                 emit branch's arm-set gate from the substrate-derived \
15847                 shape-discrimination predicate on the same axis",
15848            );
15849        }
15850    }
15851
15852    #[test]
15853    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
15854        // Fail-before-pass-after cross-axis pin on the trio
15855        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
15856        // payload-carrying arm of [`WitTarget`], exactly one per-arm
15857        // accessor returns `Some(payload)` and the two peers return
15858        // `None`; and on the payload-less [`WitTarget::Capability`]
15859        // arm, all three return `None`. Guards the drift surface where
15860        // a future extension of one per-arm accessor's accept-set (e.g.
15861        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
15862        // that widened `http_endpoint` to cover both peers without
15863        // narrowing the peer `pubsub_subject` / `store_slot` accept-
15864        // sets to keep the partition mutually exclusive) landed without
15865        // threading through the peer per-arm accessors — the resulting
15866        // silent overlap would land the same edge's payload on two
15867        // downstream per-shape emit branches at once, or leak a
15868        // pub-sub subject through the store-slot channel, at renderer
15869        // emit time far from the substrate primitive's arm-widening
15870        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
15871        // 3-way pin on the payload-field-name axis — extended onto the
15872        // per-arm-accessor payload-projection axis so the substrate-
15873        // owned partition invariant is load-bearing at every per-arm
15874        // consumer's read site.
15875        let payload_variants = [
15876            (
15877                WitTarget::Http {
15878                    endpoint: "/charge",
15879                },
15880                "http",
15881            ),
15882            (
15883                WitTarget::PubSub {
15884                    subject: "events.checkout.paid",
15885                },
15886                "pubsub",
15887            ),
15888            (
15889                WitTarget::Store {
15890                    slot: "checkout/$order",
15891                },
15892                "store",
15893            ),
15894        ];
15895        for (variant, own_arm_label) in payload_variants {
15896            let own_arm_hit = match own_arm_label {
15897                "http" => variant.is_http(),
15898                "pubsub" => variant.is_pubsub(),
15899                "store" => variant.is_store(),
15900                other => panic!("unknown own-arm label {other:?}"),
15901            };
15902            let per_arm_results = [
15903                ("http_endpoint", variant.http_endpoint()),
15904                ("pubsub_subject", variant.pubsub_subject()),
15905                ("store_slot", variant.store_slot()),
15906            ];
15907            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
15908            assert_eq!(
15909                some_count, 1,
15910                "WitTarget::{variant:?} must land exactly one per-arm \
15911                 post-projection accessor's Some result — the trio \
15912                 (http_endpoint, pubsub_subject, store_slot) must \
15913                 partition the payload arm-set; got {per_arm_results:?}",
15914            );
15915            assert!(
15916                own_arm_hit,
15917                "WitTarget::{variant:?} own-arm gen-platform predicate \
15918                 must return true on its own arm — a partition failure \
15919                 upstream of this pin",
15920            );
15921            assert!(
15922                variant.payload().is_some(),
15923                "WitTarget::{variant:?} pan-arm payload() must return \
15924                 Some on every payload-carrying arm the trio partitions",
15925            );
15926        }
15927        // The payload-less Capability arm must return None on every
15928        // per-arm accessor — the partition's terminal-fallback shape.
15929        let cap = WitTarget::Capability;
15930        assert_eq!(cap.http_endpoint(), None);
15931        assert_eq!(cap.pubsub_subject(), None);
15932        assert_eq!(cap.store_slot(), None);
15933        assert_eq!(
15934            cap.payload(),
15935            None,
15936            "WitTarget::Capability pan-arm payload() must return None — \
15937             the trio's payload-less-arm coherence witness",
15938        );
15939    }
15940
15941    #[test]
15942    fn wit_target_field_names_are_pairwise_distinct() {
15943        // Distinctness pin: if any two of the three payload-field-name
15944        // scalars ever collapse (e.g. an accidental `endpoint` copy-
15945        // paste over the `subject` const), the [`WitContract::target`]
15946        // gate's diagnostic would point authors at the wrong field —
15947        // an "expected `:endpoint`" error on a pub-sub edge would
15948        // silently misroute the fix. Same cross-axis-distinctness
15949        // discipline as the peer M3 `:placement :estrategia` variant-
15950        // discriminator scalar-value pins (cc8f749) applied to the
15951        // payload-field-name axis.
15952        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
15953        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
15954        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
15955    }
15956
15957    #[test]
15958    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
15959        // Fail-before-pass-after pin: the graph-verb payload column's
15960        // per-arm `{field}={payload}` byte-string is derived through the
15961        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
15962        // payload-carrying arms, not through a hand-rolled per-arm match
15963        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
15964        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15965        // inline. A future variant addition — the M4-and-later per-edge
15966        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
15967        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
15968        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
15969        // and both [`WitTarget::label`] (duplicate-`:contratos`
15970        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
15971        // payload column) pick up the new arm from the same dispatch.
15972        // Prior to this lift the graph verb open-coded the 4-arm match
15973        // in caixa-feira, so a variant addition would have to be threaded
15974        // through both projections in lockstep or the graph verb would
15975        // silently drop the new arm to `(capability-only)`.
15976        for variant in [
15977            WitTarget::Http {
15978                endpoint: "/charge",
15979            },
15980            WitTarget::PubSub {
15981                subject: "events.checkout.paid",
15982            },
15983            WitTarget::Store {
15984                slot: "checkout/$order",
15985            },
15986        ] {
15987            let (field, payload) = variant
15988                .payload_pair()
15989                .expect("payload arm must expose (field, payload)");
15990            assert_eq!(
15991                variant.graph_label(),
15992                format!("{field}={payload}"),
15993                "WitTarget::{variant:?} graph_label must route the \
15994                 `{{field}}={{payload}}` template through payload_pair — \
15995                 a regression to a hand-rolled per-arm match at the graph \
15996                 verb would silently disagree with a future variant \
15997                 addition landed only at payload_pair"
15998            );
15999        }
16000    }
16001
16002    #[test]
16003    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
16004        // Fail-before-pass-after pin on the payload-less arm: the graph
16005        // verb's `(capability-only)` byte-string routes through the
16006        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
16007        // [`WitTarget::Capability`] arm, not through an inline
16008        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
16009        // per-`:contratos` payload column. Peer of the sibling
16010        // [`wit_target_label_pins_per_variant_format`] Capability-arm
16011        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
16012        // extended here onto the third payload-less-arm consumer axis
16013        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
16014        // axis and the wrong-target diagnostic axis).
16015        assert_eq!(
16016            WitTarget::Capability.graph_label(),
16017            WitTarget::CAPABILITY_GRAPH_LABEL,
16018        );
16019        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
16020    }
16021
16022    #[test]
16023    fn wit_target_capability_graph_label_distinct_from_capability_label() {
16024        // Cross-consumer-axis distinctness pin: the graph-verb
16025        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
16026        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
16027        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
16028        // payload)`) surface the payload-less arm on two distinct
16029        // consumer axes; a collapse (an accidental rebrand that lands
16030        // one spelling on both consts, a copy-paste that unifies them
16031        // "for consistency") would silently merge the two byte-strings
16032        // and lose the vocabulary distinction the graph verb's
16033        // compact-column form and the diagnostic's descriptive-clause
16034        // form each carry on purpose. Peer of the sibling 4-way
16035        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
16036        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
16037        // extended here onto the cross-consumer-axis distinctness of the
16038        // two payload-less-arm consts.
16039        assert_ne!(
16040            WitTarget::CAPABILITY_GRAPH_LABEL,
16041            WitTarget::CAPABILITY_LABEL,
16042            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
16043             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
16044             diagnostic) must remain distinct — a collapse would silently \
16045             merge two consumer axes onto one spelling"
16046        );
16047    }
16048
16049    #[test]
16050    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
16051        // 4-way distinctness pin extending the sibling
16052        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
16053        // (which covers only the HTTP / PubSub / Store payload arms)
16054        // onto the fourth scalar the shared
16055        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
16056        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
16057        // (`"none"`), the payload-less Capability-arm rejection scalar.
16058        //
16059        // All four [`WitTarget::HTTP_FIELD_NAME`] /
16060        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16061        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
16062        // dispatch surface [`WitContract::target`] writes onto the
16063        // `ContratoWrongTarget::expected` field — the same `&'static
16064        // str` axis authors read as "this WIT world's shape admits
16065        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
16066        // downstream consumers rely on: an `expected: "endpoint"`
16067        // diagnostic on a Capability-shaped edge tells the author to
16068        // add a `:endpoint "…"` slot to a WIT world that admits none,
16069        // silently misrouting the fix. Until this pin landed the three
16070        // payload-arm consts were distinctness-guarded by the sibling
16071        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
16072        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
16073        // author-facing vocabulary shift from `"none"` to `"endpoint"`
16074        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
16075        // into per-shape peers) would have silently landed one
16076        // Capability-arm rejection on a payload-arm's `expected:` byte-
16077        // string and desynchronized the diagnostic from the author's
16078        // typed shape.
16079        //
16080        // Same 4-way pairwise-distinctness pin discipline as the peer
16081        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
16082        // (cc8f749) applies on the sibling M3 closed-set typed-enum
16083        // scalar-value dispatch axis; extends the pin trajectory the
16084        // sibling `wit_target_field_names_are_pairwise_distinct`
16085        // 3-way pin opened to cover the last unguarded corner on the
16086        // `ContratoWrongTarget::expected` scalar-value axis.
16087        //
16088        // Fail-before-pass-after locally verified by mutating
16089        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
16090        // — this pin fires as expected; restoring passes.
16091        let all = [
16092            WitTarget::HTTP_FIELD_NAME,
16093            WitTarget::PUBSUB_FIELD_NAME,
16094            WitTarget::STORE_FIELD_NAME,
16095            WitTarget::CAPABILITY_EXPECTED,
16096        ];
16097        for (i, a) in all.iter().enumerate() {
16098            for (j, b) in all.iter().enumerate() {
16099                if i != j {
16100                    assert_ne!(
16101                        a, b,
16102                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
16103                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
16104                         pairwise distinct — got duplicate {a:?} at indices \
16105                         {i} and {j}; all four scalars thread through the \
16106                         shared `AplicacaoError::ContratoWrongTarget::expected` \
16107                         &'static str axis, so a collapse silently misdirects \
16108                         the diagnostic on which typed shape the WIT world admits",
16109                    );
16110                }
16111            }
16112        }
16113    }
16114
16115    #[test]
16116    fn wit_target_is_variant_predicates_partition_the_arm_set() {
16117        // Fail-before-pass-after pin on the
16118        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
16119        // each of the four variants exactly one of the generated
16120        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
16121        // predicates returns `true` and the other three return
16122        // `false`. Prior to this derive the only production
16123        // arm-discriminator on [`WitTarget`] — the sync-cycle
16124        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
16125        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
16126        // the variant that expressed no compile-time link back to
16127        // the closed-set typed dispatch a future fifth
16128        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
16129        // split of [`WitTarget::PubSub`] into shape-specific peers,
16130        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
16131        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
16132        // to thread through in lockstep or the DFS exclusion would
16133        // silently disagree with the peer diagnostic templates on
16134        // which arms carry sync-versus-async semantics. Peer of the
16135        // sibling [`crate::CaixaKind`] (f5bba80),
16136        // [`PlacementStrategy`] (766ec63),
16137        // [`crate::supervisor::RestartStrategy`],
16138        // [`crate::supervisor::RestartPolicy`], and
16139        // [`crate::upgrade::UpgradeInstruction`] (915a934)
16140        // `IsVariant` derives on the sibling closed-set typed-enum
16141        // discriminator axes — extends the same one-typed-dispatch-
16142        // per-variant discipline onto the last unlifted closed-set
16143        // typed-enum discriminator on the caixa surface (the M3
16144        // mesh-slot per-`:contratos` target-arm axis), closing the
16145        // arm-discriminator convergence trajectory across every
16146        // closed-set typed enum in caixa-core.
16147        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
16148            (
16149                WitTarget::Http { endpoint: "/x" },
16150                [true, false, false, false],
16151            ),
16152            (
16153                WitTarget::PubSub {
16154                    subject: "events.x",
16155                },
16156                [false, true, false, false],
16157            ),
16158            (
16159                WitTarget::Store { slot: "kv/x" },
16160                [false, false, true, false],
16161            ),
16162            (WitTarget::Capability, [false, false, false, true]),
16163        ];
16164        for (variant, expected) in rows {
16165            let observed = [
16166                variant.is_http(),
16167                variant.is_pubsub(),
16168                variant.is_store(),
16169                variant.is_capability(),
16170            ];
16171            assert_eq!(
16172                observed, expected,
16173                "WitTarget::{variant:?} is_* predicates must partition \
16174                 the arm set (http, pubsub, store, capability); got {observed:?}"
16175            );
16176        }
16177    }
16178
16179    #[test]
16180    fn wit_target_is_variant_predicates_are_const_fn() {
16181        // The [`gen_platform::IsVariant`] derive emits `const fn`
16182        // predicates on the peer [`crate::CaixaKind`] +
16183        // [`crate::upgrade::UpgradeInstruction`] +
16184        // [`crate::supervisor::RestartStrategy`] +
16185        // [`crate::supervisor::RestartPolicy`] +
16186        // [`PlacementStrategy`] closed-set typed enums — pin the
16187        // same posture on [`WitTarget`] so a future accidental
16188        // downgrade to non-`const` (an added runtime helper reachable
16189        // only from a non-`const` context, a manual hand-rolled
16190        // `impl` that shadows the derive-generated method) trips at
16191        // caixa-core build time rather than surfacing as a downstream
16192        // `const`-context regression far from the derive declaration.
16193        //
16194        // Unlike the peer unit-variant enums (`CaixaKind` /
16195        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
16196        // whose `const` constructors need no arguments, the three
16197        // payload-carrying [`WitTarget`] arms are const-constructed
16198        // through `&'static str` payloads — the same `'static`
16199        // lifetime the closed-set typed enum's four-arm partition
16200        // pin above already threads through.
16201        //
16202        // The pin lives inside a `const { assert!(..) }` block so the
16203        // compiler enforces both halves (arm predicate is `const`-
16204        // callable AND returns `true` for the matching arm) at
16205        // caixa-core compile time — peer to the sibling
16206        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
16207        // typed enum arm-predicate const-callability axis.
16208        const {
16209            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
16210            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
16211            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
16212            assert!(WitTarget::Capability.is_capability());
16213        }
16214    }
16215
16216    #[test]
16217    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
16218        // Consumer-side pin on the sole production converge site:
16219        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
16220        // edges from the synchronous-subgraph DFS via the lifted
16221        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
16222        // predicate (rebound from the prior raw
16223        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
16224        // variant). Byte-equivalent today (`is_pubsub` is the
16225        // derive-generated `matches!(self, Self::PubSub { .. })` by
16226        // construction, the `#[is_variant(name = "pubsub")]` override
16227        // aliasing the auto-derived `is_pub_sub` back to the sibling
16228        // [`WitContract::is_pubsub`] name); pin the behavior so a
16229        // future accidental drift (a rebind onto a peer arm
16230        // predicate, a manual hand-rolled `impl` that shadows the
16231        // derive-generated method with different semantics, a peer
16232        // arm rename that shifts which variant carries sync-versus-
16233        // async semantics) trips at caixa-core test time rather than
16234        // at some downstream operator's runtime dispatch far from the
16235        // rebind commit.
16236        //
16237        // The fixture constructs a two-Servico Aplicacao with one
16238        // pub-sub edge that would close a sync-cycle if the DFS did
16239        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
16240        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
16241        // edge, which is not a cycle. A regression in the converge
16242        // (a rebind that reads the pub-sub arm as sync) would report
16243        // `AplicacaoError::ContratoCycle`.
16244        let s = AplicacaoSpec {
16245            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
16246            contratos: vec![
16247                // Pub-sub edge: DFS must skip via is_pubsub().
16248                WitContract {
16249                    de: "a".into(),
16250                    para: "b".into(),
16251                    wit: "nats:pub-sub".into(),
16252                    endpoint: None,
16253                    subject: Some("events.x".into()),
16254                    slot: None,
16255                },
16256                // HTTP edge: DFS must include.
16257                WitContract {
16258                    de: "b".into(),
16259                    para: "a".into(),
16260                    wit: "wasi:http/proxy".into(),
16261                    endpoint: Some("/x".into()),
16262                    subject: None,
16263                    slot: None,
16264                },
16265            ],
16266            politicas: MeshPolicy::default(),
16267            placement: Placement {
16268                estrategia: PlacementStrategy::Replicated,
16269                clusters: vec!["rio".into()],
16270                affinity: None,
16271                shard_key: None,
16272            },
16273            entrada: None,
16274        };
16275        s.validate()
16276            .expect("pub-sub edge must be excluded from sync-cycle DFS");
16277    }
16278
16279    #[test]
16280    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
16281        // Consumer-side pin: the same three peer consts thread through
16282        // both the [`WitTarget::label`] template (leading-`:` keyword
16283        // prefix in the duplicate-`:contratos` diagnostic) and the
16284        // [`WitContract::target`] gate's [`AplicacaoError::
16285        // ContratoMissingTarget`] `expected:` scalar (the field the
16286        // author needs to add). Pin both routes at once so a future
16287        // refactor can't accidentally split them onto separate string
16288        // literals — the "one place, everywhere reaches for it"
16289        // invariant the peer const set carries.
16290        let http_label = WitTarget::Http { endpoint: "/x" }.label();
16291        assert!(
16292            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
16293            "label must lead with :{} keyword (got {http_label:?})",
16294            WitTarget::HTTP_FIELD_NAME,
16295        );
16296
16297        let mut s = three_member_spec();
16298        s.contratos.push(WitContract {
16299            de: "cart".into(),
16300            para: "catalog".into(),
16301            wit: "kafka:topic".into(),
16302            endpoint: None,
16303            subject: None,
16304            slot: None,
16305        });
16306        match s.validate().unwrap_err() {
16307            AplicacaoError::ContratoMissingTarget { expected, .. } => {
16308                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
16309            }
16310            other => panic!("expected ContratoMissingTarget, got {other:?}"),
16311        }
16312    }
16313
16314    #[test]
16315    fn duplicate_pubsub_diagnostic_names_offending_subject() {
16316        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
16317        // on the pub-sub target axis: the duplicate-edge diagnostic
16318        // must name the `:subject` payload verbatim (not just the
16319        // `(de, para, wit)` triple). Prior to lifting the label onto
16320        // [`WitTarget::label`] the diagnostic derived the label from
16321        // raw [`WitContract`] `Option<String>` probes — a future
16322        // `WitTarget` variant addition (M4 per-edge WIT registry)
16323        // would silently fall through to the `Capability` "no
16324        // payload" default without a compiler warning. Pinning the
16325        // pub-sub arm's format closes the second of three
16326        // payload-carrying `WitTarget` arms this diagnostic threads
16327        // through.
16328        let mut s = three_member_spec();
16329        let pubsub = WitContract {
16330            de: "payment".into(),
16331            para: "cart".into(),
16332            wit: "nats:pub-sub".into(),
16333            endpoint: None,
16334            subject: Some("events.checkout.paid".into()),
16335            slot: None,
16336        };
16337        s.contratos.push(pubsub.clone());
16338        s.contratos.push(pubsub);
16339        let err = s.validate().unwrap_err();
16340        let msg = format!("{err}");
16341        assert!(
16342            msg.contains(":subject \"events.checkout.paid\""),
16343            "duplicate-pubsub diagnostic must name the offending \
16344             :subject payload (got: {msg:?})"
16345        );
16346    }
16347
16348    #[test]
16349    fn duplicate_store_diagnostic_names_offending_slot() {
16350        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
16351        // key-value target axis: the diagnostic must name the `:slot`
16352        // payload verbatim. Third of three payload-carrying
16353        // `WitTarget` arms this diagnostic threads through, closing
16354        // the per-arm label pin trilogy (`Http` — 6841,
16355        // `PubSub` + `Store` — this test + peer above).
16356        let mut s = three_member_spec();
16357        let store = WitContract {
16358            de: "cart".into(),
16359            para: "payment".into(),
16360            wit: "wasi:keyvalue/store".into(),
16361            endpoint: None,
16362            subject: None,
16363            slot: Some("checkout/$orderId".into()),
16364        };
16365        s.contratos
16366            .retain(|c| !(c.de == "cart" && c.para == "payment"));
16367        s.contratos.push(store.clone());
16368        s.contratos.push(store);
16369        let err = s.validate().unwrap_err();
16370        let msg = format!("{err}");
16371        assert!(
16372            msg.contains(":slot \"checkout/$orderId\""),
16373            "duplicate-store diagnostic must name the offending :slot \
16374             payload (got: {msg:?})"
16375        );
16376    }
16377
16378    #[test]
16379    fn rejects_entrada_path_without_leading_slash() {
16380        let mut s = three_member_spec();
16381        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
16382        let err = s.validate().unwrap_err();
16383        assert!(
16384            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
16385            "got {err:?}"
16386        );
16387    }
16388
16389    #[test]
16390    fn rejects_empty_entrada_path() {
16391        let mut s = three_member_spec();
16392        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
16393        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
16394    }
16395
16396    #[test]
16397    fn rejects_duplicate_entrada_paths() {
16398        let mut s = three_member_spec();
16399        s.entrada.as_mut().unwrap().paths = vec![
16400            "/api/cart".into(),
16401            "/api/products".into(),
16402            "/api/cart".into(),
16403        ];
16404        let err = s.validate().unwrap_err();
16405        assert!(
16406            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
16407            "got {err:?}"
16408        );
16409    }
16410
16411    #[test]
16412    fn rejects_zero_entrada_port() {
16413        let mut s = three_member_spec();
16414        s.entrada.as_mut().unwrap().port = 0;
16415        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
16416    }
16417
16418    // ── :entrada :paths value-shape gate ─────────────────────────────
16419    //
16420    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
16421    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
16422    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
16423    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
16424    // time now becomes a caixa-build-time `EntradaPathInvalid` with
16425    // the offending `:paths` entry named verbatim.
16426
16427    #[test]
16428    fn rejects_entrada_path_with_query() {
16429        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
16430        // silently passed validate and the Gateway API webhook
16431        // rejected it at apply time with no source citation.
16432        let mut s = three_member_spec();
16433        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
16434        let err = s.validate().unwrap_err();
16435        assert!(
16436            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16437                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
16438            "got {err:?}"
16439        );
16440    }
16441
16442    #[test]
16443    fn rejects_entrada_path_with_fragment() {
16444        let mut s = three_member_spec();
16445        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
16446        let err = s.validate().unwrap_err();
16447        assert!(
16448            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16449                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
16450            "got {err:?}"
16451        );
16452    }
16453
16454    #[test]
16455    fn rejects_entrada_path_with_space() {
16456        let mut s = three_member_spec();
16457        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
16458        let err = s.validate().unwrap_err();
16459        assert!(
16460            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16461                if path == "/api/my cart" && reason.contains("whitespace")),
16462            "got {err:?}"
16463        );
16464    }
16465
16466    #[test]
16467    fn rejects_entrada_path_with_tab() {
16468        let mut s = three_member_spec();
16469        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
16470        let err = s.validate().unwrap_err();
16471        assert!(
16472            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16473                if path == "/api/\tcart" && reason.contains("whitespace")),
16474            "got {err:?}"
16475        );
16476    }
16477
16478    #[test]
16479    fn rejects_entrada_path_with_control_char() {
16480        // 0x01 (SOH) — a non-whitespace control char surfaces the
16481        // distinct "control character" reason arm, separate from
16482        // the whitespace arm. Pinned so a future refactor that
16483        // collapses the two arms can't accidentally drop the more
16484        // self-locating diagnostic.
16485        let mut s = three_member_spec();
16486        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
16487        let err = s.validate().unwrap_err();
16488        assert!(
16489            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16490                if path == "/api/\x01cart" && reason.contains("control character")),
16491            "got {err:?}"
16492        );
16493    }
16494
16495    #[test]
16496    fn rejects_entrada_path_with_non_ascii() {
16497        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
16498        // unreserved-set rule rejects. The Gateway API webhook
16499        // rejects literal non-ASCII bytes; percent-encoding is the
16500        // only way to author non-ASCII in a path.
16501        let mut s = three_member_spec();
16502        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
16503        let err = s.validate().unwrap_err();
16504        assert!(
16505            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16506                if path == "/api/café" && reason.contains("non-ASCII")),
16507            "got {err:?}"
16508        );
16509    }
16510
16511    #[test]
16512    fn rejects_entrada_path_with_consecutive_slashes() {
16513        let mut s = three_member_spec();
16514        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
16515        let err = s.validate().unwrap_err();
16516        assert!(
16517            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16518                if path == "/api//cart" && reason.contains("consecutive `/`")),
16519            "got {err:?}"
16520        );
16521    }
16522
16523    #[test]
16524    fn rejects_entrada_path_with_dot_segment() {
16525        let mut s = three_member_spec();
16526        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
16527        let err = s.validate().unwrap_err();
16528        assert!(
16529            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16530                if path == "/api/./cart" && reason.contains("`.` segment")),
16531            "got {err:?}"
16532        );
16533    }
16534
16535    #[test]
16536    fn rejects_entrada_path_with_trailing_dot_segment() {
16537        // The bare `/.` and the trailing `/foo/.` are both rejected
16538        // by the Gateway API webhook; pinned separately so a future
16539        // narrowing that catches only the inner form surfaces here.
16540        let mut s = three_member_spec();
16541        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
16542        let err = s.validate().unwrap_err();
16543        assert!(
16544            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16545                if path == "/api/." && reason.contains("`.` segment")),
16546            "got {err:?}"
16547        );
16548    }
16549
16550    #[test]
16551    fn rejects_entrada_path_with_parent_segment() {
16552        let mut s = three_member_spec();
16553        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
16554        let err = s.validate().unwrap_err();
16555        assert!(
16556            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16557                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
16558            "got {err:?}"
16559        );
16560    }
16561
16562    #[test]
16563    fn rejects_entrada_path_with_trailing_parent_segment() {
16564        // Trailing `/..` — symmetric arm of the parent-segment rule,
16565        // pinned separately so a future relaxation that only checks
16566        // the inner form (`/../`) surfaces here.
16567        let mut s = three_member_spec();
16568        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
16569        let err = s.validate().unwrap_err();
16570        assert!(
16571            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16572                if path == "/api/.." && reason.contains("`..` parent-segment")),
16573            "got {err:?}"
16574        );
16575    }
16576
16577    #[test]
16578    fn rejects_entrada_path_too_long() {
16579        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
16580        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
16581        // ASCII-alphanumeric body so only the length rule fires.
16582        let mut s = three_member_spec();
16583        let big = format!("/api/{}", "a".repeat(1020));
16584        assert_eq!(big.len(), 1025);
16585        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
16586        let err = s.validate().unwrap_err();
16587        assert!(
16588            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16589                if path == &big && reason.contains("max length of 1024")),
16590            "got {err:?}"
16591        );
16592    }
16593
16594    #[test]
16595    fn entrada_path_max_length_validates() {
16596        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
16597        // maxLength cap. Boundary pin: drift in the cap surfaces here
16598        // and at `rejects_entrada_path_too_long` simultaneously.
16599        let mut s = three_member_spec();
16600        let big = format!("/api/{}", "a".repeat(1019));
16601        assert_eq!(big.len(), 1024);
16602        s.entrada.as_mut().unwrap().paths = vec![big];
16603        s.validate().unwrap();
16604    }
16605
16606    #[test]
16607    fn entrada_accepts_canonical_paths() {
16608        // Positive-control sweep — every form the Gateway API
16609        // apiserver accepts must round-trip through validate. Covers
16610        // the root catch-all, plain paths, dot-prefixed segments
16611        // (hidden-file-style, distinct from `.` and `..` segments
16612        // which are rejected), digit-bearing segments, the canonical
16613        // route-template `:param` form (`:` is RFC 3986 reserved-set
16614        // valid in paths), trailing-slash form, percent-encoded
16615        // segments, and an interior `..` *substring* (`/foo..bar` is
16616        // not the `..` segment and is allowed).
16617        for path in [
16618            "/",
16619            "/api/cart",
16620            "/healthz",
16621            "/api/.config",
16622            "/v1/products",
16623            "/products/:id",
16624            "/api/cart/",
16625            "/api/caf%C3%A9",
16626            "/foo..bar",
16627            "/...",
16628        ] {
16629            let mut s = three_member_spec();
16630            s.entrada.as_mut().unwrap().paths = vec![path.into()];
16631            s.validate()
16632                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
16633        }
16634    }
16635
16636    #[test]
16637    fn entrada_path_empty_takes_precedence_over_invalid() {
16638        // Ordering pin: `EntradaPathEmpty` is the more self-locating
16639        // diagnostic on `""` and must lead — `validate_entrada_path`
16640        // is only reached after the empty-check fires at the call
16641        // site. (The predicate itself defends against direct
16642        // invocation by returning the same error on `""`.)
16643        let mut s = three_member_spec();
16644        s.entrada.as_mut().unwrap().paths = vec![String::new()];
16645        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
16646    }
16647
16648    #[test]
16649    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
16650        // Ordering pin: a path without a leading `/` surfaces the
16651        // narrower `EntradaPathNotAbsolute` diagnostic first; the
16652        // value-shape gate is only consulted on paths that already
16653        // satisfy the absolute-prefix invariant.
16654        let mut s = three_member_spec();
16655        // `bad path` would fire the whitespace rule under the
16656        // value-shape gate, but missing-leading-`/` is the more
16657        // self-locating diagnostic.
16658        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
16659        let err = s.validate().unwrap_err();
16660        assert!(
16661            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
16662            "got {err:?}"
16663        );
16664    }
16665
16666    #[test]
16667    fn entrada_path_invalid_fires_before_duplicate_check() {
16668        // Ordering pin: a malformed path on the *first* entry of a
16669        // would-be duplicate pair fires the value-shape gate before
16670        // the duplicate gate, mirroring the
16671        // `placement_cluster_invalid_fires_before_duplicate_check`
16672        // (6cbb900) pattern on the peer axis.
16673        let mut s = three_member_spec();
16674        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
16675        let err = s.validate().unwrap_err();
16676        assert!(
16677            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
16678            "got {err:?}"
16679        );
16680    }
16681
16682    #[test]
16683    fn entrada_path_diagnostic_carries_offending_path() {
16684        // Diagnostic-shape pin — the offending path + a non-empty
16685        // reason flow through verbatim so the author can grep their
16686        // caixa.lisp for `:paths` and fix it in one edit. Same shape
16687        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
16688        let mut s = three_member_spec();
16689        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
16690        let err = s.validate().unwrap_err();
16691        match err {
16692            AplicacaoError::EntradaPathInvalid { path, reason } => {
16693                assert_eq!(path, "/api?q=1");
16694                assert!(!reason.is_empty(), "reason field must be non-empty");
16695            }
16696            other => panic!("expected EntradaPathInvalid, got {other:?}"),
16697        }
16698    }
16699
16700    #[test]
16701    fn rejects_entrada_path_with_curly_brace_template_form() {
16702        // Per-axis pin on the shared `is_gateway_api_http_path`
16703        // reserved-byte arm: the canonical "I wrote an OpenAPI
16704        // path-template `{id}` instead of the Gateway API `:id` form"
16705        // footgun the K8s apiserver would otherwise catch at admission
16706        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
16707        // landing site, far from the caixa.lisp. Surfaces as
16708        // `EntradaPathInvalid` carrying the offending path verbatim
16709        // plus the canonical `%7B`/`%7D` percent-encoding remediation
16710        // — the substrate-side `gateway_api_http_path_rejects_every_
16711        // reserved_printable_ascii_byte` predicate-level sweep pins the
16712        // full eleven-byte set; this per-axis pin confirms the
16713        // diagnostic flows through to the `EntradaPathInvalid` variant.
16714        let mut s = three_member_spec();
16715        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
16716        let err = s.validate().unwrap_err();
16717        assert!(
16718            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16719                if path == "/api/cart/{id}"
16720                    && reason.contains("reserved character")
16721                    && reason.contains("'{'")
16722                    && reason.contains("%7B")),
16723            "got {err:?}"
16724        );
16725    }
16726
16727    #[test]
16728    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
16729        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
16730        // template_form` on the sibling `:contratos :endpoint` axis.
16731        // Same shared `is_gateway_api_http_path` reserved-byte arm
16732        // fires through `ContratoEndpointInvalid`, with the offending
16733        // endpoint + `:de` + `:para` + reason flowing through verbatim.
16734        // Pins that the lifted predicate's tightening lands on both
16735        // caller axes simultaneously — one source of truth for the
16736        // Gateway API HTTPPathMatch.value accepted set.
16737        let err = contrato_endpoint_err("/api/cart/{id}");
16738        assert!(
16739            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
16740                if endpoint == "/api/cart/{id}"
16741                    && reason.contains("reserved character")
16742                    && reason.contains("'{'")
16743                    && reason.contains("%7B")),
16744            "got {err:?}"
16745        );
16746    }
16747
16748    // ── :entrada :host value-shape gate ──────────────────────────────
16749    //
16750    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
16751    // the sibling `:host` axis. Every authoring footgun the K8s
16752    // Gateway API v1 apiserver would catch at admission time becomes
16753    // a caixa-build-time `EntradaHostInvalid` with the offending
16754    // `:host` named verbatim. Same diagnostic shape as
16755    // `MembroVersaoInvalid` (9888b13).
16756
16757    #[test]
16758    fn rejects_entrada_host_with_scheme() {
16759        // Fail-before-pass-after pin — pre-gate codebases silently
16760        // accepted `https://…` and the apiserver rejected it at apply
16761        // time with no source citation.
16762        let mut s = three_member_spec();
16763        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
16764        let err = s.validate().unwrap_err();
16765        assert!(
16766            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16767                if host == "https://checkout.quero.cloud"),
16768            "got {err:?}"
16769        );
16770    }
16771
16772    #[test]
16773    fn rejects_entrada_host_with_port() {
16774        // The `:8080` port suffix is the canonical "I forgot the port
16775        // belongs in `:entrada :port`" footgun. The top-level `:` arm
16776        // (introduced after the per-label loop-only impl silently
16777        // surfaced a deep "label \"cloud:8080\" contains invalid
16778        // character ':'" leak) names the canonical fix verbatim — the
16779        // `:entrada :port` slot.
16780        let mut s = three_member_spec();
16781        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
16782        let err = s.validate().unwrap_err();
16783        assert!(
16784            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16785                if host == "checkout.quero.cloud:8080"
16786                && reason.contains(":entrada :port")),
16787            "got {err:?}"
16788        );
16789    }
16790
16791    #[test]
16792    fn rejects_entrada_host_with_trailing_colon() {
16793        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
16794        // edit) — the per-label loop would land it as a deep
16795        // "label \"com:\" must start and end with an alphanumeric"
16796        // / "contains invalid character ':'" leak. The top-level
16797        // `:` arm pre-empts with the canonical `:port` slot
16798        // diagnostic.
16799        let mut s = three_member_spec();
16800        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
16801        let err = s.validate().unwrap_err();
16802        assert!(
16803            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16804                if host == "checkout.quero.cloud:"
16805                && reason.contains(":entrada :port")),
16806            "got {err:?}"
16807        );
16808    }
16809
16810    #[test]
16811    fn rejects_entrada_host_unbracketed_ipv6_literal() {
16812        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
16813        // literals across the board (peer with `rejects_entrada_host_
16814        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
16815        // Before this top-level `:` arm landed the per-label loop
16816        // surfaced a single-label byte-class diagnostic that named the
16817        // `:` byte but not the IP-literal prohibition. The top-level
16818        // `:` arm names both the `:port` slot and the IP-literal
16819        // prohibition verbatim, so an author whose `:host "2001:..."`
16820        // value lands here gets a self-locating fix either way.
16821        let mut s = three_member_spec();
16822        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
16823        let err = s.validate().unwrap_err();
16824        assert!(
16825            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16826                if host == "2001:db8::1"
16827                && reason.contains("IPv6")),
16828            "got {err:?}"
16829        );
16830    }
16831
16832    #[test]
16833    fn rejects_entrada_host_wildcard_with_port() {
16834        // Wildcard host with port suffix — the `*.` strip and the
16835        // per-label loop on `["foo", "quero", "cloud:8080"]` would
16836        // surface the deep byte-class leak. The top-level `:` arm sits
16837        // upstream of the `*.` strip, so it names the canonical `:port`
16838        // fix verbatim regardless of whether the host is wildcard-led.
16839        let mut s = three_member_spec();
16840        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
16841        let err = s.validate().unwrap_err();
16842        assert!(
16843            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
16844                if host == "*.quero.cloud:8080"
16845                && reason.contains(":entrada :port")),
16846            "got {err:?}"
16847        );
16848    }
16849
16850    #[test]
16851    fn rejects_entrada_host_with_path() {
16852        let mut s = three_member_spec();
16853        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
16854        let err = s.validate().unwrap_err();
16855        assert!(
16856            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16857                if host == "checkout.quero.cloud/api"),
16858            "got {err:?}"
16859        );
16860    }
16861
16862    #[test]
16863    fn rejects_entrada_host_with_uppercase() {
16864        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
16865        // rejected, not silently lower-cased.
16866        let mut s = three_member_spec();
16867        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
16868        let err = s.validate().unwrap_err();
16869        assert!(
16870            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16871                if reason.contains("uppercase")),
16872            "got {err:?}"
16873        );
16874    }
16875
16876    #[test]
16877    fn rejects_entrada_host_with_underscore() {
16878        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
16879        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
16880        let mut s = three_member_spec();
16881        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
16882        let err = s.validate().unwrap_err();
16883        assert!(
16884            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16885                if reason.contains('_')),
16886            "got {err:?}"
16887        );
16888    }
16889
16890    #[test]
16891    fn rejects_entrada_host_ipv4_literal() {
16892        // Gateway API v1 explicitly forbids IP literals as Hostnames.
16893        let mut s = three_member_spec();
16894        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
16895        let err = s.validate().unwrap_err();
16896        assert!(
16897            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16898                if reason.contains("IPv4")),
16899            "got {err:?}"
16900        );
16901    }
16902
16903    #[test]
16904    fn rejects_entrada_host_with_trailing_dot() {
16905        // The Gateway API regex anchors at end-of-string with no
16906        // trailing `.` allowance — the FQDN root-dot form is rejected.
16907        let mut s = three_member_spec();
16908        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
16909        let err = s.validate().unwrap_err();
16910        assert!(
16911            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
16912                if host == "checkout.quero.cloud."),
16913            "got {err:?}"
16914        );
16915    }
16916
16917    #[test]
16918    fn rejects_entrada_host_with_leading_dot() {
16919        let mut s = three_member_spec();
16920        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
16921        let err = s.validate().unwrap_err();
16922        assert!(
16923            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16924                if reason.contains("empty label")),
16925            "got {err:?}"
16926        );
16927    }
16928
16929    #[test]
16930    fn rejects_entrada_host_with_consecutive_dots() {
16931        let mut s = three_member_spec();
16932        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
16933        let err = s.validate().unwrap_err();
16934        assert!(
16935            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16936                if reason.contains("empty label")),
16937            "got {err:?}"
16938        );
16939    }
16940
16941    #[test]
16942    fn rejects_entrada_host_with_leading_hyphen_label() {
16943        let mut s = three_member_spec();
16944        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
16945        let err = s.validate().unwrap_err();
16946        assert!(
16947            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16948                if reason.contains("alphanumeric")),
16949            "got {err:?}"
16950        );
16951    }
16952
16953    #[test]
16954    fn rejects_entrada_host_with_trailing_hyphen_label() {
16955        let mut s = three_member_spec();
16956        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
16957        let err = s.validate().unwrap_err();
16958        assert!(
16959            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16960                if reason.contains("alphanumeric")),
16961            "got {err:?}"
16962        );
16963    }
16964
16965    #[test]
16966    fn rejects_entrada_host_with_inner_wildcard() {
16967        // Gateway API allows `*` only as the first label (`*.foo`);
16968        // any inner or trailing `*` is rejected.
16969        let mut s = three_member_spec();
16970        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
16971        let err = s.validate().unwrap_err();
16972        assert!(
16973            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16974                if reason.contains("wildcard")),
16975            "got {err:?}"
16976        );
16977    }
16978
16979    #[test]
16980    fn rejects_entrada_host_bare_wildcard() {
16981        // `*.` with no domain is meaningless; Gateway API rejects it.
16982        let mut s = three_member_spec();
16983        s.entrada.as_mut().unwrap().host = "*.".into();
16984        let err = s.validate().unwrap_err();
16985        assert!(
16986            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16987                if reason.contains("wildcard")),
16988            "got {err:?}"
16989        );
16990    }
16991
16992    #[test]
16993    fn rejects_entrada_host_with_whitespace() {
16994        let mut s = three_member_spec();
16995        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
16996        let err = s.validate().unwrap_err();
16997        assert!(
16998            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
16999                if reason.contains("whitespace")),
17000            "got {err:?}"
17001        );
17002    }
17003
17004    #[test]
17005    fn rejects_entrada_host_space_names_offending_byte() {
17006        // Embedded space in the `:entrada :host` axis surfaces the
17007        // byte-naming diagnostic through the lifted
17008        // `find_ascii_whitespace_byte` predicate. Peer with the
17009        // sibling `parse_rejects_leading_whitespace` pins on
17010        // `supervisor::duration_codec` (a7ae622) — same "the
17011        // diagnostic carries the offending byte's `0x{b:02x}` shape"
17012        // discipline extended from the shared duration codec to the
17013        // Gateway API v1 Hostname axis.
17014        let mut s = three_member_spec();
17015        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
17016        let err = s.validate().unwrap_err();
17017        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17018            panic!("expected EntradaHostInvalid, got {err:?}");
17019        };
17020        assert!(
17021            reason.contains("ASCII whitespace byte"),
17022            "expected byte-naming diagnostic, got {reason:?}"
17023        );
17024        assert!(
17025            reason.contains("0x20"),
17026            "expected offending space byte 0x20, got {reason:?}"
17027        );
17028    }
17029
17030    #[test]
17031    fn rejects_entrada_host_tab_names_offending_byte() {
17032        // Embedded tab byte in the `:entrada :host` axis — the
17033        // canonical paste-from-YAML-block-scalar / paste-from-
17034        // indented-doc footgun. Pins that the lifted predicate covers
17035        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
17036        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
17037        // not just the leading-space case the pre-lift `.bytes().any`
17038        // arm's opaque "must not contain whitespace" reason already
17039        // covered. Peer with `parse_rejects_tab_byte` on
17040        // `supervisor::duration_codec` (a7ae622).
17041        let mut s = three_member_spec();
17042        s.entrada.as_mut().unwrap().host = "checkout.\tquero.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("ASCII whitespace byte"),
17049            "expected byte-naming diagnostic, got {reason:?}"
17050        );
17051        assert!(
17052            reason.contains("0x09"),
17053            "expected offending tab byte 0x09, got {reason:?}"
17054        );
17055    }
17056
17057    #[test]
17058    fn rejects_entrada_host_lf_names_offending_byte() {
17059        // Embedded LF byte in the `:entrada :host` axis — the
17060        // canonical paste-from-shell-heredoc / paste-from-multiline-
17061        // doc footgun the caixa-mesh YAML emitter would silently
17062        // reinterpret at the Gateway API v1 HTTPRoute admission
17063        // layer (an embedded LF byte in a YAML plain scalar either
17064        // truncates the value at the emitter or crashes the parser
17065        // on the k8s-apiserver side). Pins the third representative
17066        // of the full ASCII-whitespace set through the shared
17067        // predicate.
17068        let mut s = three_member_spec();
17069        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
17070        let err = s.validate().unwrap_err();
17071        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17072            panic!("expected EntradaHostInvalid, got {err:?}");
17073        };
17074        assert!(
17075            reason.contains("ASCII whitespace byte"),
17076            "expected byte-naming diagnostic, got {reason:?}"
17077        );
17078        assert!(
17079            reason.contains("0x0a"),
17080            "expected offending LF byte 0x0a, got {reason:?}"
17081        );
17082    }
17083
17084    #[test]
17085    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
17086        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
17087        // axis — the canonical paste-from-typography /
17088        // paste-from-word-processor footgun. Before the non-ASCII
17089        // Unicode `White_Space` scan lifted through the shared
17090        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
17091        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
17092        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
17093        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
17094        // with the far-from-source `label "…" must start and end
17095        // with an alphanumeric` diagnostic — burying the
17096        // paste-from-typography origin under a label-shape leak.
17097        // Peer with the sibling non-ASCII-whitespace pins at
17098        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
17099        // — 1b75b38), `limits::parse_duration`,
17100        // `limits::parse_millicores`, and the shared duration codec
17101        // — same "the diagnostic carries the offending Unicode
17102        // codepoint's `U+XXXX` shape" discipline extended from every
17103        // typed-magnitude codec to the Gateway API v1 Hostname axis.
17104        let mut s = three_member_spec();
17105        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
17106        let err = s.validate().unwrap_err();
17107        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17108            panic!("expected EntradaHostInvalid, got {err:?}");
17109        };
17110        assert!(
17111            reason.contains("non-ASCII Unicode whitespace character"),
17112            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17113        );
17114        assert!(
17115            reason.contains("U+00A0"),
17116            "expected offending NBSP codepoint U+00A0, got {reason:?}"
17117        );
17118    }
17119
17120    #[test]
17121    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
17122        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
17123        // `:entrada :host` axis — the canonical paste-from-web-doc /
17124        // paste-from-published-HTML footgun. `char::is_whitespace`
17125        // returns true for `U+2028` per the Unicode `White_Space`
17126        // property, so `str::trim` at any downstream site would
17127        // silently strip it — same drift class as NBSP but on a
17128        // different codepoint region. Pins the second representative
17129        // (non-Latin-1 `char::is_whitespace` member) through the
17130        // shared predicate. Peer with
17131        // `parse_byte_size_rejects_internal_line_separator` on
17132        // `limits::parse_byte_size` (1b75b38).
17133        let mut s = three_member_spec();
17134        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
17135        let err = s.validate().unwrap_err();
17136        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17137            panic!("expected EntradaHostInvalid, got {err:?}");
17138        };
17139        assert!(
17140            reason.contains("non-ASCII Unicode whitespace character"),
17141            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17142        );
17143        assert!(
17144            reason.contains("U+2028"),
17145            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
17146        );
17147    }
17148
17149    #[test]
17150    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
17151        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
17152        // labels in the `:entrada :host` axis — the canonical
17153        // paste-from-CJK-typography footgun (CJK IMEs default to
17154        // full-width whitespace when the space bar is pressed in
17155        // Japanese / Chinese input modes). Pins the third
17156        // representative of the non-ASCII Unicode `White_Space` set
17157        // through the shared predicate: the CJK block, distinct from
17158        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
17159        // SEPARATOR `U+2028` — covering the same axis breadth the
17160        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
17161        // (1b75b38) pins on `limits::parse_byte_size`.
17162        let mut s = three_member_spec();
17163        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
17164        let err = s.validate().unwrap_err();
17165        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17166            panic!("expected EntradaHostInvalid, got {err:?}");
17167        };
17168        assert!(
17169            reason.contains("non-ASCII Unicode whitespace character"),
17170            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17171        );
17172        assert!(
17173            reason.contains("U+3000"),
17174            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
17175        );
17176    }
17177
17178    #[test]
17179    fn rejects_entrada_host_too_long() {
17180        // Total length cap = 253; build a 254-byte host out of two
17181        // 63-byte labels + one 62-byte label + dots.
17182        let mut s = three_member_spec();
17183        let big = format!(
17184            "{}.{}.{}.{}",
17185            "a".repeat(63),
17186            "b".repeat(63),
17187            "c".repeat(63),
17188            "d".repeat(254 - 63 * 3 - 3)
17189        );
17190        assert_eq!(big.len(), 254);
17191        s.entrada.as_mut().unwrap().host = big;
17192        let err = s.validate().unwrap_err();
17193        assert!(
17194            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17195                if reason.contains("max length of 253")),
17196            "got {err:?}"
17197        );
17198    }
17199
17200    #[test]
17201    fn rejects_entrada_host_label_too_long() {
17202        let mut s = three_member_spec();
17203        // 64-byte label — one over the per-label cap.
17204        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
17205        let err = s.validate().unwrap_err();
17206        assert!(
17207            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17208                if reason.contains("label max length of 63")),
17209            "got {err:?}"
17210        );
17211    }
17212
17213    #[test]
17214    fn entrada_host_diagnostic_carries_offending_host() {
17215        // Diagnostic-shape pin — the offending host + a non-empty
17216        // reason flow through verbatim so the author can grep their
17217        // caixa.lisp for `:host "<host>"` and fix it in one edit.
17218        let mut s = three_member_spec();
17219        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
17220        let err = s.validate().unwrap_err();
17221        match err {
17222            AplicacaoError::EntradaHostInvalid { host, reason } => {
17223                assert_eq!(host, "checkout.quero.cloud:8080");
17224                assert!(!reason.is_empty(), "reason field must be non-empty");
17225            }
17226            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17227        }
17228    }
17229
17230    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
17231    // substrate primitive that folds the fourteen
17232    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
17233    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
17234    // one dispatch — peer with the sixteen equivalence pins the
17235    // [`crate::LayoutError`] `_violation` constructor family carries in
17236    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
17237    // fixture host + reason are fixed `&'static str`s so both fields of
17238    // both constructed variants pin verbatim: the `host` axis is pinned
17239    // through the shared `host.to_string()` wrap (the ctor's uniform
17240    // one-slot construction) and the `reason` axis is pinned through
17241    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
17242    // routing). Any future regression on the lift (an extra field
17243    // introduced without updating the ctor, a diverging string
17244    // conversion at either arm) surfaces at this pin's diagnostic
17245    // rather than at a per-wire-up struct-literal reintroduction.
17246    #[test]
17247    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
17248        let host = "checkout.quero.cloud:8080";
17249        let reason = "sample reason text";
17250        assert_eq!(
17251            AplicacaoError::entrada_host_invalid(host, reason),
17252            AplicacaoError::EntradaHostInvalid {
17253                host: host.to_string(),
17254                reason: reason.to_string(),
17255            },
17256            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
17257        );
17258    }
17259
17260    // Routing pin — the ctor's `host: &str` argument threads through
17261    // `.to_string()` verbatim on the `host` field, so the constructed
17262    // variant carries the offending host bytes without any wrapper-
17263    // side transformation (no `.to_ascii_lowercase()` normalization,
17264    // no `.trim()` strip, no truncation) — the same "diagnostic carries
17265    // the offending value verbatim so the author can grep their
17266    // caixa.lisp" discipline every peer typed-slot ctor at this
17267    // altitude carries.
17268    #[test]
17269    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
17270        // Uppercase + trailing whitespace + port suffix — three
17271        // wrapper-side transformations the ctor must *not* apply.
17272        let host = " Checkout.quero.CLOUD:8080 ";
17273        let err = AplicacaoError::entrada_host_invalid(host, "sample");
17274        match err {
17275            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
17276                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
17277            }
17278            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17279        }
17280    }
17281
17282    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
17283    // `&str` literals and `format!(…)` outputs identically and both
17284    // route through `Into::into` verbatim onto the `reason` field.
17285    // Pins both codepaths against the same host to prove the two
17286    // shapes the fourteen wire-up sites use at their per-arm diagnostic
17287    // (ten `&str` literals — some with `.to_string()` at the caller,
17288    // some without — plus four `format!(…)` outputs) each produce
17289    // byte-equal `reason` fields against the same offending host.
17290    #[test]
17291    fn entrada_host_invalid_ctor_routes_reason_through_into() {
17292        let host = "checkout.quero.cloud";
17293        // `&str` literal — the ctor's `impl Into<String>` accepts it
17294        // without a caller-side `.to_string()`.
17295        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
17296        // Owned `String` from `format!` — the peer `format!(…)`-shaped
17297        // wire-up arm.
17298        let from_format =
17299            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
17300        // `String` from `.to_string()` on a literal — the peer
17301        // `"literal".to_string()`-shaped wire-up arm the pre-lift
17302        // sites carried.
17303        let from_to_string =
17304            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
17305        match (&from_literal, &from_format, &from_to_string) {
17306            (
17307                AplicacaoError::EntradaHostInvalid {
17308                    reason: r_lit,
17309                    host: h_lit,
17310                },
17311                AplicacaoError::EntradaHostInvalid {
17312                    reason: r_fmt,
17313                    host: h_fmt,
17314                },
17315                AplicacaoError::EntradaHostInvalid {
17316                    reason: r_ts,
17317                    host: h_ts,
17318                },
17319            ) => {
17320                assert_eq!(r_lit, "literal reason text");
17321                assert_eq!(r_fmt, "literal reason text");
17322                assert_eq!(r_ts, "literal reason text");
17323                assert_eq!(h_lit, host);
17324                assert_eq!(h_fmt, host);
17325                assert_eq!(h_ts, host);
17326            }
17327            _ => panic!("expected three EntradaHostInvalid variants"),
17328        }
17329        // Cross-arm equivalence — the three shapes must produce
17330        // byte-equal `AplicacaoError` values, so the fourteen wire-up
17331        // sites' mixed per-arm shapes fold onto one canonical form.
17332        assert_eq!(from_literal, from_format);
17333        assert_eq!(from_literal, from_to_string);
17334    }
17335
17336    // Equivalence pins for the six sibling
17337    // [`aplicacao_field_reason_ctors!`]-generated constructors that
17338    // fold the peer `{ <field>: String, reason: String }` variants
17339    // onto the same substrate-primitive family
17340    // `entrada_host_invalid` (17dd504) already carries pins for.
17341    // Each ctor's fixture pair (a fixed `&'static str` value and a
17342    // fixed `&'static str` reason) pins both fields verbatim so any
17343    // future regression on the macro (an extra field introduced
17344    // without updating the macro, a diverging string conversion at
17345    // either arm, a field-name typo on one variant that dropped it
17346    // off the shared shape) surfaces at the affected variant's pin
17347    // rather than at a per-wire-up struct-literal reintroduction. Peer
17348    // discipline of the sixteen `LayoutError` _violation ctor pins in
17349    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
17350    // and the paired
17351    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
17352    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
17353    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
17354    // (8580068) equivalence pins on the sibling `AplicacaoError`
17355    // ctor macros.
17356    #[test]
17357    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
17358        let caixa = "cart-svc";
17359        let reason = "sample reason text";
17360        assert_eq!(
17361            AplicacaoError::membro_caixa_invalid(caixa, reason),
17362            AplicacaoError::MembroCaixaInvalid {
17363                caixa: caixa.to_string(),
17364                reason: reason.to_string(),
17365            },
17366        );
17367    }
17368
17369    #[test]
17370    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
17371        let para = "checkout";
17372        let reason = "sample reason text";
17373        assert_eq!(
17374            AplicacaoError::entrada_para_invalid(para, reason),
17375            AplicacaoError::EntradaParaInvalid {
17376                para: para.to_string(),
17377                reason: reason.to_string(),
17378            },
17379        );
17380    }
17381
17382    #[test]
17383    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
17384        let path = "/api/cart";
17385        let reason = "sample reason text";
17386        assert_eq!(
17387            AplicacaoError::entrada_path_invalid(path, reason),
17388            AplicacaoError::EntradaPathInvalid {
17389                path: path.to_string(),
17390                reason: reason.to_string(),
17391            },
17392        );
17393    }
17394
17395    #[test]
17396    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
17397        let cluster = "rio";
17398        let reason = "sample reason text";
17399        assert_eq!(
17400            AplicacaoError::placement_cluster_invalid(cluster, reason),
17401            AplicacaoError::PlacementClusterInvalid {
17402                cluster: cluster.to_string(),
17403                reason: reason.to_string(),
17404            },
17405        );
17406    }
17407
17408    #[test]
17409    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
17410        let affinity = "data-locality";
17411        let reason = "sample reason text";
17412        assert_eq!(
17413            AplicacaoError::placement_affinity_invalid(affinity, reason),
17414            AplicacaoError::PlacementAffinityInvalid {
17415                affinity: affinity.to_string(),
17416                reason: reason.to_string(),
17417            },
17418        );
17419    }
17420
17421    #[test]
17422    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
17423        let shard_key = "tenantId";
17424        let reason = "sample reason text";
17425        assert_eq!(
17426            AplicacaoError::shard_key_invalid(shard_key, reason),
17427            AplicacaoError::ShardKeyInvalid {
17428                shard_key: shard_key.to_string(),
17429                reason: reason.to_string(),
17430            },
17431        );
17432    }
17433
17434    // Cross-family invariance pin — the six sibling ctors and
17435    // `entrada_host_invalid` all route `reason: impl Into<String>` +
17436    // `<field>: &str` verbatim onto their respective typed variants
17437    // through the shared [`aplicacao_field_reason_ctors!`] macro.
17438    // Sweeps a fixture pair (`&str` literal, `format!` output) against
17439    // every ctor to pin that no per-arm wrapper transformation drifted
17440    // in against the uniform macro-generated body.
17441    #[test]
17442    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
17443        let via_literal = "literal reason text";
17444        let via_format = format!("{} reason text", "literal");
17445        assert_eq!(
17446            AplicacaoError::membro_caixa_invalid("m", via_literal),
17447            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
17448        );
17449        assert_eq!(
17450            AplicacaoError::entrada_para_invalid("p", via_literal),
17451            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
17452        );
17453        assert_eq!(
17454            AplicacaoError::entrada_path_invalid("/a", via_literal),
17455            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
17456        );
17457        assert_eq!(
17458            AplicacaoError::placement_cluster_invalid("c", via_literal),
17459            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
17460        );
17461        assert_eq!(
17462            AplicacaoError::placement_affinity_invalid("a", via_literal),
17463            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
17464        );
17465        assert_eq!(
17466            AplicacaoError::shard_key_invalid("k", via_literal),
17467            AplicacaoError::shard_key_invalid("k", via_format.clone()),
17468        );
17469        assert_eq!(
17470            AplicacaoError::entrada_host_invalid("h", via_literal),
17471            AplicacaoError::entrada_host_invalid("h", via_format),
17472        );
17473    }
17474
17475    #[test]
17476    fn entrada_host_empty_takes_precedence_over_invalid() {
17477        // Ordering pin: `EmptyEntradaHost` is the more self-locating
17478        // diagnostic on `""` and must lead — `validate_entrada_host`
17479        // is only reached after the empty-check fires at the call
17480        // site. (The predicate itself defends against direct
17481        // invocation by returning the same error on `""`.)
17482        let mut s = three_member_spec();
17483        s.entrada.as_mut().unwrap().host = String::new();
17484        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
17485    }
17486
17487    #[test]
17488    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
17489        // Ordering pin: a missing :para member is the more
17490        // self-locating diagnostic and fires before the host gate.
17491        let mut s = three_member_spec();
17492        let e = s.entrada.as_mut().unwrap();
17493        e.para = "ghost".into();
17494        e.host = "BAD HOST".into();
17495        let err = s.validate().unwrap_err();
17496        assert!(
17497            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
17498            "got {err:?}"
17499        );
17500    }
17501
17502    #[test]
17503    fn entrada_host_invalid_fires_before_port_zero() {
17504        // Ordering pin: the host gate fires before the port gate so
17505        // a malformed host is named even when the port is also wrong.
17506        let mut s = three_member_spec();
17507        let e = s.entrada.as_mut().unwrap();
17508        e.host = "Checkout.quero.cloud".into();
17509        e.port = 0;
17510        let err = s.validate().unwrap_err();
17511        assert!(
17512            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17513                if host == "Checkout.quero.cloud"),
17514            "got {err:?}"
17515        );
17516    }
17517
17518    #[test]
17519    fn entrada_accepts_canonical_hosts() {
17520        // Positive-control sweep — every form the Gateway API
17521        // apiserver accepts must round-trip through validate. Covers
17522        // a plain DNS subdomain, a leading wildcard, a single-label
17523        // host (cluster-internal), a max-length-edge label, a
17524        // hyphen-bearing label, and a Punycode IDN label.
17525        for host in [
17526            "checkout.quero.cloud",
17527            "*.quero.cloud",
17528            "checkout",
17529            // 63-byte label — exactly the per-label cap.
17530            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
17531            "foo-bar.quero.cloud",
17532            // Punycode IDN — valid because the author pre-encoded.
17533            "xn--bcher-kva.example.com",
17534        ] {
17535            let mut s = three_member_spec();
17536            s.entrada.as_mut().unwrap().host = host.into();
17537            s.validate()
17538                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
17539        }
17540    }
17541
17542    #[test]
17543    fn entrada_host_max_length_validates() {
17544        // 253-byte host is the cap exactly — must validate. Build a
17545        // 253-byte host out of three 63-byte labels + one 61-byte
17546        // label + 3 dots = 252 bytes, then pad one byte to 253.
17547        let mut s = three_member_spec();
17548        let host = format!(
17549            "{}.{}.{}.{}",
17550            "a".repeat(63),
17551            "b".repeat(63),
17552            "c".repeat(63),
17553            "d".repeat(253 - 63 * 3 - 3)
17554        );
17555        assert_eq!(host.len(), 253);
17556        s.entrada.as_mut().unwrap().host = host;
17557        s.validate().unwrap();
17558    }
17559
17560    #[test]
17561    fn entrada_host_total_length_cap_threads_lifted_render_const() {
17562        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
17563        // total-length gate now reads the K8s Gateway API v1 Hostname
17564        // `maxLength: 253` cap from the lifted
17565        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
17566        // of truth — the same constant every future Gateway-API-Hostname
17567        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
17568        // materializer's per-host validator, the future per-`Certificate`
17569        // SAN emitter for cert-manager, the multi-`:entrada`
17570        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
17571        // from. Before the lift, the aplicacao-side reader consumed a
17572        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
17573        // 253-byte value as the peer render-side canonical bounds
17574        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
17575        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
17576        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
17577        // module boundary — a future 253-byte drift on either side would
17578        // silently split into two axes' worth of admission-schema mismatch
17579        // without a build-time signal. Pin the cap through a fresh 254-
17580        // byte host that hits the total-length arm, then read the reason
17581        // for the exact byte count the shared constant carries: any future
17582        // regression on the lift (a private alias reintroduced, a hard-
17583        // coded literal at the arm, a mismatch between the aplicacao-side
17584        // and render-side canonicals) surfaces as this pin's diagnostic
17585        // failing to match, not as a per-cluster admission rejection far
17586        // from the caixa.lisp source line.
17587        let mut s = three_member_spec();
17588        let over_cap = format!(
17589            "{}.{}.{}.{}",
17590            "a".repeat(63),
17591            "b".repeat(63),
17592            "c".repeat(63),
17593            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
17594        );
17595        assert_eq!(
17596            over_cap.len(),
17597            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
17598        );
17599        s.entrada.as_mut().unwrap().host = over_cap;
17600        let err = s.validate().unwrap_err();
17601        match err {
17602            AplicacaoError::EntradaHostInvalid { reason, .. } => {
17603                let needle = format!(
17604                    "max length of {} bytes",
17605                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
17606                );
17607                assert!(
17608                    reason.contains(&needle),
17609                    "diagnostic must name the lifted \
17610                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
17611                );
17612            }
17613            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17614        }
17615    }
17616
17617    #[test]
17618    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
17619        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
17620        // on the per-label-cap axis. Before the lift, the aplicacao-side
17621        // per-label arm consumed a private const alias
17622        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
17623        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
17624        // split from it at the module boundary — every `.`-separated
17625        // label in a Gateway API v1 Hostname is a DNS-1123 label under
17626        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
17627        // so the private alias's 63 and the canonical const's 63 were
17628        // pinning the same underlying rule twice. Pin the cap through a
17629        // 64-byte label that hits the per-label arm, then read the reason
17630        // for the exact byte count the shared constant carries: any
17631        // future drift on either side (a private alias reintroduced, a
17632        // hard-coded literal at the arm, a mismatch between the two
17633        // 63-byte pins) surfaces at this pin's diagnostic rather than at
17634        // a per-cluster admission rejection whose "field is invalid"
17635        // opacity misframes the root cause.
17636        let mut s = three_member_spec();
17637        let over_cap_label = format!(
17638            "{}.quero.cloud",
17639            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
17640        );
17641        s.entrada.as_mut().unwrap().host = over_cap_label;
17642        let err = s.validate().unwrap_err();
17643        match err {
17644            AplicacaoError::EntradaHostInvalid { reason, .. } => {
17645                let needle = format!(
17646                    "label max length of {} bytes",
17647                    crate::render::DNS_1123_LABEL_MAX_LEN,
17648                );
17649                assert!(
17650                    reason.contains(&needle),
17651                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
17652                     cap verbatim on the per-label arm, got: {reason:?}",
17653                );
17654            }
17655            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17656        }
17657    }
17658
17659    #[test]
17660    fn entrada_with_empty_paths_validates() {
17661        // Empty `:paths` is the documented "match every path" form;
17662        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
17663        let mut s = three_member_spec();
17664        s.entrada.as_mut().unwrap().paths = vec![];
17665        s.validate().unwrap();
17666    }
17667
17668    #[test]
17669    fn entrada_root_path_validates() {
17670        // The author-supplied bare-root `:entrada :paths` entry is the
17671        // same byte-shape the peer emit-side catch-all constant
17672        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
17673        // the author's `:paths` list is empty — sweeping the test-side
17674        // probe literal onto the lifted const closes the two-axis pin
17675        // (author-side admit + emit-side canonical fallback) around
17676        // one `&'static str`, so a future rebrand of the catch-all
17677        // reaches both consumers by construction. Peer to
17678        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
17679        // on the canonical-literal pin surface.
17680        let mut s = three_member_spec();
17681        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
17682        s.validate().unwrap();
17683    }
17684
17685    #[test]
17686    fn placement_strategy_variants_round_trip() {
17687        for s in [
17688            PlacementStrategy::SingleNode,
17689            PlacementStrategy::Replicated,
17690            PlacementStrategy::Sharded,
17691        ] {
17692            let p = Placement {
17693                estrategia: s,
17694                clusters: vec!["rio".into()],
17695                affinity: None,
17696                // Route the paired `:shard-key` fixture-builder through the
17697                // typed cross-slot invariant predicate
17698                // [`PlacementStrategy::requires_shard_key`] rather than the
17699                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
17700                // arm-identity predicate — the two answer the same
17701                // question under today's closed accept-set but a future
17702                // arm addition that consumed `:shard-key` under a
17703                // non-`Sharded` name would silently mis-attach the
17704                // fixture's `:shard-key` if the builder read through the
17705                // arm-identity predicate. The cross-slot-invariant
17706                // predicate migrates through one caixa-core edit on any
17707                // future arm addition; the fixture keeps producing a
17708                // `validate()`-passing round-trip by construction.
17709                shard_key: if s.requires_shard_key() {
17710                    Some("$key".into())
17711                } else {
17712                    None
17713                },
17714            };
17715            let json = serde_json::to_string(&p).unwrap();
17716            let back: Placement = serde_json::from_str(&json).unwrap();
17717            assert_eq!(back, p);
17718        }
17719    }
17720
17721    #[test]
17722    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
17723        // The fail-before-pass-after pin: pre-lift there was no
17724        // single-source binding between the [`PlacementStrategy`]
17725        // variant name the `Serialize` derive emits and the byte-
17726        // string every downstream cluster-side dispatcher (the
17727        // `lareira-fleet-programs` aggregator's per-entry strategy
17728        // branch, the future `app-operator` reconciler, the M3
17729        // Adaptive compression pass's per-strategy weighting) probes
17730        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
17731        // future `#[serde(rename_all = "kebab-case")]` attribute on
17732        // the enum — or a variant rename in the source — would
17733        // silently rebrand the emitted scalar under one spelling
17734        // while every downstream dispatcher still probed the other,
17735        // with the failure surfacing at the aggregator's dispatch
17736        // step or the operator's reconcile posture (workloads coming
17737        // up under the `default()` `Replicated` arm rather than the
17738        // typed slot's declared strategy) far from the source
17739        // rebrand commit and with no field naming the drift. Pinning
17740        // the two paths (the `Serialize` derive's serialized string
17741        // AND the [`PlacementStrategy::as_str`] helper) to the same
17742        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
17743        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
17744        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
17745        // makes any future drift on either endpoint fail here at
17746        // caixa-core build time.
17747        for (variant, expected) in [
17748            (
17749                PlacementStrategy::SingleNode,
17750                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17751            ),
17752            (
17753                PlacementStrategy::Replicated,
17754                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17755            ),
17756            (
17757                PlacementStrategy::Sharded,
17758                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17759            ),
17760        ] {
17761            let json = serde_json::to_string(&variant).unwrap();
17762            assert_eq!(
17763                json,
17764                format!("\"{expected}\""),
17765                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
17766            );
17767            assert_eq!(
17768                variant.as_str(),
17769                expected,
17770                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
17771                 M3_PLACEMENT_ESTRATEGIA_* constant"
17772            );
17773        }
17774    }
17775
17776    #[test]
17777    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
17778        // Cross-arm drift-detection pin on the M3
17779        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
17780        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
17781        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
17782        // scalar-value pentad: a future collapse of two canonical
17783        // variant byte-strings onto the same value (an accidental
17784        // copy-paste flip of
17785        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
17786        // read `"SingleNode"`, a per-arm rebrand that lands one const
17787        // without touching its paired peer) would silently reroute
17788        // every downstream operator's per-strategy dispatch onto the
17789        // sibling arm's reconcile branch and pass every
17790        // propagation-probe test that expected only the stale arm's
17791        // value — a `Replicated`-declared Aplicacao would come up
17792        // under the `SingleNode` primary-and-standby reconcile
17793        // posture, so every-cluster active-active workload would
17794        // silently collapse onto one-cluster-runs-at-a-time takeover
17795        // semantics against its declared strategy, with no field
17796        // naming the strategy-value drift root cause. Peer of the
17797        // sibling
17798        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
17799        // (09ffb2d) /
17800        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
17801        // (ccdf955) /
17802        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
17803        // (d739850) distinctness pins on the sibling OTP-shape /
17804        // caixa-kind closed-set typed-enum discriminator axes — the
17805        // fourth (and structurally the M3 mesh-primitive-defining)
17806        // closed-set typed-enum axis to converge on the same
17807        // "pairwise-distinct-by-construction" discipline.
17808        //
17809        // Fail-before-pass-after locally verified by mutating
17810        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
17811        // also read `"SingleNode"` — this pin fires as expected;
17812        // restoring passes.
17813        let all = [
17814            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
17815            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
17816            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
17817        ];
17818        for (i, a) in all.iter().enumerate() {
17819            for (j, b) in all.iter().enumerate() {
17820                if i != j {
17821                    assert_ne!(
17822                        a, b,
17823                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
17824                         distinct — got duplicate {a:?} at indices {i} and {j}",
17825                    );
17826                }
17827            }
17828        }
17829    }
17830
17831    #[test]
17832    fn placement_strategy_display_routes_through_as_str_helper() {
17833        // The fail-before-pass-after pin: pre-lift the sibling
17834        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
17835        // / [`crate::supervisor::RestartPolicy`] both carried a stable
17836        // [`std::fmt::Display`] surface via their
17837        // `#[discriminant(also_display)]` gen-platform derive, but
17838        // [`PlacementStrategy`] did not — every consumer reaching for
17839        // a strategy byte-string past the wire format had to pick
17840        // between three paths ([`PlacementStrategy::as_str`], the
17841        // `Serialize` derive's serialized string, or `format!("{v:?}")`
17842        // on the `Debug` derive), any two of which a future variant
17843        // rename or `#[serde(rename_all = "kebab-case")]` attribute
17844        // would silently desynchronize. Wiring [`std::fmt::Display`]
17845        // through [`PlacementStrategy::as_str`] closes the third path:
17846        // every `format!("{v}")` call reaches the same lifted
17847        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
17848        // and the [`PlacementStrategy::as_str`] helper already route
17849        // through, so a future variant rename lands at exactly one
17850        // place. Pin the routing here so a future
17851        // `impl std::fmt::Display for PlacementStrategy` reimplementation
17852        // that hand-rolls the arms instead of delegating to
17853        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
17854        for variant in [
17855            PlacementStrategy::SingleNode,
17856            PlacementStrategy::Replicated,
17857            PlacementStrategy::Sharded,
17858        ] {
17859            assert_eq!(
17860                variant.to_string(),
17861                variant.as_str(),
17862                "PlacementStrategy::{variant:?} Display must route through \
17863                 PlacementStrategy::as_str (single source of truth: the lifted \
17864                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
17865            );
17866        }
17867    }
17868
17869    #[test]
17870    fn placement_strategy_display_matches_serialized_wire_byte_string() {
17871        // The fail-before-pass-after pin on the second half of the
17872        // three-path convergence: `Display` (user-facing text) agrees
17873        // byte-for-byte with the `Serialize` derive's wire format
17874        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
17875        // scalar) on every variant. Pre-lift the two paths were
17876        // structurally independent — a future
17877        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
17878        // would silently rebrand the emitted wire scalar
17879        // (`single-node`, `replicated`, `sharded`) while every consumer
17880        // that pretty-prints the strategy (the M3 diagnostic templates,
17881        // the future `feira app graph` per-Aplicacao strategy line,
17882        // the future M4 CR materializer's admission-webhook rejection
17883        // body) would still emit the TitleCase form the `as_str` /
17884        // `Display` route returns, with the mismatch surfacing at
17885        // consumer parse time / operator dispatch time far from the
17886        // source rebrand commit. Pin the two paths byte-for-byte here
17887        // so any future serde-attribute or variant-rename drift is a
17888        // caixa-core-build-time test failure at this call, not a
17889        // silent per-consumer dispatch miss.
17890        for variant in [
17891            PlacementStrategy::SingleNode,
17892            PlacementStrategy::Replicated,
17893            PlacementStrategy::Sharded,
17894        ] {
17895            let wire = serde_json::to_string(&variant).unwrap();
17896            // Strip the outer `"…"` the JSON string form carries — the
17897            // wire scalar the K8s / YAML apiserver consumes is the
17898            // enclosed byte-string, not the quote wrapper.
17899            let unquoted = wire
17900                .strip_prefix('"')
17901                .and_then(|s| s.strip_suffix('"'))
17902                .expect("serialized PlacementStrategy is a JSON string");
17903            assert_eq!(
17904                variant.to_string(),
17905                unquoted,
17906                "PlacementStrategy::{variant:?} Display byte-string must match the \
17907                 Serialize derive's wire byte-string (three-path convergence: \
17908                 Display + as_str + Serialize all resolve to the same \
17909                 M3_PLACEMENT_ESTRATEGIA_* const)"
17910            );
17911        }
17912    }
17913
17914    #[test]
17915    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
17916        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
17917        // derive on [`PlacementStrategy`]: for each of the three variants
17918        // exactly one of the generated `is_single_node` / `is_replicated`
17919        // / `is_sharded` predicates returns `true` and the other two
17920        // return `false`. Prior to this derive the three per-arm
17921        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
17922        // (the `placement_strategy_variants_round_trip` fixture, the
17923        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
17924        // fixture, and the
17925        // `validate_placement_reads_through_lifted_estrategia_accessor`
17926        // fixture) each open-coded a per-arm PartialEq compare against
17927        // the enum variant — three sites that expressed no compile-time
17928        // link back to the closed-set typed dispatch a future fourth
17929        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
17930        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
17931        // would have to thread through in lockstep or one fixture would
17932        // silently disagree with the others on which arms consume the
17933        // `:shard-key` axis. Peer of the sibling
17934        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
17935        // / [`crate::supervisor::RestartPolicy`] /
17936        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
17937        // the sibling closed-set typed-enum discriminator axes — extends
17938        // the same one-typed-dispatch-per-variant discipline onto the
17939        // fifth (and only remaining) closed-set typed-enum discriminator
17940        // on the caixa surface, closing the axis on the M3 mesh-slot
17941        // family.
17942        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
17943            (PlacementStrategy::SingleNode, [true, false, false]),
17944            (PlacementStrategy::Replicated, [false, true, false]),
17945            (PlacementStrategy::Sharded, [false, false, true]),
17946        ];
17947        for (variant, expected) in rows {
17948            let observed = [
17949                variant.is_single_node(),
17950                variant.is_replicated(),
17951                variant.is_sharded(),
17952            ];
17953            assert_eq!(
17954                observed, expected,
17955                "PlacementStrategy::{variant:?} is_* predicates must partition \
17956                 the arm set (single_node, replicated, sharded); got {observed:?}"
17957            );
17958        }
17959    }
17960
17961    #[test]
17962    fn placement_strategy_is_variant_predicates_are_const_fn() {
17963        // The [`gen_platform::IsVariant`] derive emits `const fn`
17964        // predicates on the peer [`crate::CaixaKind`] +
17965        // [`crate::upgrade::UpgradeInstruction`] +
17966        // [`crate::supervisor::RestartStrategy`] +
17967        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
17968        // pin the same posture on [`PlacementStrategy`] so a future
17969        // accidental downgrade to non-`const` (an added runtime helper
17970        // reachable only from a non-`const` context, a manual hand-rolled
17971        // `impl` that shadows the derive-generated method) trips at
17972        // caixa-core build time rather than surfacing as a downstream
17973        // `const`-context regression far from the derive declaration.
17974        //
17975        // The pin lives inside a `const { assert!(..) }` block so the
17976        // compiler enforces both halves (arm predicate is `const`-
17977        // callable AND returns `true` for the matching arm) at
17978        // caixa-core compile time — peer to the sibling
17979        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
17980        // pins on the closed-set typed enum arm-predicate const-
17981        // callability axis.
17982        const {
17983            assert!(PlacementStrategy::SingleNode.is_single_node());
17984            assert!(PlacementStrategy::Replicated.is_replicated());
17985            assert!(PlacementStrategy::Sharded.is_sharded());
17986        }
17987    }
17988
17989    #[test]
17990    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
17991        // Fail-before-pass-after pin on the substrate-lifted
17992        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
17993        // per-arm predicate: for each variant in the closed accept-set the
17994        // predicate returns `true` iff the variant consumes the paired
17995        // [`Placement::shard_key`] axis under
17996        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
17997        // partition. Today the accept-set is the singleton `{Sharded}` —
17998        // `Sharded` is the Akka-style hash-keyed distribution arm
17999        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
18000        // §II.1) and `Replicated` (active-active) refuse the axis through
18001        // [`AplicacaoError::ShardKeyOnNonSharded`].
18002        //
18003        // Pins the per-arm truth-table so a future arm addition (an
18004        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
18005        // roadmap names, a `WeightedShard` promotion the future M5
18006        // adaptive-placement engine acknowledges) that landed a variant
18007        // without extending this predicate's arm-set would surface as a
18008        // caixa-core build-time exhaustiveness error at the
18009        // `match self { … }` arm-fan below rather than a silent per-consumer
18010        // mis-classification at renderer emit time. The paired
18011        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
18012        // predicate stays a distinct question — arm-identity (which the
18013        // sibling
18014        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
18015        // pin already locks) is not cross-slot-invariant consumption; today
18016        // they trip on the same singleton but the pair migrates through
18017        // one caixa-core edit on any future arm addition.
18018        //
18019        // Peer of the sibling per-arm classifier pins
18020        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
18021        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
18022        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
18023        // derived paired predicate on the post-projection typed-view axis
18024        // — same "per-arm semantic-classification predicate paired with
18025        // the arm-identity predicate the derive already emits" discipline
18026        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
18027        // `:placement :shard-key` cross-slot-invariant axis.
18028        let rows: [(PlacementStrategy, bool); 3] = [
18029            (PlacementStrategy::SingleNode, false),
18030            (PlacementStrategy::Replicated, false),
18031            (PlacementStrategy::Sharded, true),
18032        ];
18033        for (variant, expected) in rows {
18034            assert_eq!(
18035                variant.requires_shard_key(),
18036                expected,
18037                "PlacementStrategy::{variant:?}.requires_shard_key() must \
18038                 be {expected} (the substrate-canonical cross-slot invariant \
18039                 on the :placement :shard-key axis; today `Sharded` is the \
18040                 singleton consuming arm — MESH-COMPOSITION §II.4)",
18041            );
18042        }
18043    }
18044
18045    #[test]
18046    fn placement_strategy_requires_shard_key_is_const_fn() {
18047        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
18048        // invariant per-arm predicate is declared `#[must_use] pub const
18049        // fn` — pin the `const`-eval posture here so a future accidental
18050        // downgrade to non-`const` (an added runtime helper reachable
18051        // only from a non-`const` context, a manual hand-rolled `impl`
18052        // that shadows the current three-arm `match self { … }` dispatch)
18053        // trips at caixa-core build time rather than surfacing as a
18054        // downstream `const`-context regression far from the declaration.
18055        // Same shape as the sibling
18056        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
18057        // the peer [`gen_platform::IsVariant`]-derived arm-identity
18058        // predicate axis, but here the load-bearing assertions live in
18059        // module-scope `const _: () = assert!(…)` items so a violation
18060        // fails at compile time (const-eval trip) rather than test time —
18061        // strictly stronger than the runtime `assert!(CONST)` pattern the
18062        // sibling pin uses, and side-steps the
18063        // `clippy::assertions_on_constants` lint the runtime pattern
18064        // otherwise accumulates on the module baseline.
18065        //
18066        // The test body simply witnesses that the module-scope items
18067        // compiled and the runtime dispatch agrees with the const-eval
18068        // dispatch on every arm — the runtime read gives the test a
18069        // failure surface (rather than an empty test body clippy would
18070        // flag as a no-op).
18071        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
18072        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
18073        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
18074        assert_eq!(
18075            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
18076            [
18077                PlacementStrategy::SingleNode.requires_shard_key(),
18078                PlacementStrategy::Replicated.requires_shard_key(),
18079                PlacementStrategy::Sharded.requires_shard_key(),
18080            ],
18081            "runtime and const-eval dispatch on \
18082             PlacementStrategy::requires_shard_key must agree on every arm",
18083        );
18084    }
18085
18086    #[test]
18087    fn placement_estrategia_accessor_is_const_fn() {
18088        // The [`Placement::estrategia`] per-`:placement` distribution-
18089        // strategy `Copy`-return scalar accessor is declared
18090        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
18091        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
18092        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
18093        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
18094        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
18095        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
18096        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
18097        // [`RateLimit`], every one a `pub const fn`). Pin the
18098        // `const`-eval posture here so a future accidental downgrade to
18099        // non-`const` (an added runtime helper reachable only from a
18100        // non-`const` context, a slot promotion to a non-`Copy` return
18101        // that would silently drop the `const` qualifier, a manual
18102        // hand-rolled shadow) trips at caixa-core build time rather
18103        // than surfacing as a downstream `const`-context regression far
18104        // from the declaration.
18105        //
18106        // Same shape as the sibling
18107        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
18108        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
18109        // predicate axis — the load-bearing witness lives in the
18110        // module-scope `const fn` wrapper `estrategia_via_const_fn`
18111        // below: a body that calls [`Placement::estrategia`] under a
18112        // `const fn` signature is well-formed only when the callee is
18113        // itself `const fn`, so any future accidental downgrade of
18114        // [`Placement::estrategia`] to non-`const` fails at caixa-core
18115        // build time (const-eval E0015 / E0658 depending on the arm),
18116        // strictly stronger than a runtime `assert!(CONST)` and
18117        // side-stepping the destructor-in-const restriction that
18118        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
18119        // items on `Placement`'s `Vec<String>` / `Option<String>`
18120        // carriers.
18121        //
18122        // The runtime body witnesses that the const-eval-shaped
18123        // wrapper agrees with a direct call on every closed-set arm.
18124        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
18125            p.estrategia()
18126        }
18127        for estrategia in [
18128            PlacementStrategy::SingleNode,
18129            PlacementStrategy::Replicated,
18130            PlacementStrategy::Sharded,
18131        ] {
18132            let placement = Placement {
18133                estrategia,
18134                clusters: Vec::new(),
18135                affinity: None,
18136                shard_key: None,
18137            };
18138            assert_eq!(
18139                estrategia_via_const_fn(&placement),
18140                placement.estrategia(),
18141                "const-fn-wrapped and direct dispatch on \
18142                 Placement::estrategia must agree for {estrategia:?}",
18143            );
18144        }
18145    }
18146
18147    #[test]
18148    fn entrada_port_accessor_is_const_fn() {
18149        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
18150        // scalar accessor is declared `#[must_use] pub const fn` —
18151        // matching the peer M3 mesh-slot `Copy`-return accessor family
18152        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
18153        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
18154        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
18155        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
18156        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
18157        // [`RateLimit::window`] on the sibling [`RateLimit`], the
18158        // sibling per-`:placement` [`Placement::estrategia`] pinned by
18159        // [`placement_estrategia_accessor_is_const_fn`] above — every
18160        // one a `pub const fn`). Pin the `const`-eval posture here so
18161        // a future accidental downgrade to non-`const` (an added
18162        // runtime helper reachable only from a non-`const` context, an
18163        // `Option<u16>`-shape migration once the substrate grows
18164        // per-`:membros` heterogeneous listener ports that would
18165        // silently drop the `const` qualifier, a manual hand-rolled
18166        // shadow) trips at caixa-core build time rather than surfacing
18167        // as a downstream `const`-context regression far from the
18168        // declaration.
18169        //
18170        // Same shape as the sibling
18171        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
18172        // load-bearing witness lives in the module-scope `const fn`
18173        // wrapper `port_via_const_fn`: a body that calls
18174        // [`Entrada::port`] under a `const fn` signature is well-formed
18175        // only when the callee is itself `const fn`, side-stepping the
18176        // destructor-in-const restriction that would otherwise block a
18177        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
18178        // `String` / `Vec<String>` carriers.
18179        //
18180        // The runtime body sweeps a representative port set spanning
18181        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
18182        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
18183        // ceiling — the const-fn-wrapped call must agree with a direct
18184        // call on every fixture (a violation trips the test) and every
18185        // returned scalar must byte-equal the input `port` (a violation
18186        // means the accessor stopped being a raw field-return copy).
18187        const fn port_via_const_fn(e: &Entrada) -> u16 {
18188            e.port()
18189        }
18190        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
18191            let entrada = Entrada {
18192                host: String::new(),
18193                para: String::new(),
18194                port,
18195                paths: Vec::new(),
18196            };
18197            assert_eq!(
18198                port_via_const_fn(&entrada),
18199                entrada.port(),
18200                "const-fn-wrapped and direct dispatch on Entrada::port \
18201                 must agree for port={port}",
18202            );
18203            assert_eq!(
18204                entrada.port(),
18205                port,
18206                "Entrada::port must return the storage-side u16 verbatim \
18207                 for port={port}",
18208            );
18209        }
18210    }
18211
18212    #[test]
18213    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
18214        // Load-bearing cross-slot-partition pin closing the loop between
18215        // the substrate-lifted
18216        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
18217        // the closed-set typed enum and the actual
18218        // [`AplicacaoSpec::validate_placement`] runtime behavior across
18219        // the paired `:placement :shard-key` axis: every validated
18220        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
18221        // satisfies `placement.shard_key().is_some() ==
18222        // placement.estrategia().requires_shard_key()`. The four-cell
18223        // shape witness sweeps every combination of (variant in the
18224        // closed accept-set, `:shard-key` Some/None) and pins:
18225        //
18226        //   * variant.requires_shard_key() && shard_key.is_some() →
18227        //     validate() passes; the paired shape is the sole
18228        //     `requires_shard_key` arm-family accepted shape.
18229        //   * variant.requires_shard_key() && shard_key.is_none() →
18230        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
18231        //     the paired shape is the refused missing-key shape on
18232        //     Sharded-family arms.
18233        //   * !variant.requires_shard_key() && shard_key.is_some() →
18234        //     validate() fails with
18235        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
18236        //     is the refused declared-but-inert shape on non-Sharded-
18237        //     family arms.
18238        //   * !variant.requires_shard_key() && shard_key.is_none() →
18239        //     validate() passes; the paired shape is the sole
18240        //     non-`requires_shard_key` arm-family accepted shape.
18241        //
18242        // The compile-time-exhaustive `match p.estrategia()` dispatch at
18243        // [`AplicacaoSpec::validate_placement`] preserves its structural
18244        // arm-fan (a future arm addition still surfaces a build-time
18245        // exhaustiveness error there); this pin closes the semantic loop
18246        // between the arm-fan's shape-gate cascades and the substrate-
18247        // canonical predicate every downstream consumer of the paired
18248        // shape reads through. Fail-before-pass-after locally verified by
18249        // mutating the predicate's `Sharded => true` arm to `false` — the
18250        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
18251        // `validate() must pass` assertion; restoring passes. Same "close
18252        // the loop between the typed predicate and the runtime behavior"
18253        // discipline as the sibling
18254        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
18255        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
18256        // per-arm classifier axis.
18257        for variant in [
18258            PlacementStrategy::SingleNode,
18259            PlacementStrategy::Replicated,
18260            PlacementStrategy::Sharded,
18261        ] {
18262            for present in [false, true] {
18263                let mut spec = three_member_spec();
18264                spec.placement.estrategia = variant;
18265                spec.placement.shard_key = present.then(|| "tenantId".into());
18266                let expects_ok = variant.requires_shard_key() == present;
18267                let result = spec.validate();
18268                match (expects_ok, &result) {
18269                    (true, Ok(())) => {}
18270                    (false, Err(err)) => {
18271                        // Cross-check the refusal diagnostic names the
18272                        // right cell of the four-cell shape witness — the
18273                        // `requires_shard_key && !present` cell must trip
18274                        // [`AplicacaoError::ShardedWithoutKey`]; the
18275                        // `!requires_shard_key && present` cell must trip
18276                        // [`AplicacaoError::ShardKeyOnNonSharded`].
18277                        match (variant.requires_shard_key(), present, err) {
18278                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
18279                            (
18280                                false,
18281                                true,
18282                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
18283                            ) => {
18284                                assert_eq!(
18285                                    *e, variant,
18286                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
18287                                     the paired PlacementStrategy",
18288                                );
18289                            }
18290                            _ => panic!(
18291                                "unexpected refusal for estrategia={variant:?} \
18292                                 present={present}: {err:?}"
18293                            ),
18294                        }
18295                    }
18296                    (true, Err(err)) => panic!(
18297                        "validate() must pass for estrategia={variant:?} \
18298                         present={present} (requires_shard_key={} == present={present}), \
18299                         got {err:?}",
18300                        variant.requires_shard_key(),
18301                    ),
18302                    (false, Ok(())) => panic!(
18303                        "validate() must fail for estrategia={variant:?} \
18304                         present={present} (requires_shard_key={} != present={present})",
18305                        variant.requires_shard_key(),
18306                    ),
18307                }
18308            }
18309        }
18310    }
18311
18312    #[test]
18313    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
18314        // Pin the M3 diagnostic template routes through the typed
18315        // [`PlacementStrategy`] Display byte-string (rebound from the
18316        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
18317        // routes emitted identical bytes (the `Debug` derive on a
18318        // unit variant emits the variant name verbatim, exactly what
18319        // `as_str` returns), but the two paths were structurally
18320        // independent — a future `#[serde(rename_all = "…")]`
18321        // attribute or variant rename would coordinate the wire /
18322        // `Display` / `as_str` triple through the lifted const but
18323        // leave the `Debug` route on the compiler-derived variant name,
18324        // silently desynchronizing the diagnostic byte-string from the
18325        // wire byte-string. Rebinding the template onto `Display`
18326        // ties the diagnostic to the same lifted
18327        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
18328        // emits — drift becomes structurally impossible. Pin the
18329        // byte-string here so a future edit that reverts the template
18330        // to `{estrategia:?}` is caught at caixa-core test time, not
18331        // at consumer dispatch time.
18332        for (variant, expected_scalar) in [
18333            (
18334                PlacementStrategy::SingleNode,
18335                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18336            ),
18337            (
18338                PlacementStrategy::Replicated,
18339                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18340            ),
18341            (
18342                PlacementStrategy::Sharded,
18343                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18344            ),
18345        ] {
18346            let err = AplicacaoError::PlacementWithoutClusters {
18347                estrategia: variant,
18348            };
18349            let msg = err.to_string();
18350            assert!(
18351                msg.starts_with(&format!(":placement {expected_scalar} requires")),
18352                "PlacementWithoutClusters diagnostic for {variant:?} must open \
18353                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
18354            );
18355        }
18356    }
18357
18358    #[test]
18359    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
18360        // Peer of
18361        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
18362        // on the second M3 diagnostic that carries the typed
18363        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
18364        // diagnostics now route the strategy scalar through the same
18365        // [`std::fmt::Display`] surface, tying the diagnostic
18366        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
18367        // const set the wire format also emits. The two non-Sharded
18368        // arms are exercised here (the diagnostic exists to flag a
18369        // `:shard-key` slot the current strategy will never consume);
18370        // the peer `Sharded` arm never reaches this diagnostic (the
18371        // `Sharded` strategy consumes `:shard-key` — the
18372        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
18373        // slot instead).
18374        for (variant, expected_scalar) in [
18375            (
18376                PlacementStrategy::SingleNode,
18377                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18378            ),
18379            (
18380                PlacementStrategy::Replicated,
18381                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18382            ),
18383        ] {
18384            let err = AplicacaoError::ShardKeyOnNonSharded {
18385                estrategia: variant,
18386                shard_key: "$tenantId".into(),
18387            };
18388            let msg = err.to_string();
18389            assert!(
18390                msg.starts_with(&format!(":placement {expected_scalar} carries")),
18391                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
18392                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
18393            );
18394        }
18395    }
18396
18397    #[test]
18398    fn placement_strategy_all_enumerates_every_variant_once() {
18399        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
18400        // exhaustive-iteration surface: every variant appears exactly
18401        // once, and the slice length matches the arm count of the
18402        // closed set. Every consumer that walks the accepted-strategy
18403        // set (a future `feira app placement --list` CLI-side surfacing,
18404        // a future M4 admission-webhook's rejection body naming the
18405        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
18406        // reverse-projection consumers that iterate the accept-set for
18407        // a "did you mean" hint) reads through this slice, so a future
18408        // variant addition (an `Anycast` mesh-anycast arm the
18409        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
18410        // grows the enum but forgets to grow [`Self::ALL`] silently
18411        // truncates every downstream consumer's accept-set at the same
18412        // pre-addition boundary — this pin fails at caixa-core build
18413        // time on the pairwise-distinct + arm-count invariants.
18414        //
18415        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
18416        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
18417        // pins on the peer closed-set typed-enum axes.
18418        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
18419        assert_eq!(
18420            all.len(),
18421            3,
18422            "PlacementStrategy::ALL must enumerate every variant of the \
18423             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
18424        );
18425        for (i, a) in all.iter().enumerate() {
18426            for (j, b) in all.iter().enumerate() {
18427                if i != j {
18428                    assert_ne!(
18429                        a, b,
18430                        "PlacementStrategy::ALL must carry every variant exactly \
18431                         once — got duplicate {a:?} at indices {i} and {j}"
18432                    );
18433                }
18434            }
18435        }
18436        for variant in [
18437            PlacementStrategy::SingleNode,
18438            PlacementStrategy::Replicated,
18439            PlacementStrategy::Sharded,
18440        ] {
18441            assert!(
18442                all.contains(&variant),
18443                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
18444                 addition that grows the enum but forgets to grow the ALL slice \
18445                 silently truncates every downstream consumer's accept-set at the \
18446                 pre-addition boundary"
18447            );
18448        }
18449    }
18450
18451    #[test]
18452    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
18453        // Fail-before-pass-after pin on the forward accept-set of the
18454        // [`PlacementStrategy::from_wire`] reverse projection: every
18455        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
18456        // constant the [`PlacementStrategy::as_str`] emitter walks
18457        // parses back to its paired variant. Any future arm addition
18458        // that grows the emitter's `as_str` match but forgets to grow
18459        // the parser's `from_str` match silently splits the two halves
18460        // of the round-trip — the wire byte-string one non-serde
18461        // consumer parses from the one the emitter wrote — with the
18462        // failure surfacing at parse time far from the rebrand commit.
18463        // Pinning the three-arm accept-set here catches the drift at
18464        // caixa-core build time.
18465        //
18466        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
18467        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
18468        // closed-set typed-enum `str → Self` axes.
18469        for (wire, expected) in [
18470            (
18471                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18472                PlacementStrategy::SingleNode,
18473            ),
18474            (
18475                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18476                PlacementStrategy::Replicated,
18477            ),
18478            (
18479                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18480                PlacementStrategy::Sharded,
18481            ),
18482        ] {
18483            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
18484                panic!(
18485                    "PlacementStrategy::from_wire({wire:?}) must accept every \
18486                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
18487                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
18488                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
18489                )
18490            });
18491            assert_eq!(
18492                parsed, expected,
18493                "PlacementStrategy::from_wire({wire:?}) must return \
18494                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
18495            );
18496        }
18497    }
18498
18499    #[test]
18500    fn placement_strategy_from_wire_round_trips_through_as_str() {
18501        // Fail-before-pass-after pin on the closed round-trip between
18502        // the forward [`PlacementStrategy::as_str`] emitter and the
18503        // reverse [`PlacementStrategy::from_wire`] parser: for every
18504        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
18505        // output must return exactly the same variant. Any per-arm
18506        // divergence — a future arm added to `as_str` but not
18507        // `from_str`, an accidental copy-paste flip in one but not the
18508        // other — silently splits the emit and parse halves and the
18509        // failure surfaces at consumer parse time far from the drift
18510        // site. The `ALL`-iterating shape means a future variant
18511        // addition picks up the coverage by construction.
18512        //
18513        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
18514        // [`crate::CaixaKind::from_wire`] and the
18515        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
18516        // sibling round-trip pin on [`RateLimitUnit`].
18517        for &variant in PlacementStrategy::ALL {
18518            let wire = variant.as_str();
18519            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
18520                panic!(
18521                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
18522                     must be Some({variant:?}) — the two halves of the round-trip \
18523                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
18524                     got None on wire byte-string {wire:?}"
18525                )
18526            });
18527            assert_eq!(
18528                parsed, variant,
18529                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
18530                 must round-trip to the same variant; got {parsed:?}"
18531            );
18532        }
18533    }
18534
18535    #[test]
18536    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
18537        // Fail-before-pass-after pin on the closed-set refusal
18538        // discipline of [`PlacementStrategy::from_wire`]: every
18539        // byte-string outside the three-arm accept-set returns `None`
18540        // rather than silently collapsing onto the [`Default`]
18541        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
18542        // exercised here sweeps the load-bearing drift shapes: the
18543        // empty string (a stripped serde-attribute drift), an all-
18544        // whitespace string (the canonical text-editor accidental
18545        // padding shape), the lowercased kebab-case forms a future
18546        // `#[serde(rename_all = "kebab-case")]` attribute would emit
18547        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
18548        // coincidentally match the accepted canonical scalars, so only
18549        // `"single-node"` fires as a refusal, but pinning the case-
18550        // sensitivity of the accepted arms via the peer [`SingleNode`]
18551        // assertion in the round-trip pin makes the discipline
18552        // structurally clear), the lowercased single-word forms
18553        // (`"singlenode"`), the padded canonical scalar
18554        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
18555        // (`"Sharded\n"`), and a pointer-different `&'static str` that
18556        // happens to alias a canonical byte-string by content but not
18557        // by identity (validated implicitly by the emitter's routing
18558        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
18559        // identity a paired [`crate::assert_str_reexport_identity`] pin
18560        // in caixa-core's per-const declaration surface would catch).
18561        //
18562        // Peer of the sibling
18563        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
18564        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
18565        for bad in [
18566            "",
18567            " ",
18568            "\n",
18569            "\t",
18570            "single-node",
18571            "singlenode",
18572            "SingleNodes",
18573            "single_node",
18574            "single node",
18575            "SINGLENODE",
18576            "SingleNode ",
18577            " SingleNode",
18578            " Sharded ",
18579            "Sharded\n",
18580            "replicated ",
18581            "sharded",
18582            "REPLICATED",
18583            "Anycast",
18584            "Global",
18585            "?",
18586        ] {
18587            assert!(
18588                PlacementStrategy::from_wire(bad).is_none(),
18589                "PlacementStrategy::from_wire({bad:?}) must return None — the \
18590                 parser's accept-set is exactly the three PlacementStrategy::as_str \
18591                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
18592                 is outside that closed set"
18593            );
18594        }
18595    }
18596
18597    #[test]
18598    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
18599        // Fail-before-pass-after pin on the third path of the four-path
18600        // convergence: `from_str` (the reverse projection) inverts the
18601        // `Serialize` derive's wire byte-string on every variant.
18602        // Together with the pre-existing three-path convergence
18603        // (`Display` + `as_str` + `Serialize` all resolve to the same
18604        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
18605        // the peer
18606        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
18607        // this closes the round-trip: the wire byte-string the
18608        // `Serialize` derive emits parses back to the same variant
18609        // through `from_str`, so any future serde-attribute or variant-
18610        // rename drift on the emit half now surfaces as a matched drift
18611        // on the parse half at caixa-core build time — the two halves
18612        // migrate as a unit through the lifted consts on any future
18613        // rename, and the round-trip cannot silently split.
18614        //
18615        // Peer of the sibling
18616        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
18617        // wire-format pin — extends the three-path convergence
18618        // (`Display` + `as_str` + `Serialize`) onto the fourth path
18619        // (`from_str`), closing the `str ↔ Self` round-trip on the
18620        // M3 `:placement :estrategia` closed-set axis.
18621        for &variant in PlacementStrategy::ALL {
18622            let wire = serde_json::to_string(&variant).unwrap();
18623            let unquoted = wire
18624                .strip_prefix('"')
18625                .and_then(|s| s.strip_suffix('"'))
18626                .expect("serialized PlacementStrategy is a JSON string");
18627            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
18628                panic!(
18629                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
18630                     Serialize derive's wire byte-string for \
18631                     PlacementStrategy::{variant:?} — the four-path convergence \
18632                     (Display + as_str + Serialize + from_str) resolves through \
18633                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
18634                )
18635            });
18636            assert_eq!(
18637                parsed, variant,
18638                "PlacementStrategy::from_wire of the Serialize derive's wire \
18639                 byte-string for PlacementStrategy::{variant:?} must round-trip \
18640                 to the same variant; got {parsed:?}"
18641            );
18642        }
18643    }
18644
18645    #[test]
18646    fn rejects_zero_policy_timeout() {
18647        let mut s = three_member_spec();
18648        s.politicas.timeout = Some(Duration::ZERO);
18649        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18650    }
18651
18652    #[test]
18653    fn rejects_zero_policy_retries() {
18654        let mut s = three_member_spec();
18655        s.politicas.retries = Some(0);
18656        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
18657    }
18658
18659    #[test]
18660    fn rejects_policy_retries_above_cap() {
18661        // The fail-before-pass-after pin: `Some(11)` is structurally
18662        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
18663        // passed validate on every pre-gate codebase because the
18664        // typed slot's only check was the zero-floor arm. The
18665        // thundering-herd amplification vector only surfaced at the
18666        // runtime substrate (Envoy / Cilium L7 retry overlay)
18667        // far from the source caixa.lisp with no field naming the
18668        // offending policy.
18669        let mut s = three_member_spec();
18670        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
18671        assert_eq!(
18672            s.validate().unwrap_err(),
18673            AplicacaoError::PolicyRetriesExceedsCap {
18674                retries: POLICY_RETRIES_MAX + 1
18675            }
18676        );
18677    }
18678
18679    #[test]
18680    fn rejects_policy_retries_far_above_cap() {
18681        // The `u32::MAX` worst case — the four-billion-retry policy
18682        // a typo (`(:retries 4294967295)`) or struct-literal
18683        // copy-paste lands in the slot. Pin the cap arm's coverage
18684        // explicitly across the full `u32` overflow so a future
18685        // relaxation that drops the upper bound surfaces here.
18686        let mut s = three_member_spec();
18687        s.politicas.retries = Some(u32::MAX);
18688        assert_eq!(
18689            s.validate().unwrap_err(),
18690            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
18691        );
18692    }
18693
18694    #[test]
18695    fn accepts_policy_retries_at_cap() {
18696        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
18697        // must validate. The cap is inclusive on the top edge,
18698        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
18699        // discipline on the sibling [`crate::LimitsSpec::memory`]
18700        // axis. Pin the boundary explicitly so a future off-by-one
18701        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
18702        // surfaces here as a test failure rather than a silent
18703        // contract narrowing.
18704        let mut s = three_member_spec();
18705        s.politicas.retries = Some(POLICY_RETRIES_MAX);
18706        s.validate()
18707            .expect("retries == POLICY_RETRIES_MAX must validate");
18708    }
18709
18710    #[test]
18711    fn accepts_policy_retries_typical_values() {
18712        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
18713        // every value in the validated set must pass. The
18714        // Envoy / Istio production-playbook recommendation band
18715        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
18716        // (`maxRetries ≤ 10`) both lie within this set.
18717        for r in 1..=POLICY_RETRIES_MAX {
18718            let mut s = three_member_spec();
18719            s.politicas.retries = Some(r);
18720            s.validate()
18721                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
18722        }
18723    }
18724
18725    #[test]
18726    fn policy_retries_zero_takes_precedence_over_cap() {
18727        // The cross-arm ordering pin: `Some(0)` is structurally
18728        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
18729        // (cap), but the zero-floor diagnostic is the more
18730        // self-locating one (it directly names the omit-axis
18731        // remediation), so the validate gate must fire on zero
18732        // first. Pin the order so a future refactor that reorders
18733        // the arms surfaces here as a test failure rather than a
18734        // silent diagnostic regression. Same shape every other
18735        // zero-then-shape ordering on this surface uses
18736        // ([`AplicacaoError::PolicyTimeoutZero`] then
18737        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
18738        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
18739        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
18740        let mut s = three_member_spec();
18741        s.politicas.retries = Some(0);
18742        assert_eq!(
18743            s.validate().unwrap_err(),
18744            AplicacaoError::PolicyRetriesZero,
18745            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
18746        );
18747    }
18748
18749    #[test]
18750    fn policy_retries_cap_diagnostic_carries_offending_value() {
18751        // The diagnostic-shape pin: the offending `u32` is carried
18752        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
18753        // variant so the surfaced error message names the value the
18754        // author wrote (`":politicas :retries (47) exceeds the
18755        // mesh-policy ceiling …"`), not just the cap. Same
18756        // self-locating diagnostic shape every other typed-cap arm
18757        // on this surface carries
18758        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
18759        // offending byte count verbatim).
18760        let mut s = three_member_spec();
18761        s.politicas.retries = Some(47);
18762        let err = s.validate().unwrap_err();
18763        assert!(
18764            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
18765            "got {err:?}"
18766        );
18767        let msg = err.to_string();
18768        assert!(
18769            msg.contains("47"),
18770            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
18771        );
18772    }
18773
18774    #[test]
18775    fn policy_retries_cap_is_aws_app_mesh_aligned() {
18776        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
18777        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
18778        // schema cap — the only upstream mesh-policy schema that
18779        // documents an explicit hard cap. Pinning the literal value
18780        // here surfaces a future drift (a relaxation to 20, a
18781        // tightening to 5) as a deliberate test edit, not a silent
18782        // contract narrowing.
18783        assert_eq!(POLICY_RETRIES_MAX, 10);
18784    }
18785
18786    #[test]
18787    fn rejects_circuit_breaker_zero_max_failures() {
18788        let mut s = three_member_spec();
18789        s.politicas.circuit_breaker = Some(CircuitBreaker {
18790            max_failures: 0,
18791            window: Duration::from_secs(60),
18792        });
18793        assert_eq!(
18794            s.validate().unwrap_err(),
18795            AplicacaoError::PolicyBreakerZeroFailures
18796        );
18797    }
18798
18799    #[test]
18800    fn rejects_circuit_breaker_max_failures_above_cap() {
18801        // The fail-before-pass-after pin: `1001` is structurally one
18802        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
18803        // silently passed validate on every pre-gate codebase
18804        // because the typed slot's only check was the zero-floor
18805        // arm. The breaker-no-op vector only surfaced at the runtime
18806        // substrate (Envoy / Cilium L7 outlier-detection overlay)
18807        // far from the source caixa.lisp with no field naming the
18808        // offending policy.
18809        let mut s = three_member_spec();
18810        s.politicas.circuit_breaker = Some(CircuitBreaker {
18811            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18812            window: Duration::from_secs(60),
18813        });
18814        assert_eq!(
18815            s.validate().unwrap_err(),
18816            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18817                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18818            }
18819        );
18820    }
18821
18822    #[test]
18823    fn rejects_circuit_breaker_max_failures_far_above_cap() {
18824        // The `u32::MAX` worst case — the four-billion-failure
18825        // threshold a typo (`(:max-failures 4294967295)`) or a
18826        // struct-literal copy-paste lands in the slot. Pin the cap
18827        // arm's coverage explicitly across the full `u32` overflow
18828        // so a future relaxation that drops the upper bound surfaces
18829        // here.
18830        let mut s = three_member_spec();
18831        s.politicas.circuit_breaker = Some(CircuitBreaker {
18832            max_failures: u32::MAX,
18833            window: Duration::from_secs(60),
18834        });
18835        assert_eq!(
18836            s.validate().unwrap_err(),
18837            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18838                max_failures: u32::MAX,
18839            }
18840        );
18841    }
18842
18843    #[test]
18844    fn accepts_circuit_breaker_max_failures_at_cap() {
18845        // The boundary value — exactly
18846        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
18847        // cap is inclusive on the top edge, matching the
18848        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
18849        // discipline on the sibling capped axes. Pin the boundary
18850        // explicitly so a future off-by-one tightening
18851        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
18852        // surfaces here as a test failure rather than a silent
18853        // contract narrowing.
18854        let mut s = three_member_spec();
18855        s.politicas.circuit_breaker = Some(CircuitBreaker {
18856            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
18857            window: Duration::from_secs(60),
18858        });
18859        s.validate()
18860            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
18861    }
18862
18863    #[test]
18864    fn accepts_circuit_breaker_max_failures_typical_values() {
18865        // The documented production-playbook band positive-control
18866        // sweep — every value Hystrix / Istio / Envoy / Polly /
18867        // Resilience4j recommend (5..=50) must pass, plus a sweep
18868        // through the hyperscale band (100, 500, 1000) the cap
18869        // accepts. Pin the inclusive validated set explicitly so a
18870        // future tightening of the ceiling surfaces here.
18871        //
18872        // Clears the fixture's `:retries` (which is `Some(3)`) so this
18873        // per-axis sweep is pure: the sibling cross-axis
18874        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
18875        // gate rejects any `max_failures <= retries` pair, so the
18876        // `max_failures = 1` boundary at the head of the sweep would
18877        // otherwise trip on the fixture-inherited retry policy rather
18878        // than the per-axis boundary this test names. Same discipline
18879        // the sibling per-axis `accepts_circuit_breaker_window_*`
18880        // sweeps take against the fixture's `:timeout` for the
18881        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
18882        // cross-axis arm.
18883        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
18884            let mut s = three_member_spec();
18885            s.politicas.retries = None;
18886            s.politicas.circuit_breaker = Some(CircuitBreaker {
18887                max_failures: n,
18888                window: Duration::from_secs(60),
18889            });
18890            s.validate()
18891                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
18892        }
18893    }
18894
18895    #[test]
18896    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
18897        // The cross-arm ordering pin: `0` is structurally outside
18898        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
18899        // (cap), but the zero-floor diagnostic is the more
18900        // self-locating one (it directly names the omit-axis
18901        // remediation), so the validate gate must fire on zero
18902        // first. Same shape every other zero-then-shape ordering on
18903        // this surface uses
18904        // ([`AplicacaoError::PolicyRetriesZero`] then
18905        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18906        // [`AplicacaoError::PolicyTimeoutZero`] then
18907        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
18908        let mut s = three_member_spec();
18909        s.politicas.circuit_breaker = Some(CircuitBreaker {
18910            max_failures: 0,
18911            window: Duration::from_secs(60),
18912        });
18913        assert_eq!(
18914            s.validate().unwrap_err(),
18915            AplicacaoError::PolicyBreakerZeroFailures,
18916            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
18917        );
18918    }
18919
18920    #[test]
18921    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
18922        // The cross-arm ordering pin between the cap and the
18923        // sibling `:window` gates (zero-window, canonical-window).
18924        // A breaker carrying both an over-cap `max_failures` AND a
18925        // structurally invalid window (zero, sub-ms) must surface
18926        // the cap diagnostic first — the cap arm is wired
18927        // immediately after the zero-failure arm and strictly
18928        // before the window arms, so the offending value the
18929        // diagnostic names matches the order the author would
18930        // discover the gates by reading top-to-bottom through
18931        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
18932        // future refactor that reorders the arms surfaces here as a
18933        // test failure rather than a silent diagnostic regression.
18934        let mut s = three_member_spec();
18935        s.politicas.circuit_breaker = Some(CircuitBreaker {
18936            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18937            window: Duration::ZERO,
18938        });
18939        assert_eq!(
18940            s.validate().unwrap_err(),
18941            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18942                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18943            },
18944            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
18945        );
18946    }
18947
18948    #[test]
18949    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
18950        // The diagnostic-shape pin: the offending `u32` is carried
18951        // verbatim into the
18952        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
18953        // variant so the surfaced error message names the value the
18954        // author wrote (`":politicas :circuit-breaker :max-failures
18955        // (50000) exceeds the mesh-policy ceiling …"`), not just
18956        // the cap. Same self-locating diagnostic shape every other
18957        // typed-cap arm on this surface carries
18958        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18959        // offending retry count verbatim,
18960        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
18961        // offending byte count verbatim).
18962        let mut s = three_member_spec();
18963        s.politicas.circuit_breaker = Some(CircuitBreaker {
18964            max_failures: 50_000,
18965            window: Duration::from_secs(60),
18966        });
18967        let err = s.validate().unwrap_err();
18968        assert!(
18969            matches!(
18970                err,
18971                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18972                    max_failures: 50_000
18973                }
18974            ),
18975            "got {err:?}"
18976        );
18977        let msg = err.to_string();
18978        assert!(
18979            msg.contains("50000"),
18980            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
18981        );
18982    }
18983
18984    #[test]
18985    fn policy_breaker_max_failures_cap_pins_canonical_value() {
18986        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
18987        // value at 1000 — an order of magnitude above every
18988        // documented production-playbook recommendation band
18989        // (Hystrix `requestVolumeThreshold` default 20, Istio
18990        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
18991        // `outlier_detection.consecutive_5xx` default 5, Polly /
18992        // Resilience4j typical 5..=50) and below the
18993        // clearly-pathological "effectively no protection" floor
18994        // (10_000, 100_000, u32::MAX). Pinning the literal value
18995        // here surfaces a future drift (a relaxation to 10_000, a
18996        // tightening to 100) as a deliberate test edit, not a
18997        // silent contract narrowing.
18998        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
18999    }
19000
19001    #[test]
19002    fn rejects_circuit_breaker_zero_window() {
19003        let mut s = three_member_spec();
19004        s.politicas.circuit_breaker = Some(CircuitBreaker {
19005            max_failures: 5,
19006            window: Duration::ZERO,
19007        });
19008        assert_eq!(
19009            s.validate().unwrap_err(),
19010            AplicacaoError::PolicyBreakerZeroWindow
19011        );
19012    }
19013
19014    #[test]
19015    fn rejects_zero_rate_limit() {
19016        let mut s = three_member_spec();
19017        s.politicas.rate_limit = Some(RateLimit {
19018            rate: 0,
19019            window: Duration::from_secs(1),
19020        });
19021        assert_eq!(
19022            s.validate().unwrap_err(),
19023            AplicacaoError::PolicyRateLimitZero
19024        );
19025    }
19026
19027    #[test]
19028    fn rejects_rate_limit_zero_window() {
19029        // `RateLimit { rate: 100, window: Duration::ZERO }` is
19030        // constructible programmatically (the typed `Duration` field
19031        // imposes no nonzero invariant) but renders through
19032        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
19033        // codec's `parse` rejects as `unknown rate-limit window unit
19034        // "0s"`. Until this validate-time gate landed the typed slot
19035        // accepted the value silently and the round-trip break only
19036        // surfaced at deserialize time (potentially in a downstream
19037        // consumer that never re-validates). Pin the rejection at
19038        // `AplicacaoSpec::validate` so the typed slot's valid set
19039        // matches the codec's round-trippable set structurally.
19040        let mut s = three_member_spec();
19041        s.politicas.rate_limit = Some(RateLimit {
19042            rate: 100,
19043            window: Duration::ZERO,
19044        });
19045        assert_eq!(
19046            s.validate().unwrap_err(),
19047            AplicacaoError::PolicyRateLimitWindowNotCanonical {
19048                window: Duration::ZERO
19049            }
19050        );
19051    }
19052
19053    #[test]
19054    fn rejects_rate_limit_arbitrary_seconds_window() {
19055        // 45 seconds is a valid `Duration` but not one of the three
19056        // canonical rate-limit windows the codec round-trips
19057        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
19058        // refuses on round-trip — same round-trip-break shape the
19059        // zero-window arm above pins, with a non-zero magnitude to
19060        // guard against a future "reject only zero" half-measure.
19061        let mut s = three_member_spec();
19062        let window = Duration::from_secs(45);
19063        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
19064        assert_eq!(
19065            s.validate().unwrap_err(),
19066            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19067        );
19068    }
19069
19070    #[test]
19071    fn rejects_rate_limit_two_minute_window() {
19072        // 120 seconds = 2 minutes is a "looks-canonical" but
19073        // not-canonical window: it's a clean integer multiple of the
19074        // minute unit, but the codec only round-trips the
19075        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
19076        // A `Duration::from_secs(120)` window renders as `"100/120s"`
19077        // which the parser rejects. Pinning this case rules out a
19078        // future "accept any clean multiple of s/m/h" relaxation
19079        // that would silently break the codec contract.
19080        let mut s = three_member_spec();
19081        let window = Duration::from_secs(120);
19082        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
19083        assert_eq!(
19084            s.validate().unwrap_err(),
19085            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19086        );
19087    }
19088
19089    #[test]
19090    fn rejects_rate_limit_subsecond_window() {
19091        // A sub-second window (e.g. 500ms) is a valid `Duration` but
19092        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
19093        // Pin the rejection so a future relaxation can't silently
19094        // admit fractional-second windows that the codec can't
19095        // round-trip.
19096        let mut s = three_member_spec();
19097        let window = Duration::from_millis(500);
19098        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
19099        assert_eq!(
19100            s.validate().unwrap_err(),
19101            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19102        );
19103    }
19104
19105    #[test]
19106    fn rejects_policy_rate_limit_above_cap() {
19107        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
19108        // is structurally one past the cap and silently passed
19109        // validate on every pre-gate codebase because the typed slot's
19110        // only `rate` check was the zero-floor arm. The no-op-limiter
19111        // shape only surfaced at the runtime substrate (Envoy's
19112        // `local_rate_limit.token_bucket.max_tokens`, the future
19113        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
19114        // with no field naming the offending policy.
19115        let mut s = three_member_spec();
19116        s.politicas.rate_limit = Some(RateLimit {
19117            rate: POLICY_RATE_LIMIT_MAX + 1,
19118            window: Duration::from_secs(1),
19119        });
19120        assert_eq!(
19121            s.validate().unwrap_err(),
19122            AplicacaoError::PolicyRateLimitExceedsCap {
19123                rate: POLICY_RATE_LIMIT_MAX + 1
19124            }
19125        );
19126    }
19127
19128    #[test]
19129    fn rejects_policy_rate_limit_far_above_cap() {
19130        // The `u32::MAX` worst case — the four-billion-token rate-limit
19131        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
19132        // copy-paste lands in the slot. Pin the cap arm's coverage
19133        // explicitly across the full `u32` overflow so a future
19134        // relaxation that drops the upper bound surfaces here. Peer to
19135        // `rejects_policy_retries_far_above_cap` on the sibling
19136        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
19137        // on the sibling `:max-failures` axis.
19138        let mut s = three_member_spec();
19139        s.politicas.rate_limit = Some(RateLimit {
19140            rate: u32::MAX,
19141            window: Duration::from_secs(1),
19142        });
19143        assert_eq!(
19144            s.validate().unwrap_err(),
19145            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
19146        );
19147    }
19148
19149    #[test]
19150    fn accepts_policy_rate_limit_at_cap() {
19151        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
19152        // must validate. The cap is inclusive on the top edge, matching
19153        // every other typed upper bound in this crate
19154        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
19155        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
19156        // across all three canonical windows so a future off-by-one
19157        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
19158        // window-conditional cap surfaces here as a test failure rather
19159        // than a silent contract narrowing.
19160        for secs in [1u64, 60, 3600] {
19161            let mut s = three_member_spec();
19162            s.politicas.rate_limit = Some(RateLimit {
19163                rate: POLICY_RATE_LIMIT_MAX,
19164                window: Duration::from_secs(secs),
19165            });
19166            s.validate().unwrap_or_else(|e| {
19167                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
19168            });
19169        }
19170    }
19171
19172    #[test]
19173    fn accepts_policy_rate_limit_typical_values() {
19174        // The documented production-playbook recommendation band —
19175        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
19176        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
19177        // Enterprise ~1M per-hour. Every value in the validated set
19178        // must pass; pin the band explicitly so a future tightening
19179        // surfaces here.
19180        //
19181        // Clears the fixture's `:retries` (which is `Some(3)`) so this
19182        // per-axis sweep is pure: the sibling cross-axis
19183        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
19184        // rejects any `rate <= retries` pair, so the `rate = 1`
19185        // boundary at the head of the sweep would otherwise trip on the
19186        // fixture-inherited retry policy rather than the per-axis
19187        // boundary this test names. Same discipline the sibling per-axis
19188        // `accepts_circuit_breaker_max_failures_typical_values` sweep
19189        // takes against the fixture's `:retries` for the peer cross-axis
19190        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
19191        // arm.
19192        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
19193            for secs in [1u64, 60, 3600] {
19194                let mut s = three_member_spec();
19195                s.politicas.retries = None;
19196                s.politicas.rate_limit = Some(RateLimit {
19197                    rate,
19198                    window: Duration::from_secs(secs),
19199                });
19200                s.validate().unwrap_or_else(|e| {
19201                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
19202                });
19203            }
19204        }
19205    }
19206
19207    #[test]
19208    fn policy_rate_limit_zero_takes_precedence_over_cap() {
19209        // The cross-arm ordering pin: `rate == 0` is structurally
19210        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
19211        // (cap), but the zero-floor diagnostic is the more
19212        // self-locating one (it directly names the omit-axis
19213        // remediation). Pin the order so a future refactor that
19214        // reorders the arms surfaces here as a test failure rather
19215        // than a silent diagnostic regression. Same shape every other
19216        // zero-then-cap ordering on this surface uses
19217        // ([`AplicacaoError::PolicyRetriesZero`] then
19218        // [`AplicacaoError::PolicyRetriesExceedsCap`];
19219        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
19220        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
19221        let mut s = three_member_spec();
19222        s.politicas.rate_limit = Some(RateLimit {
19223            rate: 0,
19224            window: Duration::from_secs(1),
19225        });
19226        assert_eq!(
19227            s.validate().unwrap_err(),
19228            AplicacaoError::PolicyRateLimitZero,
19229            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
19230        );
19231    }
19232
19233    #[test]
19234    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
19235        // Two-axis-bad pin: rate above cap *and* window non-canonical.
19236        // The validate gate must fire on the rate cap first — the
19237        // amplification-shape (no-op limiter) diagnostic is the more
19238        // fundamental one; the window-canonical diagnostic is the
19239        // narrower codec-round-trip shape. Pin the ordering so a future
19240        // refactor that reorders the rate-then-window check arms
19241        // surfaces here as a test failure rather than a silent
19242        // diagnostic regression.
19243        let mut s = three_member_spec();
19244        s.politicas.rate_limit = Some(RateLimit {
19245            rate: POLICY_RATE_LIMIT_MAX + 1,
19246            window: Duration::from_secs(45),
19247        });
19248        assert_eq!(
19249            s.validate().unwrap_err(),
19250            AplicacaoError::PolicyRateLimitExceedsCap {
19251                rate: POLICY_RATE_LIMIT_MAX + 1
19252            },
19253            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
19254        );
19255    }
19256
19257    #[test]
19258    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
19259        // The diagnostic-shape pin: the offending `u32` is carried
19260        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
19261        // variant so the surfaced error message names the value the
19262        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
19263        // the mesh-policy ceiling …"`), not just the cap. Same
19264        // self-locating diagnostic shape every other typed-cap arm on
19265        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
19266        // carries the offending retries count verbatim,
19267        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
19268        // the offending failure count verbatim).
19269        let mut s = three_member_spec();
19270        s.politicas.rate_limit = Some(RateLimit {
19271            rate: 5_000_000,
19272            window: Duration::from_secs(1),
19273        });
19274        let err = s.validate().unwrap_err();
19275        assert!(
19276            matches!(
19277                err,
19278                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
19279            ),
19280            "got {err:?}"
19281        );
19282        let msg = err.to_string();
19283        assert!(
19284            msg.contains("5000000"),
19285            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
19286        );
19287    }
19288
19289    #[test]
19290    fn policy_rate_limit_cap_pins_canonical_value() {
19291        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
19292        // 1_000_000 — two-to-three orders of magnitude above every
19293        // documented production-playbook recommendation band (Envoy /
19294        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
19295        // Gateway 10_000..=100_000 per-minute) and below the
19296        // clearly-pathological "paste-from-binary blob" floor
19297        // (100_000_000, u32::MAX). Pinning the literal value here
19298        // surfaces a future drift (a relaxation to 10_000_000, a
19299        // tightening to 100_000) as a deliberate test edit, not a
19300        // silent contract narrowing.
19301        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
19302    }
19303
19304    #[test]
19305    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
19306        // Both axes are invalid here: rate == 0 *and* window is
19307        // non-canonical. The validate gate must fire on rate first
19308        // (matching the existing `rejects_zero_rate_limit` ordering),
19309        // so the existing diagnostic continues to lead with the
19310        // simpler "zero rate" framing. Pinning the order of checks
19311        // so a future refactor that reorders the arms surfaces here
19312        // as a test failure rather than a silent diagnostic
19313        // regression.
19314        let mut s = three_member_spec();
19315        s.politicas.rate_limit = Some(RateLimit {
19316            rate: 0,
19317            window: Duration::from_secs(45),
19318        });
19319        assert_eq!(
19320            s.validate().unwrap_err(),
19321            AplicacaoError::PolicyRateLimitZero
19322        );
19323    }
19324
19325    #[test]
19326    fn rate_limit_canonical_windows_validate() {
19327        // The three canonical windows the codec round-trips
19328        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
19329        // unchanged. Pin the full canonical set as a positive case
19330        // (the existing `rate_limit_round_trip_seconds` /
19331        // `rate_limit_round_trip_minutes` tests pin the
19332        // serialize-then-deserialize property at the codec layer; this
19333        // test pins the validate-side complement so a future tightening
19334        // of the canonical set — e.g. dropping `:hour` — surfaces here
19335        // as a test failure rather than a silent contract narrowing).
19336        for secs in [1u64, 60, 3600] {
19337            let mut s = three_member_spec();
19338            s.politicas.rate_limit = Some(RateLimit {
19339                rate: 100,
19340                window: Duration::from_secs(secs),
19341            });
19342            s.validate().expect("canonical window must validate");
19343        }
19344    }
19345
19346    #[test]
19347    fn rate_limit_validated_value_round_trips_through_codec() {
19348        // The structural property the validate gate enforces:
19349        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
19350        // losslessly through the `rate_limit_codec` (serialize → string
19351        // → deserialize → equal value). Pin this end-to-end so a future
19352        // change to either side (the validate gate's accepted window
19353        // set, the codec's parse/render unit set) that breaks the
19354        // alignment surfaces here. The previous-state shape (typed
19355        // slot accepts arbitrary `Duration`, codec only round-trips
19356        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
19357        // window — the validate gate now forecloses that.
19358        for secs in [1u64, 60, 3600] {
19359            let mut s = three_member_spec();
19360            s.politicas.rate_limit = Some(RateLimit {
19361                rate: 250,
19362                window: Duration::from_secs(secs),
19363            });
19364            s.validate().unwrap();
19365            let json = serde_json::to_string(&s.politicas).unwrap();
19366            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19367            assert_eq!(
19368                back.rate_limit, s.politicas.rate_limit,
19369                "every validated :rate-limit must round-trip losslessly through the codec"
19370            );
19371        }
19372    }
19373
19374    #[test]
19375    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
19376        // The hour-window canonical form (`"<n>/h"`) was missing from
19377        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
19378        // pair. Now that the validate gate pins 3600s as part of the
19379        // canonical set, pin its serialize-side render shape too so
19380        // the third leg of the s/m/h tripod is explicitly tested.
19381        let policy = MeshPolicy {
19382            rate_limit: Some(RateLimit {
19383                rate: 10000,
19384                window: Duration::from_secs(3600),
19385            }),
19386            ..Default::default()
19387        };
19388        let json = serde_json::to_string(&policy).unwrap();
19389        assert!(
19390            json.contains("\"10000/h\""),
19391            "hour-window canonical form must render with `h` suffix (got: {json})"
19392        );
19393        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19394        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
19395    }
19396
19397    #[test]
19398    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
19399        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
19400        // typed accessor's accepted-window set against the codec's
19401        // accepted set explicitly. A future addition to the codec
19402        // (e.g. accepting `:day`/`:week` as authoring units) must be
19403        // accompanied by a parallel addition here, and a regression
19404        // that drops one of the three canonical units from either
19405        // side surfaces as a test failure. The accessor is the
19406        // single source of truth for the canonical-window set —
19407        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
19408        // gate and [`rate_limit_codec::render`]'s canonical arm both
19409        // read through it — this test enshrines that its
19410        // `Duration → Option<RateLimitUnit>` projection matches the
19411        // codec's parse / render arms' accepted-window set exactly.
19412        //
19413        // Predecessor: this pin previously read the module-private
19414        // free helper `is_canonical_rate_limit_window` — a delegate
19415        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
19416        // — but the helper had no production consumers left after the
19417        // validate-gate migration onto [`RateLimit::canonical_unit`]
19418        // and was deleted; the closed-set arm-window bijection now
19419        // lives on exactly one typed dispatch on the substrate
19420        // primitive.
19421        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
19422            RateLimit { rate: 1, window }.canonical_unit()
19423        };
19424        assert!(canonical_unit(Duration::from_secs(1)).is_some());
19425        assert!(canonical_unit(Duration::from_secs(60)).is_some());
19426        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
19427        // Non-canonical windows the accessor rejects.
19428        assert!(canonical_unit(Duration::ZERO).is_none());
19429        assert!(canonical_unit(Duration::from_secs(2)).is_none());
19430        assert!(canonical_unit(Duration::from_secs(30)).is_none());
19431        assert!(canonical_unit(Duration::from_secs(120)).is_none());
19432        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
19433        // Sub-second windows: even `Duration::from_millis(1000)` is
19434        // exactly 1s and accepted; `Duration::from_millis(500)` is
19435        // sub-second and rejected.
19436        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
19437        assert!(canonical_unit(Duration::from_millis(500)).is_none());
19438        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
19439    }
19440
19441    #[test]
19442    fn rate_limit_unit_table_projections_are_mutual_inverses() {
19443        // Bidirection pin against the closed-set typed enum
19444        // [`RateLimitUnit`] arm-table (the canonical
19445        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
19446        // of the rate-limit unit surface reads from). The two
19447        // projection directions [`RateLimitUnit::from_suffix`] /
19448        // [`RateLimitUnit::window`] (str → Duration, exposed as one
19449        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
19450        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
19451        // (Duration → str, exposed as one typed dispatch through
19452        // [`RateLimit::canonical_unit`] composed with
19453        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
19454        // codec's parse arm ([`rate_limit_codec::parse`] via
19455        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
19456        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
19457        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
19458        // via [`RateLimit::canonical_unit`]) all key off. A future
19459        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
19460        // sub-second window) is one variant + one arm per method on the
19461        // closed-set enum; the compiler-enforced exhaustiveness on
19462        // every consumer's `match self` arms picks it up by
19463        // construction. This pin enshrines that both projection
19464        // directions agree on every canonical arm row and neither
19465        // leaks a spurious entry the other doesn't recognize.
19466        //
19467        // Predecessor: this test previously read the two vestigial
19468        // module-private free helpers `rate_limit_window_unit` and
19469        // `rate_limit_window_from_unit` on the `Duration → &str` and
19470        // `&str → Duration` axes; the former was deleted after its
19471        // sole production consumer ([`rate_limit_codec::render`])
19472        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
19473        // the latter is folded here into the substrate primitive
19474        // [`RateLimitUnit::window_from_suffix`] so both projection
19475        // directions live on the closed-set enum's arm-table.
19476        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
19477            let window = super::RateLimitUnit::window_from_suffix(unit)
19478                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
19479            assert_eq!(
19480                window,
19481                Duration::from_secs(secs),
19482                "unit {unit:?} must resolve to {secs}s"
19483            );
19484            let projected_suffix = RateLimit { rate: 1, window }
19485                .canonical_unit()
19486                .map(super::RateLimitUnit::as_suffix);
19487            assert_eq!(
19488                projected_suffix,
19489                Some(unit),
19490                "Duration({secs}s) must render as {unit:?} \
19491                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
19492            );
19493        }
19494        // Non-table units yield None on the `unit → Duration`
19495        // projection — a future `"d"` addition to the table would
19496        // flip this arm; today it pins the current three-row table's
19497        // rejection semantics.
19498        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
19499        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
19500        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
19501        // Non-table Durations yield None on the `Duration → unit`
19502        // projection — pins that the two projections agree on the
19503        // "not in the table" semantic too, so a drift where the
19504        // parse-side accepts a value the render-side can't emit is
19505        // a build error at the two-arm pair, not a silent codec
19506        // round-trip break.
19507        let projected_suffix = |window: Duration| -> Option<&'static str> {
19508            RateLimit { rate: 1, window }
19509                .canonical_unit()
19510                .map(super::RateLimitUnit::as_suffix)
19511        };
19512        assert!(projected_suffix(Duration::from_secs(2)).is_none());
19513        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
19514        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
19515    }
19516
19517    #[test]
19518    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
19519        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
19520        // substrate-primitive `&str → Duration` associated method the
19521        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
19522        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
19523        // to the same [`Duration`] the two-step composition
19524        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
19525        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
19526        // `"MIN"`) must project to [`None`] on both paths. A future
19527        // implementation of `window_from_suffix` that took a shortcut
19528        // through a per-suffix `match` table (bypassing the arm-table's
19529        // `Self::from_suffix` scan and the arm-table's `Self::window`
19530        // dispatch) would silently split the accept-set — the parse
19531        // arm would accept a suffix the enum's arm-table doesn't know,
19532        // or reject a suffix the enum's arm-table does; this pin
19533        // surfaces that drift at caixa-core build time rather than at a
19534        // downstream serde round-trip audit on a live `MeshPolicy`.
19535        //
19536        // Same byte-parity discipline the sibling
19537        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
19538        // pin carries on the peer `Duration → RateLimitUnit` axis via
19539        // [`RateLimit::canonical_unit`], and the peer
19540        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
19541        // carries on the bidirectional arm-table axis — extended here
19542        // onto the fifth (and last unlifted) projection axis on the
19543        // closed-set enum's arm-table.
19544        let composition = |suffix: &str| -> Option<Duration> {
19545            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
19546        };
19547        for suffix in ["s", "m", "h"] {
19548            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
19549            let via_composition = composition(suffix);
19550            assert_eq!(
19551                via_method, via_composition,
19552                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
19553                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
19554                 method must delegate to the arm-table's two typed dispatches, \
19555                 not shortcut through a per-suffix match table"
19556            );
19557            assert!(
19558                via_method.is_some(),
19559                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
19560                 RateLimitUnit::window_from_suffix"
19561            );
19562        }
19563        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
19564            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
19565            let via_composition = composition(suffix);
19566            assert_eq!(
19567                via_method, via_composition,
19568                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
19569                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
19570                 axis too"
19571            );
19572            assert!(
19573                via_method.is_none(),
19574                "non-arm suffix {suffix:?} must project to None via \
19575                 RateLimitUnit::window_from_suffix — a future extension that \
19576                 accepted this suffix without a corresponding arm on the enum \
19577                 would split the codec's parse-accepted set from the enum's \
19578                 arm-table"
19579            );
19580        }
19581        // And the codec's parse arm now reads through this method: a
19582        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
19583        // the same `Duration` the method returns for its unit, closing
19584        // the two-consumer drift surface (the codec's parse arm and the
19585        // enum's arm-table) with one typed dispatch on the substrate
19586        // primitive.
19587        for suffix in ["s", "m", "h"] {
19588            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
19589            let mp: MeshPolicy = serde_json::from_str(&wire)
19590                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
19591            let parsed = mp.rate_limit().expect("rate_limit payload present");
19592            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
19593                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
19594            assert_eq!(
19595                parsed.window(),
19596                via_method,
19597                "codec parse arm on {wire:?} must resolve the window through \
19598                 RateLimitUnit::window_from_suffix, not a divergent path"
19599            );
19600        }
19601    }
19602
19603    #[test]
19604    fn rate_limit_unit_all_enumerates_every_arm_once() {
19605        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
19606        // enumerate every arm of the closed-set enum exactly once, in
19607        // the canonical shortest-to-longest window order (Second before
19608        // Minute before Hour) — the same order the sibling
19609        // [`crate::supervisor::RestartStrategy`] /
19610        // [`crate::supervisor::RestartPolicy`] /
19611        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
19612        // typed enums carry (the arm declared first is the arm listed
19613        // first). A future variant addition that extends the enum
19614        // without appending to [`RateLimitUnit::ALL`] leaves the
19615        // exhaustive iteration surface silently short one arm — the
19616        // codec's parse arm would then reject the new suffix even
19617        // though the enum knows it. This pin closes the drift.
19618        assert_eq!(
19619            super::RateLimitUnit::ALL,
19620            &[
19621                super::RateLimitUnit::Second,
19622                super::RateLimitUnit::Minute,
19623                super::RateLimitUnit::Hour,
19624            ],
19625            "RateLimitUnit::ALL must enumerate every arm exactly once, \
19626             in canonical shortest-to-longest window order"
19627        );
19628    }
19629
19630    #[test]
19631    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
19632        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
19633        // every arm's [`RateLimitUnit::as_suffix`] output must parse
19634        // back through [`RateLimitUnit::from_suffix`] to the same
19635        // variant. A future arm addition that lands `as_suffix` but
19636        // forgets `from_suffix` (`from_suffix` iterates
19637        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
19638        // is the load-bearing carrier of the round-trip; the sibling
19639        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
19640        // the `ALL` half) trips here at caixa-core build time rather
19641        // than surfacing as a codec round-trip miss (a `render` emit
19642        // that lands a suffix the paired `parse` cannot decode).
19643        for unit in super::RateLimitUnit::ALL {
19644            let suffix = unit.as_suffix();
19645            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
19646                panic!(
19647                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
19648                     RateLimitUnit::as_suffix output — got None for {unit:?}"
19649                )
19650            });
19651            assert_eq!(
19652                parsed, *unit,
19653                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
19654                 must return RateLimitUnit::{unit:?}"
19655            );
19656        }
19657    }
19658
19659    #[test]
19660    fn rate_limit_unit_from_window_and_window_round_trip() {
19661        // Total round-trip pin on the `(from_window, window)` pair:
19662        // every arm's [`RateLimitUnit::window`] output must parse back
19663        // through [`RateLimitUnit::from_window`] to the same variant.
19664        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
19665        // on the peer `Duration` axis — the two round-trip pins
19666        // together enshrine that both projections of the typed
19667        // canonical-unit bijection are total on the arm-set.
19668        for unit in super::RateLimitUnit::ALL {
19669            let window = unit.window();
19670            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
19671                panic!(
19672                    "RateLimitUnit::from_window({window:?}) must accept every \
19673                     RateLimitUnit::window output — got None for {unit:?}"
19674                )
19675            });
19676            assert_eq!(
19677                parsed, *unit,
19678                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
19679                 must return RateLimitUnit::{unit:?}"
19680            );
19681        }
19682    }
19683
19684    #[test]
19685    fn rate_limit_unit_from_window_accessor_is_const_fn() {
19686        // Fail-before-pass-after pin: witnesses the
19687        // [`RateLimitUnit::from_window`] `const`-eval posture via a
19688        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
19689        // -> Option<RateLimitUnit>` whose body calls
19690        // `RateLimitUnit::from_window(window)`, well-formed only when
19691        // the callee is itself `const fn` (any future downgrade to
19692        // non-`const` fails at caixa-core build time with E0015 `cannot
19693        // call non-const function`, strictly stronger than a runtime
19694        // `assert!`, side-stepping the destructor-in-const restriction
19695        // that blocks direct `const _: Option<RateLimitUnit> =
19696        // RateLimitUnit::from_window(...)` items on `Duration`'s
19697        // carrier). The runtime body sweeps every closed-set
19698        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
19699        // rejection sample (`Duration::from_millis(500)` sub-second
19700        // residue) and asserts the wrapped and direct dispatches agree
19701        // — a violation means the wrapper stopped compiling under a
19702        // future `const`-posture downgrade, or the reverse resolver's
19703        // arm-set silently split from the peer `Self::window` emitter's
19704        // arm-set. Peer of the sibling
19705        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
19706        // (152c868) /
19707        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
19708        // (152c868) /
19709        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
19710        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
19711        // `const`-eval-surface pins on the peer M2 / M3 substrate-
19712        // primitive `Copy`-return accessor axes, extended onto the
19713        // reverse `Duration → RateLimitUnit` projection axis on the
19714        // M3 mesh-slot rate-limit closed-set typed enum.
19715        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
19716            super::RateLimitUnit::from_window(window)
19717        }
19718        for unit in super::RateLimitUnit::ALL {
19719            let window = unit.window();
19720            let via_wrapper = from_window_via_const_fn(window);
19721            let direct = super::RateLimitUnit::from_window(window);
19722            assert_eq!(
19723                via_wrapper, direct,
19724                "RateLimitUnit::from_window({window:?}) via const fn \
19725                 wrapper must agree with direct dispatch for {unit:?}"
19726            );
19727            assert_eq!(
19728                via_wrapper,
19729                Some(*unit),
19730                "RateLimitUnit::from_window({window:?}) via const fn \
19731                 wrapper must return Some({unit:?}) for the peer \
19732                 window() output"
19733            );
19734        }
19735        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
19736        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
19737    }
19738
19739    #[test]
19740    fn rate_limit_unit_from_window_composes_through_window_accessor() {
19741        // Composition-witness pin on the routing-through-peer discipline:
19742        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
19743        // through the peer `pub const fn` [`RateLimitUnit::window`]
19744        // canonical-`Duration` projection rather than a hand-authored
19745        // per-arm second-magnitude literal — a future arm-magnitude edit
19746        // on the sibling `window()` accessor (a `Second → 2s` typo, a
19747        // `Hour → 3599s` off-by-one) must therefore reach this reverse
19748        // resolver by construction. A pin that hard-coded the three
19749        // second-magnitudes here would silently split from the peer
19750        // emitter on any such edit; instead, this pin asserts the
19751        // composition invariant `from_window(u.window()) == Some(u)`
19752        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
19753        // arm — a violation means either the peer `Self::window`
19754        // accessor drifted (breaking every downstream consumer that
19755        // reads through it), or the reverse resolver stopped routing
19756        // through the peer (introducing a hand-authored literal that
19757        // silently disagrees with the emitter). Either failure is a
19758        // caixa-core-build-time surface, not a downstream renderer
19759        // round-trip regression.
19760        //
19761        // Peer of the sibling
19762        // [`crate::render::assert_str_reexport_identity`] discipline on
19763        // the substrate-primitive `&'static str` re-export axis and the
19764        // [`rate_limit_unit_from_window_and_window_round_trip`]
19765        // round-trip pin on the peer projection direction; extends the
19766        // one-canonical-dispatch-per-projection discipline onto the
19767        // reverse-resolver's per-arm probe axis.
19768        for unit in super::RateLimitUnit::ALL {
19769            let window_via_peer = unit.window();
19770            let resolved = super::RateLimitUnit::from_window(window_via_peer);
19771            assert_eq!(
19772                resolved,
19773                Some(*unit),
19774                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
19775                 must return Some({unit:?}) — the reverse resolver's per-arm \
19776                 probes must route through the peer `Self::window` accessor \
19777                 so any future arm-magnitude edit reaches both projection \
19778                 directions by construction"
19779            );
19780        }
19781    }
19782
19783    #[test]
19784    fn rate_limit_canonical_unit_accessor_is_const_fn() {
19785        // Fail-before-pass-after pin: witnesses the
19786        // [`RateLimit::canonical_unit`] `const`-eval posture via a
19787        // `const fn` wrapper
19788        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
19789        // whose body calls `rl.canonical_unit()`, well-formed only when
19790        // the callee is itself `const fn` (any future downgrade to
19791        // non-`const` fails at caixa-core build time with E0015 `cannot
19792        // call non-const method`). The runtime body sweeps every
19793        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
19794        // constructs a typed [`RateLimit`] with the peer `Self::window`
19795        // canonical `Duration`, then asserts both the wrapper and the
19796        // direct dispatch agree and both return `Some(unit)`. Composes
19797        // with the sibling
19798        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
19799        // typed [`RateLimit`] projection layer's `const`-posture is
19800        // load-bearing on the reverse resolver's `const`-posture, and
19801        // both must migrate together (a downgrade of either surface
19802        // splits the paired `const`-eval-surface pass on the M3
19803        // mesh-slot rate-limit `Duration ↔ Self` bijection).
19804        const fn canonical_unit_via_const_fn(
19805            rl: &super::RateLimit,
19806        ) -> Option<super::RateLimitUnit> {
19807            rl.canonical_unit()
19808        }
19809        for unit in super::RateLimitUnit::ALL {
19810            let rl = super::RateLimit {
19811                rate: 1,
19812                window: unit.window(),
19813            };
19814            let via_wrapper = canonical_unit_via_const_fn(&rl);
19815            let direct = rl.canonical_unit();
19816            assert_eq!(
19817                via_wrapper, direct,
19818                "RateLimit::canonical_unit() via const fn wrapper must \
19819                 agree with direct dispatch for {unit:?}"
19820            );
19821            assert_eq!(
19822                via_wrapper,
19823                Some(*unit),
19824                "RateLimit::canonical_unit() via const fn wrapper must \
19825                 return Some({unit:?}) for a RateLimit whose window is \
19826                 the peer RateLimitUnit::{unit:?}.window() output"
19827            );
19828        }
19829    }
19830
19831    #[test]
19832    fn rate_limit_unit_projections_are_pairwise_distinct() {
19833        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
19834        // [`RateLimitUnit::window`] outputs must be pairwise distinct
19835        // across every arm — an accidental copy-paste flip that
19836        // reroutes one arm's suffix or window to also match another
19837        // silently collapses two arms onto one, so
19838        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
19839        // (both using `find` on `Self::ALL`) would return whichever
19840        // arm the linear scan lands on first — a match-arm-ordering-
19841        // dependent outcome the closed-set typed-enum shape is meant
19842        // to rule out structurally. Peer of the sibling
19843        // `caixa_kind_wire_consts_are_pairwise_distinct` /
19844        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
19845        // other closed-set typed-enum discriminator axes.
19846        let all = super::RateLimitUnit::ALL;
19847        for (i, a) in all.iter().enumerate() {
19848            for (j, b) in all.iter().enumerate() {
19849                if i != j {
19850                    assert_ne!(
19851                        a.as_suffix(),
19852                        b.as_suffix(),
19853                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
19854                         must be distinct — a collision silently collapses two \
19855                         arms onto one under from_suffix's linear scan"
19856                    );
19857                    assert_ne!(
19858                        a.window(),
19859                        b.window(),
19860                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
19861                         must be distinct — a collision silently collapses two \
19862                         arms onto one under from_window's linear scan"
19863                    );
19864                }
19865            }
19866        }
19867    }
19868
19869    #[test]
19870    fn rate_limit_unit_display_routes_through_as_suffix() {
19871        // Route pin: [`std::fmt::Display`] must byte-equal
19872        // [`RateLimitUnit::as_suffix`] on every arm — the single
19873        // source of truth for the canonical suffix. A future
19874        // reimplementation that hand-rolls the arms instead of
19875        // delegating to [`RateLimitUnit::as_suffix`] would silently
19876        // desynchronize `format!("{u}")` from the codec's parse arm
19877        // (which uses `as_suffix` to compare suffixes). Peer of the
19878        // sibling `caixa_kind_display_routes_through_as_str_helper` /
19879        // `placement_strategy_display_routes_through_as_str_helper`
19880        // pins on the peer closed-set typed-enum Display axes.
19881        for unit in super::RateLimitUnit::ALL {
19882            assert_eq!(
19883                unit.to_string(),
19884                unit.as_suffix(),
19885                "RateLimitUnit::{unit:?} Display must route through \
19886                 as_suffix (single source of truth: the canonical suffix \
19887                 the codec parses and renders)"
19888            );
19889        }
19890    }
19891
19892    #[test]
19893    fn rate_limit_unit_from_window_rejects_non_canonical() {
19894        // Rejection pin on the parser's accept-set: any Duration
19895        // outside the three-arm [`RateLimitUnit::window`] output set
19896        // (sub-second residue, or a second-magnitude outside `{1, 60,
19897        // 3600}`) must return `None`. A future accidental widening of
19898        // the accept-set (rounding down sub-second residue to the
19899        // nearest arm, admitting `Duration::from_secs(30)` as a
19900        // half-minute unit) would silently drift the parser's accept-
19901        // set from the emitter's — a validated slot with a
19902        // non-canonical window would then round-trip through the
19903        // codec to a canonical form the author never wrote.
19904        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
19905        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
19906        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
19907        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
19908        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
19909        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
19910        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
19911    }
19912
19913    #[test]
19914    fn rate_limit_unit_from_suffix_rejects_unknown() {
19915        // Rejection pin on the suffix parser's accept-set: any string
19916        // outside the three-arm [`RateLimitUnit::as_suffix`] output
19917        // set must return `None`. Peer of the sibling
19918        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
19919        // the [`crate::CaixaKind`] `from_wire` accept-set.
19920        for bad in [
19921            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
19922            " s",
19923        ] {
19924            assert!(
19925                super::RateLimitUnit::from_suffix(bad).is_none(),
19926                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
19927                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
19928                 outputs"
19929            );
19930        }
19931    }
19932
19933    #[test]
19934    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
19935        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
19936        // every canonical `:window` magnitude the validate gate
19937        // accepts must map to the paired [`RateLimitUnit`] arm through
19938        // this accessor. A future validate-gate rebrand that widened
19939        // the accepted-window set without extending [`RateLimitUnit`]
19940        // would silently split the accessor's `Some`-return set from
19941        // the validate gate's accept-set — a slot that satisfies
19942        // validate would land at the accessor with `None`, so a
19943        // consumer past validate that pattern-matches on the returned
19944        // `Some` would silently miss the newly-accepted magnitude.
19945        for (window_secs, expected) in [
19946            (1u64, super::RateLimitUnit::Second),
19947            (60, super::RateLimitUnit::Minute),
19948            (3600, super::RateLimitUnit::Hour),
19949        ] {
19950            let rl = RateLimit {
19951                rate: 100,
19952                window: Duration::from_secs(window_secs),
19953            };
19954            assert_eq!(
19955                rl.canonical_unit(),
19956                Some(expected),
19957                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
19958                 must return Some({expected:?})"
19959            );
19960        }
19961        // Non-canonical windows the validate gate rejects also return
19962        // None here — the accessor is the typed-enum projection of
19963        // the sibling `is_canonical_rate_limit_window` predicate.
19964        let bad = RateLimit {
19965            rate: 100,
19966            window: Duration::from_secs(30),
19967        };
19968        assert!(
19969            bad.canonical_unit().is_none(),
19970            "RateLimit with a non-canonical window must return None from \
19971             canonical_unit — the validate gate rejects the same set"
19972        );
19973    }
19974
19975    #[test]
19976    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
19977        // Fail-before-pass-after byte-parity pin: for every canonical
19978        // window the [`rate_limit_codec::render`] arm's emitted string
19979        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
19980        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
19981        // the vestigial free helper [`rate_limit_window_unit`] (a
19982        // `find_map`-walked `Duration → &'static str` delegate) onto the
19983        // substrate primitive [`RateLimit::canonical_unit`] typed method
19984        // (a closed-set `match self.window` arm on
19985        // [`RateLimitUnit::from_window`], projected through
19986        // [`RateLimitUnit::as_suffix`] via the enum's
19987        // [`std::fmt::Display`] impl). A future re-routing of the render
19988        // arm through a differently-computed unit projection would break
19989        // this pin at build time rather than as a silent per-consumer
19990        // codec round-trip drift far from the substrate primitive edit.
19991        //
19992        // Sibling to the peer
19993        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
19994        // on the free-helper axis: that pin locks the two projections
19995        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
19996        // on the closed-set arm table; this pin locks the codec's render
19997        // arm reads through the typed accessor rather than the free
19998        // helper. Two production consumers of the canonical-unit axis
19999        // now key off one typed dispatch on the substrate primitive.
20000        for (window_secs, unit) in [
20001            (1u64, super::RateLimitUnit::Second),
20002            (60, super::RateLimitUnit::Minute),
20003            (3600, super::RateLimitUnit::Hour),
20004        ] {
20005            let rl = RateLimit {
20006                rate: 42,
20007                window: Duration::from_secs(window_secs),
20008            };
20009            let policy = MeshPolicy {
20010                rate_limit: Some(rl),
20011                ..Default::default()
20012            };
20013            let json = serde_json::to_string(&policy).unwrap();
20014            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
20015            assert!(
20016                json.contains(&expected),
20017                "rate_limit_codec::render must emit {expected} (via \
20018                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
20019                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
20020            );
20021            // And the accessor route resolves to the same typed unit
20022            // the render arm's Display formatting is asked to produce —
20023            // so a future edit that split the two paths (one through
20024            // the accessor, one through a re-introduced free helper)
20025            // trips this pin.
20026            assert_eq!(
20027                rl.canonical_unit(),
20028                Some(unit),
20029                "RateLimit::canonical_unit must return Some({unit:?}) for a \
20030                 {window_secs}s window; the codec render arm reads the same \
20031                 typed unit through this accessor"
20032            );
20033        }
20034    }
20035
20036    #[test]
20037    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
20038        // Fail-before-pass-after byte-parity pin on the validate gate's
20039        // canonical-window shape probe: every non-canonical `:window`
20040        // the free-helper predicate [`is_canonical_rate_limit_window`]
20041        // rejects is also rejected by the substrate primitive
20042        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
20043        // gate now reads through, and vice versa on the accepted set
20044        // (the three canonical windows). Locks the migration from the
20045        // free helper onto the substrate primitive: a future re-routing
20046        // of one of the two paths through a differently-computed unit
20047        // projection would silently split the codec's accepted set from
20048        // the validate gate's accepted set — a two-consumer drift the
20049        // codec-round-trip pin
20050        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
20051        // above closes on the render arm and this pin closes on the
20052        // validate arm.
20053        for canonical_window_secs in [1u64, 60, 3600] {
20054            let mut s = three_member_spec();
20055            let rl = RateLimit {
20056                rate: 100,
20057                window: Duration::from_secs(canonical_window_secs),
20058            };
20059            s.politicas.rate_limit = Some(rl);
20060            assert!(
20061                s.validate().is_ok(),
20062                "canonical {canonical_window_secs}s window must pass \
20063                 validate_politicas — the validate gate now reads \
20064                 RateLimit::canonical_unit().is_none() and the accessor \
20065                 returns Some on every canonical arm"
20066            );
20067            assert!(
20068                rl.canonical_unit().is_some(),
20069                "canonical {canonical_window_secs}s window must resolve to \
20070                 Some on RateLimit::canonical_unit — the validate gate reads \
20071                 this accessor directly"
20072            );
20073        }
20074        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
20075            let mut s = three_member_spec();
20076            let rl = RateLimit {
20077                rate: 100,
20078                window: Duration::from_secs(non_canonical_window_secs),
20079            };
20080            s.politicas.rate_limit = Some(rl);
20081            assert_eq!(
20082                s.validate().unwrap_err(),
20083                AplicacaoError::PolicyRateLimitWindowNotCanonical {
20084                    window: rl.window(),
20085                },
20086                "non-canonical {non_canonical_window_secs}s window must be \
20087                 rejected by validate_politicas — the validate gate now \
20088                 keys off RateLimit::canonical_unit().is_none()"
20089            );
20090            assert!(
20091                rl.canonical_unit().is_none(),
20092                "non-canonical {non_canonical_window_secs}s window must \
20093                 resolve to None on RateLimit::canonical_unit — the two \
20094                 paths (the free helper the validate gate previously read \
20095                 and the substrate primitive the validate gate now reads) \
20096                 must agree on the same rejected set"
20097            );
20098        }
20099        // And the substrate-primitive [`RateLimit::canonical_unit`]
20100        // accessor's accepted-window set matches the codec's parse arm's
20101        // accepted-suffix set on every canonical / non-canonical shape,
20102        // so a future silent drift between the codec's accepted set and
20103        // the validate gate's accepted set is a build error at test time
20104        // (both consumers key off the same closed-set enum's `match self`
20105        // arms). The predecessor free helper `is_canonical_rate_limit_window`
20106        // — a delegate that composed [`RateLimitUnit::from_window`] with
20107        // `.is_some()` — was deleted after this migration; the
20108        // canonical-window set now lives on exactly one typed dispatch
20109        // on the substrate primitive.
20110        for (secs, expected) in [
20111            (1u64, true),
20112            (60, true),
20113            (3600, true),
20114            (2, false),
20115            (30, false),
20116            (86_400, false),
20117        ] {
20118            let window = Duration::from_secs(secs);
20119            let rl = RateLimit { rate: 1, window };
20120            assert_eq!(
20121                rl.canonical_unit().is_some(),
20122                expected,
20123                "RateLimit::canonical_unit().is_some() must agree with the \
20124                 codec-accepted canonical-window set on {secs}s"
20125            );
20126            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
20127                1 => "s",
20128                60 => "m",
20129                3600 => "h",
20130                _ => return,
20131            })
20132            .is_some_and(|d| d == window);
20133            if expected {
20134                assert!(
20135                    suffix_from_axis,
20136                    "the codec's `&str → Duration` axis \
20137                     ({secs}s) must round-trip to the same Duration the \
20138                     substrate primitive's accessor returns Some on"
20139                );
20140            }
20141        }
20142    }
20143
20144    #[test]
20145    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
20146        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
20147        // derive: for each of the three variants, exactly one of the
20148        // generated `is_second` / `is_minute` / `is_hour` predicates
20149        // returns `true` and the other two return `false`. Peer of
20150        // the sibling
20151        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
20152        // sibling `IsVariant`-derived closed-set typed-enum pins.
20153        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
20154            (super::RateLimitUnit::Second, [true, false, false]),
20155            (super::RateLimitUnit::Minute, [false, true, false]),
20156            (super::RateLimitUnit::Hour, [false, false, true]),
20157        ];
20158        for (variant, expected) in rows {
20159            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
20160            assert_eq!(
20161                observed, expected,
20162                "RateLimitUnit::{variant:?} is_* predicates must partition \
20163                 the arm set (second, minute, hour); got {observed:?}"
20164            );
20165        }
20166    }
20167
20168    #[test]
20169    fn rejects_policy_timeout_sub_millisecond() {
20170        // A purely sub-millisecond `Duration` (`from_micros(500)` =
20171        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
20172        // arm passes — but `as_millis() == 0`, so the shared codec's
20173        // `render` arm returns the literal `"0s"`, which the
20174        // codec's `parse` arm then deserializes as `Duration::ZERO`
20175        // and the `PolicyTimeoutZero` zero-floor gate would reject
20176        // on re-validate. Pin the rejection at the typed slot's
20177        // canonical-floor gate so the round-trip break surfaces at
20178        // validate time, naming the offending `Duration`, rather
20179        // than at the next serialize → deserialize round-trip far
20180        // from the source `caixa.lisp`.
20181        let mut s = three_member_spec();
20182        let timeout = Duration::from_micros(500);
20183        s.politicas.timeout = Some(timeout);
20184        assert_eq!(
20185            s.validate().unwrap_err(),
20186            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
20187        );
20188    }
20189
20190    #[test]
20191    fn rejects_policy_timeout_non_integer_millisecond() {
20192        // A `Duration` with non-integer-millisecond residue
20193        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
20194        // through the shared codec's `render` arm as `"1ms"` (the
20195        // `as_millis()` floor truncates), which the codec's `parse`
20196        // arm then deserializes as `Duration::from_millis(1)` =
20197        // 1_000_000 ns — silently *different* from the original.
20198        // Pin the rejection so this round-trip break surfaces at
20199        // validate time, where the offending `Duration` is named,
20200        // rather than as a silent value-laundered round-trip on the
20201        // next codec round-trip.
20202        let mut s = three_member_spec();
20203        let timeout = Duration::from_micros(1500);
20204        s.politicas.timeout = Some(timeout);
20205        assert_eq!(
20206            s.validate().unwrap_err(),
20207            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
20208        );
20209    }
20210
20211    #[test]
20212    fn accepts_policy_timeout_integer_millisecond_forms() {
20213        // The codec's accepted set — integer multiples of 1ms — is
20214        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
20215        // `1h` all pass the canonical gate. Pin the canonical-forms
20216        // sweep so a future tightening of the codec's grammar (e.g.
20217        // dropping `:ms`) surfaces here as a test failure rather
20218        // than a silent contract narrowing on the typed slot.
20219        for timeout in [
20220            Duration::from_millis(1),
20221            Duration::from_millis(500),
20222            Duration::from_millis(1500),
20223            Duration::from_secs(30),
20224            Duration::from_secs(120),
20225            Duration::from_secs(3600),
20226        ] {
20227            let mut s = three_member_spec();
20228            s.politicas.timeout = Some(timeout);
20229            s.validate()
20230                .expect("integer-millisecond :timeout must validate");
20231        }
20232    }
20233
20234    #[test]
20235    fn policy_timeout_zero_takes_precedence_over_canonical() {
20236        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
20237        // pass the canonical-millisecond gate; the more self-locating
20238        // `PolicyTimeoutZero` arm (which names the omit-axis
20239        // remediation directly) must fire first. Pin the ordering so
20240        // a future refactor that reorders the arms surfaces here as a
20241        // test failure rather than a silent diagnostic regression.
20242        let mut s = three_member_spec();
20243        s.politicas.timeout = Some(Duration::ZERO);
20244        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
20245    }
20246
20247    #[test]
20248    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
20249        // The diagnostic envelope carries the offending `Duration`
20250        // verbatim so the author can grep their `caixa.lisp` for
20251        // `:timeout "<value>"` and fix it in one edit. Same
20252        // diagnostic shape every other typed-slot canonical-form
20253        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
20254        // peer `:rate-limit :window` axis.
20255        let mut s = three_member_spec();
20256        let timeout = Duration::from_nanos(1_000_001);
20257        s.politicas.timeout = Some(timeout);
20258        match s.validate().unwrap_err() {
20259            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
20260                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
20261            }
20262            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
20263        }
20264    }
20265
20266    #[test]
20267    fn rejects_policy_timeout_above_cap() {
20268        // The fail-before-pass-after pin: 3601s = 1h + 1s is
20269        // structurally one canonical-tick past the
20270        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
20271        // integer-millisecond magnitude the canonical-form arm above
20272        // accepts cleanly, that the codec round-trips losslessly as
20273        // `"3601s"`, and that silently passed validate on every
20274        // pre-gate codebase because the typed slot's only checks were
20275        // the zero-floor and canonical-form arms. The mesh-level
20276        // deadline degenerates only at the runtime substrate (Envoy
20277        // / Cilium L7 timeout overlay) far from the source
20278        // `caixa.lisp` with no field naming the offending policy.
20279        let mut s = three_member_spec();
20280        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
20281        s.politicas.timeout = Some(timeout);
20282        assert_eq!(
20283            s.validate().unwrap_err(),
20284            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20285        );
20286    }
20287
20288    #[test]
20289    fn rejects_policy_timeout_one_millisecond_above_cap() {
20290        // Boundary case: exactly 1ms past the cap (the granularity
20291        // the canonical-form gate enforces). Catches a future
20292        // "strictly less than" half-measure and pins the diagnostic
20293        // to name the offending `Duration` verbatim. Peer of
20294        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
20295        // boundary pin on the sibling `:limits :memory` top edge.
20296        let mut s = three_member_spec();
20297        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
20298        s.politicas.timeout = Some(timeout);
20299        assert_eq!(
20300            s.validate().unwrap_err(),
20301            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20302        );
20303    }
20304
20305    #[test]
20306    fn rejects_policy_timeout_far_above_cap() {
20307        // The "obvious authoring footgun" case: a `(:timeout "24h")`
20308        // or `(:timeout "86400s")` — values the canonical-form arm
20309        // accepts as integer-millisecond magnitudes, the codec
20310        // round-trips losslessly through serde, but the mesh-level
20311        // policy cannot honor (a 24-hour synchronous-`:contratos`
20312        // deadline is operationally indistinguishable from
20313        // omit-the-axis). Until this gate landed validate accepted
20314        // it. Pin both common above-cap values (24h, 7d) so a future
20315        // relaxation that drops the upper bound surfaces here.
20316        for timeout in [
20317            Duration::from_secs(86_400),    // 24h
20318            Duration::from_secs(604_800),   // 7d
20319            Duration::from_secs(1_000_000), // ~11.5 days
20320        ] {
20321            let mut s = three_member_spec();
20322            s.politicas.timeout = Some(timeout);
20323            assert_eq!(
20324                s.validate().unwrap_err(),
20325                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20326            );
20327        }
20328    }
20329
20330    #[test]
20331    fn accepts_policy_timeout_at_cap() {
20332        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
20333        // must validate. The cap is inclusive on the top edge,
20334        // matching the [`POLICY_RETRIES_MAX`] /
20335        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
20336        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
20337        // sibling capped axes. Pin the boundary explicitly so a
20338        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
20339        // instead of `>`) surfaces here as a test failure rather
20340        // than a silent contract narrowing.
20341        let mut s = three_member_spec();
20342        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
20343        s.validate()
20344            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
20345    }
20346
20347    #[test]
20348    fn accepts_policy_timeout_typical_values() {
20349        // The documented production-playbook band positive-control
20350        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
20351        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
20352        // plus a sweep through the long-running-workflow band
20353        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
20354        // validated set explicitly so a future tightening of the
20355        // ceiling surfaces here as a deliberate test edit, not a
20356        // silent contract narrowing.
20357        for timeout in [
20358            Duration::from_millis(1),
20359            Duration::from_millis(500),
20360            Duration::from_secs(1),
20361            Duration::from_secs(10),
20362            Duration::from_secs(15), // Envoy default
20363            Duration::from_secs(30),
20364            Duration::from_secs(60), // AWS App Mesh typical
20365            Duration::from_secs(300),
20366            Duration::from_secs(900),
20367            Duration::from_secs(1800),
20368            Duration::from_secs(3600), // exactly 1h, the cap
20369        ] {
20370            let mut s = three_member_spec();
20371            s.politicas.timeout = Some(timeout);
20372            s.validate()
20373                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
20374        }
20375    }
20376
20377    #[test]
20378    fn policy_timeout_zero_takes_precedence_over_cap() {
20379        // The cross-arm ordering pin: `Duration::ZERO` is
20380        // structurally outside both `>= 1ms` (zero-floor) and
20381        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
20382        // diagnostic is the more self-locating one (it directly
20383        // names the omit-axis remediation), so the validate gate
20384        // must fire on zero first. Same shape every other
20385        // zero-then-shape ordering on this surface uses
20386        // ([`AplicacaoError::PolicyRetriesZero`] then
20387        // [`AplicacaoError::PolicyRetriesExceedsCap`];
20388        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20389        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20390        let mut s = three_member_spec();
20391        s.politicas.timeout = Some(Duration::ZERO);
20392        assert_eq!(
20393            s.validate().unwrap_err(),
20394            AplicacaoError::PolicyTimeoutZero,
20395            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
20396        );
20397    }
20398
20399    #[test]
20400    fn policy_timeout_canonical_takes_precedence_over_cap() {
20401        // The cross-arm ordering pin: a `Duration` that is *both*
20402        // sub-millisecond (non-canonical-form) and structurally
20403        // above the cap surfaces the canonical-form diagnostic
20404        // first, because the round-trip-shape break is the more
20405        // fundamental issue (the value can't even round-trip
20406        // through the codec, so the cap diagnostic naming
20407        // `1ms..=1h` would be misleading — there's no integer-ms
20408        // form of the offending value). Pin the order so a future
20409        // refactor that reorders the arms surfaces here as a test
20410        // failure rather than a silent diagnostic regression.
20411        let mut s = three_member_spec();
20412        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
20413        // *and* total magnitude above the 1h cap.
20414        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
20415        s.politicas.timeout = Some(timeout);
20416        assert_eq!(
20417            s.validate().unwrap_err(),
20418            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
20419            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
20420        );
20421    }
20422
20423    #[test]
20424    fn policy_timeout_cap_diagnostic_carries_offending_value() {
20425        // The diagnostic-shape pin: the offending `Duration` is
20426        // carried verbatim into the
20427        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
20428        // surfaced error message names the value the author wrote
20429        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
20430        // exceeds the mesh-policy ceiling …"`), not just the cap.
20431        // Same self-locating diagnostic shape every other typed-cap
20432        // arm on this surface carries
20433        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
20434        // offending retry count verbatim).
20435        let mut s = three_member_spec();
20436        let timeout = Duration::from_secs(7200); // 2h
20437        s.politicas.timeout = Some(timeout);
20438        let err = s.validate().unwrap_err();
20439        assert!(
20440            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
20441            "got {err:?}"
20442        );
20443        let msg = err.to_string();
20444        assert!(
20445            msg.contains("7200"),
20446            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
20447        );
20448    }
20449
20450    #[test]
20451    fn policy_timeout_cap_pins_canonical_value() {
20452        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
20453        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
20454        // the shared duration codec emits as a clean canonical
20455        // string (`"<n>h"`). Pinning the literal value here surfaces
20456        // a future drift (a relaxation to 24h, a tightening to 5m)
20457        // as a deliberate test edit, not a silent contract
20458        // narrowing. Same shape every other typed-cap value pin on
20459        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
20460        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
20461        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
20462    }
20463
20464    #[test]
20465    fn policy_timeout_cap_value_round_trips_through_codec() {
20466        // The codec round-trip property the cap arm preserves: the
20467        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
20468        // the shared duration codec — every value at the cap renders
20469        // to a clean canonical string (`"1h"`) and parses back to
20470        // the same `Duration`. Pin this so a future drift between
20471        // the cap constant and the codec's largest emitted unit
20472        // surfaces here. Same shape every other typed boundary pin
20473        // on this surface uses
20474        // (`wasm32_memory_cap_matches_parsed_4_gib`).
20475        let policy = MeshPolicy {
20476            timeout: Some(POLICY_TIMEOUT_MAX),
20477            ..Default::default()
20478        };
20479        let json = serde_json::to_string(&policy).unwrap();
20480        // The codec emits `"1h"` for the canonical 1-hour magnitude.
20481        assert!(
20482            json.contains("\"1h\""),
20483            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
20484        );
20485        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20486        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
20487    }
20488
20489    #[test]
20490    fn rejects_circuit_breaker_window_sub_millisecond() {
20491        // Peer of the `:timeout` sub-millisecond arm on the second
20492        // typed-`Duration` `:politicas` axis: a purely sub-ms
20493        // `Duration` (`from_micros(500)`) renders through the shared
20494        // codec as `"0s"`, which the codec parses back to
20495        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
20496        // zero-floor gate then rejects on re-validate.
20497        let mut s = three_member_spec();
20498        let window = Duration::from_micros(500);
20499        s.politicas.circuit_breaker = Some(CircuitBreaker {
20500            max_failures: 5,
20501            window,
20502        });
20503        assert_eq!(
20504            s.validate().unwrap_err(),
20505            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
20506        );
20507    }
20508
20509    #[test]
20510    fn rejects_circuit_breaker_window_non_integer_millisecond() {
20511        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
20512        // with non-integer-millisecond residue renders through the
20513        // shared codec as the truncated `"<n>ms"` form, parsing back
20514        // to a *different* `Duration` on the next round-trip.
20515        let mut s = three_member_spec();
20516        let window = Duration::from_micros(1500);
20517        s.politicas.circuit_breaker = Some(CircuitBreaker {
20518            max_failures: 5,
20519            window,
20520        });
20521        assert_eq!(
20522            s.validate().unwrap_err(),
20523            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
20524        );
20525    }
20526
20527    #[test]
20528    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
20529        // The canonical-forms sweep on the breaker axis: every
20530        // integer-ms multiple the codec round-trips losslessly
20531        // passes the canonical gate.
20532        //
20533        // Clears `:timeout` from the fixture so this per-axis sweep
20534        // covers windows shorter than the fixture's 30s timeout
20535        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
20536        // structurally-inert breaker
20537        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
20538        // the cross-axis gate at the end of
20539        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
20540        // `(:timeout, :window)` shape, not on the per-axis
20541        // integer-millisecond canonical-form shape this test pins.
20542        // The paired shape is covered by
20543        // `rejects_circuit_breaker_window_below_timeout`.
20544        for window in [
20545            Duration::from_millis(1),
20546            Duration::from_millis(500),
20547            Duration::from_millis(1500),
20548            Duration::from_secs(30),
20549            Duration::from_secs(60),
20550            Duration::from_secs(3600),
20551        ] {
20552            let mut s = three_member_spec();
20553            s.politicas.timeout = None;
20554            s.politicas.circuit_breaker = Some(CircuitBreaker {
20555                max_failures: 5,
20556                window,
20557            });
20558            s.validate()
20559                .expect("integer-millisecond :circuit-breaker :window must validate");
20560        }
20561    }
20562
20563    #[test]
20564    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
20565        // `Duration::ZERO` would pass the canonical-ms gate (the
20566        // sub-ns residue is zero) but must surface the narrower
20567        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
20568        // remediation.
20569        let mut s = three_member_spec();
20570        s.politicas.circuit_breaker = Some(CircuitBreaker {
20571            max_failures: 5,
20572            window: Duration::ZERO,
20573        });
20574        assert_eq!(
20575            s.validate().unwrap_err(),
20576            AplicacaoError::PolicyBreakerZeroWindow
20577        );
20578    }
20579
20580    #[test]
20581    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
20582        // Both axes invalid: max_failures == 0 *and* window is
20583        // sub-ms. The validate gate must fire on max_failures first
20584        // (matching the existing ordering pin
20585        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
20586        // the existing diagnostic continues to lead with the simpler
20587        // "zero threshold" framing.
20588        let mut s = three_member_spec();
20589        s.politicas.circuit_breaker = Some(CircuitBreaker {
20590            max_failures: 0,
20591            window: Duration::from_micros(500),
20592        });
20593        assert_eq!(
20594            s.validate().unwrap_err(),
20595            AplicacaoError::PolicyBreakerZeroFailures
20596        );
20597    }
20598
20599    #[test]
20600    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
20601        let mut s = three_member_spec();
20602        let window = Duration::from_nanos(60_000_000_001);
20603        s.politicas.circuit_breaker = Some(CircuitBreaker {
20604            max_failures: 5,
20605            window,
20606        });
20607        match s.validate().unwrap_err() {
20608            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
20609                assert_eq!(w, window, "diagnostic must carry the offending Duration");
20610            }
20611            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
20612        }
20613    }
20614
20615    #[test]
20616    fn rejects_circuit_breaker_window_above_cap() {
20617        // The fail-before-pass-after pin: 3601s = 1h + 1s is
20618        // structurally one canonical-tick past the
20619        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
20620        // integer-millisecond magnitude the canonical-form arm above
20621        // accepts cleanly, that the codec round-trips losslessly as
20622        // `"3601s"`, and that silently passed validate on every
20623        // pre-gate codebase because the typed slot's only checks were
20624        // the zero-floor and canonical-form arms. The
20625        // rolling-window-to-lifetime-counter degeneration surfaces
20626        // only at the runtime substrate (Envoy's outlier_detection
20627        // interval, the future CiliumClusterwideEnvoyConfig overlay)
20628        // far from the source `caixa.lisp` with no field naming the
20629        // offending policy.
20630        let mut s = three_member_spec();
20631        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
20632        s.politicas.circuit_breaker = Some(CircuitBreaker {
20633            max_failures: 5,
20634            window,
20635        });
20636        assert_eq!(
20637            s.validate().unwrap_err(),
20638            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20639        );
20640    }
20641
20642    #[test]
20643    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
20644        // Boundary case: exactly 1ms past the cap (the granularity the
20645        // canonical-form gate enforces). Catches a future "strictly
20646        // less than" half-measure and pins the diagnostic to name the
20647        // offending `Duration` verbatim. Peer of
20648        // `rejects_policy_timeout_one_millisecond_above_cap` on the
20649        // sibling duration-typed `:politicas :timeout` top edge.
20650        let mut s = three_member_spec();
20651        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
20652        s.politicas.circuit_breaker = Some(CircuitBreaker {
20653            max_failures: 5,
20654            window,
20655        });
20656        assert_eq!(
20657            s.validate().unwrap_err(),
20658            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20659        );
20660    }
20661
20662    #[test]
20663    fn rejects_circuit_breaker_window_far_above_cap() {
20664        // The "obvious authoring footgun" case: a `(:window "24h")` or
20665        // `(:window "86400s")` — values the canonical-form arm
20666        // accepts as integer-millisecond magnitudes, the codec
20667        // round-trips losslessly through serde, but the
20668        // rolling-window breaker contract cannot honor (a 24-hour
20669        // rolling failure window is operationally a lifetime counter).
20670        // Until this gate landed validate accepted it. Pin both common
20671        // above-cap values (24h, 7d) so a future relaxation that
20672        // drops the upper bound surfaces here.
20673        for window in [
20674            Duration::from_secs(86_400),    // 24h
20675            Duration::from_secs(604_800),   // 7d
20676            Duration::from_secs(1_000_000), // ~11.5 days
20677        ] {
20678            let mut s = three_member_spec();
20679            s.politicas.circuit_breaker = Some(CircuitBreaker {
20680                max_failures: 5,
20681                window,
20682            });
20683            assert_eq!(
20684                s.validate().unwrap_err(),
20685                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
20686            );
20687        }
20688    }
20689
20690    #[test]
20691    fn accepts_circuit_breaker_window_at_cap() {
20692        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
20693        // (1h) — must validate. The cap is inclusive on the top edge,
20694        // matching the [`POLICY_TIMEOUT_MAX`] /
20695        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
20696        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
20697        // sibling capped axes. Pin the boundary explicitly so a
20698        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
20699        // instead of `>`) surfaces here as a test failure rather than
20700        // a silent contract narrowing.
20701        let mut s = three_member_spec();
20702        s.politicas.circuit_breaker = Some(CircuitBreaker {
20703            max_failures: 5,
20704            window: POLICY_BREAKER_WINDOW_MAX,
20705        });
20706        s.validate()
20707            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
20708    }
20709
20710    #[test]
20711    fn accepts_circuit_breaker_window_typical_values() {
20712        // The documented production-playbook band positive-control
20713        // sweep — every value Hystrix / resilience4j / Istio / Envoy
20714        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
20715        // through the long-tail failure-detection band (15m, 30m, 1h)
20716        // the cap accepts. Pin the inclusive validated set explicitly
20717        // so a future tightening of the ceiling surfaces here as a
20718        // deliberate test edit, not a silent contract narrowing.
20719        //
20720        // Clears `:timeout` from the fixture so this per-axis sweep
20721        // covers windows shorter than the fixture's 30s timeout
20722        // (Hystrix's 10s default, resilience4j's 30s, and the
20723        // sub-second warm-up band) — every such value is a
20724        // structurally-inert breaker under the cross-axis gate at the
20725        // end of [`AplicacaoSpec::validate_politicas`]
20726        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
20727        // the paired `(:timeout, :window)` shape is covered by
20728        // `rejects_circuit_breaker_window_below_timeout`; this
20729        // per-axis pin ranges only over the per-axis-bracket accept set.
20730        for window in [
20731            Duration::from_millis(1),
20732            Duration::from_millis(500),
20733            Duration::from_secs(1),
20734            Duration::from_secs(10), // Hystrix / Istio / Envoy default
20735            Duration::from_secs(30),
20736            Duration::from_secs(60),  // resilience4j typical
20737            Duration::from_secs(300), // AWS App Mesh typical
20738            Duration::from_secs(900),
20739            Duration::from_secs(1800),
20740            Duration::from_secs(3600), // exactly 1h, the cap
20741        ] {
20742            let mut s = three_member_spec();
20743            s.politicas.timeout = None;
20744            s.politicas.circuit_breaker = Some(CircuitBreaker {
20745                max_failures: 5,
20746                window,
20747            });
20748            s.validate()
20749                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
20750        }
20751    }
20752
20753    #[test]
20754    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
20755        // The cross-arm ordering pin: `Duration::ZERO` is structurally
20756        // outside both `>= 1ms` (zero-floor) and
20757        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
20758        // diagnostic is the more self-locating one (it directly names
20759        // the omit-axis remediation), so the validate gate must fire
20760        // on zero first. Same shape every other zero-then-cap
20761        // ordering on this surface uses
20762        // ([`AplicacaoError::PolicyTimeoutZero`] then
20763        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
20764        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20765        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20766        let mut s = three_member_spec();
20767        s.politicas.circuit_breaker = Some(CircuitBreaker {
20768            max_failures: 5,
20769            window: Duration::ZERO,
20770        });
20771        assert_eq!(
20772            s.validate().unwrap_err(),
20773            AplicacaoError::PolicyBreakerZeroWindow,
20774            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
20775        );
20776    }
20777
20778    #[test]
20779    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
20780        // The cross-arm ordering pin: a `Duration` that is *both*
20781        // sub-millisecond (non-canonical-form) and structurally above
20782        // the cap surfaces the canonical-form diagnostic first,
20783        // because the round-trip-shape break is the more fundamental
20784        // issue (the value can't even round-trip through the codec, so
20785        // the cap diagnostic naming `1ms..=1h` would be misleading —
20786        // there's no integer-ms form of the offending value). Pin the
20787        // order so a future refactor that reorders the arms surfaces
20788        // here as a test failure rather than a silent diagnostic
20789        // regression. Peer of
20790        // `policy_timeout_canonical_takes_precedence_over_cap` on the
20791        // sibling duration-typed `:politicas :timeout` axis.
20792        let mut s = three_member_spec();
20793        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
20794        s.politicas.circuit_breaker = Some(CircuitBreaker {
20795            max_failures: 5,
20796            window,
20797        });
20798        assert_eq!(
20799            s.validate().unwrap_err(),
20800            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
20801            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
20802        );
20803    }
20804
20805    #[test]
20806    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
20807        // The cross-arm ordering pin between the two breaker axes: a
20808        // `CircuitBreaker` whose *both* `max_failures` is above its
20809        // cap *and* `window` is above its cap surfaces the
20810        // max-failures cap diagnostic first, because the validate
20811        // gate visits the failures arm before the window arm. Pin the
20812        // order so a future refactor that reorders the breaker arms
20813        // surfaces here.
20814        let mut s = three_member_spec();
20815        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
20816        s.politicas.circuit_breaker = Some(CircuitBreaker {
20817            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20818            window,
20819        });
20820        assert_eq!(
20821            s.validate().unwrap_err(),
20822            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20823                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
20824            },
20825            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
20826        );
20827    }
20828
20829    #[test]
20830    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
20831        // The diagnostic-shape pin: the offending `Duration` is
20832        // carried verbatim into the
20833        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
20834        // the surfaced error message names the value the author wrote
20835        // (`":politicas :circuit-breaker :window (Duration { secs:
20836        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
20837        // just the cap. Same self-locating diagnostic shape every
20838        // other typed-cap arm on this surface carries
20839        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
20840        // offending `Duration` verbatim).
20841        let mut s = three_member_spec();
20842        let window = Duration::from_secs(7200); // 2h
20843        s.politicas.circuit_breaker = Some(CircuitBreaker {
20844            max_failures: 5,
20845            window,
20846        });
20847        let err = s.validate().unwrap_err();
20848        assert!(
20849            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
20850            "got {err:?}"
20851        );
20852        let msg = err.to_string();
20853        assert!(
20854            msg.contains("7200"),
20855            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
20856        );
20857    }
20858
20859    #[test]
20860    fn circuit_breaker_window_cap_pins_canonical_value() {
20861        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
20862        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
20863        // shared duration codec emits as a clean canonical string
20864        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
20865        // the sibling duration-typed `:politicas :timeout` axis (the
20866        // two duration-typed `:politicas` axes share a uniform top
20867        // edge). Pinning the literal value here surfaces a future
20868        // drift (a relaxation to 24h, a tightening to 5m) as a
20869        // deliberate test edit, not a silent contract narrowing. Same
20870        // shape every other typed-cap value pin on this surface uses
20871        // (`policy_timeout_cap_pins_canonical_value`).
20872        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
20873        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
20874        assert_eq!(
20875            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
20876            "the two duration-typed `:politicas` caps share the same top edge"
20877        );
20878    }
20879
20880    #[test]
20881    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
20882        // The codec round-trip property the cap arm preserves: the
20883        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
20884        // through the shared duration codec — every value at the cap
20885        // renders to a clean canonical string (`"1h"`) and parses back
20886        // to the same `Duration`. Pin this so a future drift between
20887        // the cap constant and the codec's largest emitted unit
20888        // surfaces here. Same shape every other typed boundary pin on
20889        // this surface uses
20890        // (`policy_timeout_cap_value_round_trips_through_codec`).
20891        let policy = MeshPolicy {
20892            circuit_breaker: Some(CircuitBreaker {
20893                max_failures: 5,
20894                window: POLICY_BREAKER_WINDOW_MAX,
20895            }),
20896            ..Default::default()
20897        };
20898        let json = serde_json::to_string(&policy).unwrap();
20899        // The codec emits `"1h"` for the canonical 1-hour magnitude.
20900        assert!(
20901            json.contains("\"1h\""),
20902            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
20903        );
20904        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20905        assert_eq!(
20906            back.circuit_breaker.unwrap().window,
20907            POLICY_BREAKER_WINDOW_MAX
20908        );
20909    }
20910
20911    #[test]
20912    fn is_integer_millisecond_duration_predicate_tracks_codec() {
20913        // Pin the predicate's accepted set against the codec's
20914        // accepted set explicitly. The codec parses
20915        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
20916        // accepted value is an integer-millisecond multiple — so the
20917        // predicate must accept exactly that set. Same shape every
20918        // other predicate-on-the-typed-slot helper carries
20919        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
20920        // Read directly from the codec-owned predicate — the crate's
20921        // single source of truth every typed-`Duration` axis now routes
20922        // through via
20923        // [`crate::render::require_positive_canonical_bounded_duration`].
20924        use super::supervisor::duration_codec::is_integer_millisecond_duration;
20925        assert!(is_integer_millisecond_duration(Duration::ZERO));
20926        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
20927        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
20928        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
20929        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
20930        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
20931        // Non-integer-millisecond residue: rejected.
20932        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
20933        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
20934        assert!(!is_integer_millisecond_duration(Duration::from_micros(
20935            1500
20936        )));
20937        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
20938        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
20939            999_999
20940        )));
20941        // The 1-ns-past-1ms boundary: rejected (no longer a clean
20942        // integer-millisecond multiple).
20943        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
20944            1_000_001
20945        )));
20946    }
20947
20948    #[test]
20949    fn policy_timeout_validated_value_round_trips_through_codec() {
20950        // The structural property the canonical-ms gate enforces:
20951        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
20952        // round-trips losslessly through the shared `duration_codec`
20953        // (serialize → string → deserialize → equal value). Pin this
20954        // end-to-end so a future change to either side (the validate
20955        // gate's accepted granularity, the codec's parse/render unit
20956        // set) that breaks the alignment surfaces here. The
20957        // previous-state shape (typed slot accepts arbitrary
20958        // `Duration`, codec only round-trips integer-ms) would fail
20959        // this test for any `Duration::from_micros(1500)` timeout —
20960        // the validate gate now forecloses that.
20961        for timeout in [
20962            Duration::from_millis(1),
20963            Duration::from_millis(1500),
20964            Duration::from_secs(30),
20965            Duration::from_secs(3600),
20966        ] {
20967            let mut s = three_member_spec();
20968            s.politicas.timeout = Some(timeout);
20969            s.validate().unwrap();
20970            let json = serde_json::to_string(&s.politicas).unwrap();
20971            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20972            assert_eq!(
20973                back.timeout, s.politicas.timeout,
20974                "every validated :timeout must round-trip losslessly through the codec"
20975            );
20976        }
20977    }
20978
20979    #[test]
20980    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
20981        // Peer of the `:timeout` round-trip property on the breaker
20982        // axis.
20983        //
20984        // Clears `:timeout` from the fixture so the round-trip pin
20985        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
20986        // cross-axis gate would otherwise reject as structurally-inert
20987        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
20988        // the paired `(:timeout, :window)` cross-axis relation is
20989        // pinned separately by
20990        // `rejects_circuit_breaker_window_below_timeout`, and this
20991        // property is a pure serde-codec round-trip on the per-axis
20992        // slot.
20993        for window in [
20994            Duration::from_millis(1),
20995            Duration::from_millis(1500),
20996            Duration::from_secs(30),
20997            Duration::from_secs(3600),
20998        ] {
20999            let mut s = three_member_spec();
21000            s.politicas.timeout = None;
21001            s.politicas.circuit_breaker = Some(CircuitBreaker {
21002                max_failures: 5,
21003                window,
21004            });
21005            s.validate().unwrap();
21006            let json = serde_json::to_string(&s.politicas).unwrap();
21007            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21008            assert_eq!(
21009                back.circuit_breaker.unwrap().window,
21010                window,
21011                "every validated :circuit-breaker :window must round-trip losslessly"
21012            );
21013        }
21014    }
21015
21016    #[test]
21017    fn rejects_circuit_breaker_window_below_timeout() {
21018        // The fail-before-pass-after pin on the cross-axis
21019        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
21020        // is individually well-formed under its own per-axis bracket
21021        // (both integer-millisecond, both above the zero floor, both
21022        // below the cap), but the pair is a structurally-inert
21023        // breaker: a call dispatched at t=0 is declared failed at
21024        // t=30s, by which point the 10s rolling window open at
21025        // dispatch has already rolled twice, so no window can hold
21026        // a timeout-derived failure however high the call volume.
21027        //
21028        // Envoy's `outlier_detection.interval` against the per-route
21029        // request timeout carries the identical relation; Hystrix
21030        // ships the canonical ratio in its defaults (10s window
21031        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
21032        //
21033        // Pin both the diagnostic arm and the payload values so a
21034        // future re-shape of the arm surfaces here as a deliberate
21035        // test edit.
21036        let mut s = three_member_spec();
21037        s.politicas.timeout = Some(Duration::from_secs(30));
21038        s.politicas.circuit_breaker = Some(CircuitBreaker {
21039            max_failures: 5,
21040            window: Duration::from_secs(10),
21041        });
21042        assert_eq!(
21043            s.validate().unwrap_err(),
21044            AplicacaoError::PolicyBreakerWindowBelowTimeout {
21045                window: Duration::from_secs(10),
21046                timeout: Duration::from_secs(30),
21047            }
21048        );
21049    }
21050
21051    #[test]
21052    fn accepts_circuit_breaker_window_equal_to_timeout() {
21053        // Boundary pin: `:window == :timeout` is the smallest window
21054        // that structurally admits at least one full timeout-derived
21055        // failure before the rolling interval closes (the invariant
21056        // is `:window >= :timeout`, not strict inequality). Catches
21057        // a future off-by-one tightening that would drift the accept
21058        // set away from the codified [`MeshPolicy::breaker_window_
21059        // observes_timeout`] predicate.
21060        let mut s = three_member_spec();
21061        s.politicas.timeout = Some(Duration::from_secs(30));
21062        s.politicas.circuit_breaker = Some(CircuitBreaker {
21063            max_failures: 5,
21064            window: Duration::from_secs(30),
21065        });
21066        s.validate()
21067            .expect("window == timeout is the boundary accept case");
21068    }
21069
21070    #[test]
21071    fn accepts_circuit_breaker_window_above_timeout() {
21072        // Positive-control sweep across the production-playbook band —
21073        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
21074        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
21075        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
21076        // playbook recommends must validate under the cross-axis gate.
21077        for (timeout, window) in [
21078            (Duration::from_secs(1), Duration::from_secs(10)),
21079            (Duration::from_secs(5), Duration::from_secs(30)),
21080            (Duration::from_secs(10), Duration::from_secs(60)),
21081            (Duration::from_secs(30), Duration::from_secs(300)),
21082            (Duration::from_secs(60), Duration::from_secs(300)),
21083        ] {
21084            let mut s = three_member_spec();
21085            s.politicas.timeout = Some(timeout);
21086            s.politicas.circuit_breaker = Some(CircuitBreaker {
21087                max_failures: 5,
21088                window,
21089            });
21090            s.validate().unwrap_or_else(|e| {
21091                panic!(
21092                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
21093                     validate; got {e:?}"
21094                )
21095            });
21096        }
21097    }
21098
21099    #[test]
21100    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
21101        // Off-by-one boundary pin: a window exactly 1ms shy of the
21102        // timeout is still structurally inert under the invariant
21103        // (the dispatch-to-report lag is `timeout`, so the window
21104        // must span at least one such lag). Catches a future
21105        // strict-inequality relaxation that would silently drift
21106        // the accept boundary.
21107        let timeout = Duration::from_secs(30);
21108        let window = Duration::from_millis(29_999);
21109        let mut s = three_member_spec();
21110        s.politicas.timeout = Some(timeout);
21111        s.politicas.circuit_breaker = Some(CircuitBreaker {
21112            max_failures: 5,
21113            window,
21114        });
21115        assert_eq!(
21116            s.validate().unwrap_err(),
21117            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
21118        );
21119    }
21120
21121    #[test]
21122    fn cross_axis_gate_vacuous_when_timeout_absent() {
21123        // The predicate is vacuously `true` when `:timeout` is None —
21124        // a `:circuit-breaker` alone declares no relation to a
21125        // substrate-imposed deadline (the failure signal reaches the
21126        // breaker from the transport's own error surface, so no
21127        // dispatch-to-report lag is knowable at author time). Pin so
21128        // a future tightening that made the gate opinionated on
21129        // half-declared pairs surfaces here.
21130        let mut s = three_member_spec();
21131        s.politicas.timeout = None;
21132        s.politicas.circuit_breaker = Some(CircuitBreaker {
21133            max_failures: 5,
21134            window: Duration::from_millis(1),
21135        });
21136        s.validate().expect(
21137            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
21138        );
21139    }
21140
21141    #[test]
21142    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
21143        // Peer of the sibling `:timeout`-absent case: a `:timeout`
21144        // without a `:circuit-breaker` declares a per-call deadline
21145        // without any rolling-window failure accounting, so the pair
21146        // is undeclared and the cross-axis gate has nothing to check.
21147        let mut s = three_member_spec();
21148        s.politicas.timeout = Some(Duration::from_secs(3600));
21149        s.politicas.circuit_breaker = None;
21150        s.validate().expect(
21151            "cross-axis gate must be vacuous when :circuit-breaker is None, \
21152             however large :timeout is",
21153        );
21154    }
21155
21156    #[test]
21157    fn cross_axis_gate_runs_after_per_axis_brackets() {
21158        // Ordering pin: a pair whose window is *both* zero-floor-
21159        // violating and structurally below the timeout must surface
21160        // the per-axis zero-floor arm first — the zero-floor
21161        // diagnostic is more self-locating (its omit-axis remediation
21162        // is directly named), where the cross-axis arm would send the
21163        // author to reconcile two values one of which is not a
21164        // meaningful window at all. Same ordering discipline every
21165        // per-axis bracket carries internally (zero-floor before
21166        // canonical-form before cap).
21167        let mut s = three_member_spec();
21168        s.politicas.timeout = Some(Duration::from_secs(30));
21169        s.politicas.circuit_breaker = Some(CircuitBreaker {
21170            max_failures: 5,
21171            window: Duration::ZERO,
21172        });
21173        assert_eq!(
21174            s.validate().unwrap_err(),
21175            AplicacaoError::PolicyBreakerZeroWindow,
21176            "per-axis zero-floor arm must fire before the cross-axis gate"
21177        );
21178    }
21179
21180    #[test]
21181    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
21182        // Equivalence pin: the substrate-canonical
21183        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
21184        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21185        // arm must discriminate the same set on every pair covered
21186        // by their shared invariant. A future refactor of either
21187        // side that breaks the equivalence trips here rather than as
21188        // a divergence between the predicate's Boolean answer and
21189        // the validate gate's Ok/Err arm — the same
21190        // predicate-vs-gate coherence discipline the peer
21191        // [`PlacementStrategy::is_shard_keyed`] predicate carries
21192        // against `AplicacaoSpec::validate_placement`. The sweep
21193        // covers both arms of the invariant (below, equal, above)
21194        // and both vacuous arms (None `:timeout`, None
21195        // `:circuit-breaker`), so the equivalence holds
21196        // exhaustively over the axis-covered accept and reject sets.
21197        let cases: &[(Option<Duration>, Option<Duration>)] = &[
21198            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
21199            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
21200            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
21201            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
21202            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
21203            (None, Some(Duration::from_secs(1))),
21204            (Some(Duration::from_secs(30)), None),
21205            (None, None),
21206        ];
21207        for (timeout, window) in cases.iter().copied() {
21208            let politicas = MeshPolicy {
21209                timeout,
21210                circuit_breaker: window.map(|w| CircuitBreaker {
21211                    max_failures: 5,
21212                    window: w,
21213                }),
21214                ..Default::default()
21215            };
21216            let predicate = politicas.breaker_window_observes_timeout();
21217
21218            let mut s = three_member_spec();
21219            s.politicas = politicas.clone();
21220            let gate_ok = !matches!(
21221                s.validate(),
21222                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
21223            );
21224
21225            assert_eq!(
21226                predicate, gate_ok,
21227                "predicate must agree with validate arm on pair \
21228                 (timeout={timeout:?}, window={window:?})"
21229            );
21230        }
21231    }
21232
21233    #[test]
21234    fn rejects_rate_limit_starves_circuit_breaker() {
21235        // The fail-before-pass-after pin on the cross-axis
21236        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
21237        // individually well-formed under its own per-axis bracket
21238        // (both above the zero floor, both below the cap, rate-limit
21239        // window canonical), but the pair is a structurally-inert
21240        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
21241        // calls per rolling breaker window, so no window can
21242        // accumulate five failures however catastrophic the upstream
21243        // failure rate.
21244        //
21245        // Envoy's `outlier_detection.consecutive_5xx` paired against
21246        // `local_rate_limit.token_bucket.max_tokens` /
21247        // `fill_interval` carries the identical relation; every
21248        // production playbook that pairs the two axes (Envoy, Istio,
21249        // AWS App Mesh, Kong) sizes the rate at or above the
21250        // breaker's minimum-request-volume threshold for exactly this
21251        // reason.
21252        //
21253        // Pin both the diagnostic arm and the payload values so a
21254        // future re-shape of the arm surfaces here as a deliberate
21255        // test edit. Clears `:timeout` so the sibling
21256        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
21257        // does not fire first on the ordering-precedent it holds
21258        // over this arm.
21259        let mut s = three_member_spec();
21260        s.politicas.timeout = None;
21261        s.politicas.circuit_breaker = Some(CircuitBreaker {
21262            max_failures: 5,
21263            window: Duration::from_secs(10),
21264        });
21265        s.politicas.rate_limit = Some(RateLimit {
21266            rate: 1,
21267            window: Duration::from_secs(3600),
21268        });
21269        assert_eq!(
21270            s.validate().unwrap_err(),
21271            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21272                rate: 1,
21273                rl_window: Duration::from_secs(3600),
21274                max_failures: 5,
21275                cb_window: Duration::from_secs(10),
21276            }
21277        );
21278    }
21279
21280    #[test]
21281    fn accepts_rate_limit_can_trip_circuit_breaker() {
21282        // Positive-control sweep across the production-playbook band
21283        // — every pair a real playbook recommends where the rate
21284        // clearly admits enough calls per breaker window to reach
21285        // `:max-failures` must validate. Envoy default 5 failures
21286        // in 10s with 100/s (1000 calls / window, 200× the threshold),
21287        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
21288        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
21289        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
21290        // the sibling cross-axis arm is vacuous on this sweep.
21291        for (rate, rl_window, max_failures, cb_window) in [
21292            (
21293                100u32,
21294                Duration::from_secs(1),
21295                5u32,
21296                Duration::from_secs(10),
21297            ),
21298            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
21299            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
21300            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
21301            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
21302        ] {
21303            let mut s = three_member_spec();
21304            s.politicas.timeout = None;
21305            s.politicas.circuit_breaker = Some(CircuitBreaker {
21306                max_failures,
21307                window: cb_window,
21308            });
21309            s.politicas.rate_limit = Some(RateLimit {
21310                rate,
21311                window: rl_window,
21312            });
21313            s.validate().unwrap_or_else(|e| {
21314                panic!(
21315                    "production-playbook pair rate={rate}/{rl_window:?} \
21316                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
21317                )
21318            });
21319        }
21320    }
21321
21322    #[test]
21323    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
21324        // Boundary pin: `rate × cb_window == max_failures × rl_window`
21325        // is the smallest bucket capacity that structurally admits
21326        // exactly `max_failures` calls per rolling breaker window
21327        // (the invariant is `≥`, not strict inequality). Catches a
21328        // future off-by-one tightening to strict inequality that
21329        // would drift the accept set away from the codified
21330        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
21331        // 5 calls/s over a 1s breaker window == 5 max_failures.
21332        let mut s = three_member_spec();
21333        s.politicas.timeout = None;
21334        s.politicas.circuit_breaker = Some(CircuitBreaker {
21335            max_failures: 5,
21336            window: Duration::from_secs(1),
21337        });
21338        s.politicas.rate_limit = Some(RateLimit {
21339            rate: 5,
21340            window: Duration::from_secs(1),
21341        });
21342        s.validate()
21343            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
21344    }
21345
21346    #[test]
21347    fn rejects_rate_limit_one_call_short_per_cb_window() {
21348        // Off-by-one boundary pin: exactly one call short of the trip
21349        // threshold per breaker window is still structurally inert
21350        // (the invariant is `≥`, so `<` refuses even a one-call
21351        // shortfall). 4 calls/s over a 1s window == 4 admissible
21352        // failures, one shy of the 5-`max_failures` threshold.
21353        // Catches a future strict-inequality relaxation that would
21354        // silently drift the accept boundary.
21355        let mut s = three_member_spec();
21356        s.politicas.timeout = None;
21357        s.politicas.circuit_breaker = Some(CircuitBreaker {
21358            max_failures: 5,
21359            window: Duration::from_secs(1),
21360        });
21361        s.politicas.rate_limit = Some(RateLimit {
21362            rate: 4,
21363            window: Duration::from_secs(1),
21364        });
21365        assert_eq!(
21366            s.validate().unwrap_err(),
21367            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21368                rate: 4,
21369                rl_window: Duration::from_secs(1),
21370                max_failures: 5,
21371                cb_window: Duration::from_secs(1),
21372            }
21373        );
21374    }
21375
21376    #[test]
21377    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
21378        // The predicate is vacuously `true` when `:rate-limit` is
21379        // None — a `:circuit-breaker` alone declares no relation to
21380        // a substrate-imposed call rate (the failure signal reaches
21381        // the breaker from the transport's own error surface, at
21382        // whatever rate upstream callers push traffic). Pin so a
21383        // future tightening that made the gate opinionated on
21384        // half-declared pairs surfaces here.
21385        let mut s = three_member_spec();
21386        s.politicas.timeout = None;
21387        s.politicas.circuit_breaker = Some(CircuitBreaker {
21388            max_failures: 1000,
21389            window: Duration::from_millis(1),
21390        });
21391        s.politicas.rate_limit = None;
21392        s.validate().expect(
21393            "cross-axis starve gate must be vacuous when :rate-limit is None, \
21394             however high :max-failures and however small :window are",
21395        );
21396    }
21397
21398    #[test]
21399    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
21400        // Peer of the sibling `:rate-limit`-absent case: a
21401        // `:rate-limit` without a `:circuit-breaker` declares a
21402        // per-edge token-bucket rate without any failure counter to
21403        // starve, so the pair is undeclared and the cross-axis gate
21404        // has nothing to check.
21405        //
21406        // Also clears the fixture's `:retries` (which is `Some(3)`) so
21407        // the sibling cross-axis
21408        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
21409        // (which reasons across the paired `(:retries, :rate-limit)`
21410        // pair independent of `:circuit-breaker`) is vacuous on this
21411        // pin — this test names the *starve* arm's vacuity on the
21412        // `:circuit-breaker`-absent case, not the burst arm's.
21413        let mut s = three_member_spec();
21414        s.politicas.timeout = None;
21415        s.politicas.retries = None;
21416        s.politicas.circuit_breaker = None;
21417        s.politicas.rate_limit = Some(RateLimit {
21418            rate: 1,
21419            window: Duration::from_secs(3600),
21420        });
21421        s.validate().expect(
21422            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
21423             however low :rate is",
21424        );
21425    }
21426
21427    #[test]
21428    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
21429        // Ordering pin: a pair whose rate is *both* zero-floor-
21430        // violating and structurally below the trip threshold must
21431        // surface the per-axis zero-floor arm first — the zero-floor
21432        // diagnostic is more self-locating (its omit-axis remediation
21433        // is directly named), where the cross-axis arm would send the
21434        // author to reconcile four values one of which is not a
21435        // meaningful rate at all. Same ordering discipline every
21436        // per-axis bracket carries internally (zero-floor before
21437        // canonical-form before cap), and the sibling cross-axis
21438        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
21439        // ordering pins on the `(:timeout, :window)` pair.
21440        let mut s = three_member_spec();
21441        s.politicas.timeout = None;
21442        s.politicas.circuit_breaker = Some(CircuitBreaker {
21443            max_failures: 5,
21444            window: Duration::from_secs(10),
21445        });
21446        s.politicas.rate_limit = Some(RateLimit {
21447            rate: 0,
21448            window: Duration::from_secs(1),
21449        });
21450        assert_eq!(
21451            s.validate().unwrap_err(),
21452            AplicacaoError::PolicyRateLimitZero,
21453            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
21454        );
21455    }
21456
21457    #[test]
21458    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
21459        // Cross-axis ordering pin: a `:politicas` whose axes trip
21460        // BOTH cross-axis arms — `:window < :timeout` (the sibling
21461        // `PolicyBreakerWindowBelowTimeout` invariant) AND
21462        // `:rate-limit` starves the breaker within `:window` (this
21463        // arm) — must surface the timeout-relation diagnostic first.
21464        // The timeout arm is the per-call-deadline invariant every
21465        // synchronous edge carries whether or not `:rate-limit` is
21466        // declared, so its diagnostic is more self-locating; the
21467        // starve arm needs the reader to reason across three axes,
21468        // where the timeout arm names only two.
21469        //
21470        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
21471        // pair trips both: the window is below the timeout, and the
21472        // rate (1 call/hour) admits far fewer than 5 calls per 10s
21473        // breaker window.
21474        let mut s = three_member_spec();
21475        s.politicas.timeout = Some(Duration::from_secs(30));
21476        s.politicas.circuit_breaker = Some(CircuitBreaker {
21477            max_failures: 5,
21478            window: Duration::from_secs(10),
21479        });
21480        s.politicas.rate_limit = Some(RateLimit {
21481            rate: 1,
21482            window: Duration::from_secs(3600),
21483        });
21484        assert_eq!(
21485            s.validate().unwrap_err(),
21486            AplicacaoError::PolicyBreakerWindowBelowTimeout {
21487                window: Duration::from_secs(10),
21488                timeout: Duration::from_secs(30),
21489            },
21490            "sibling :window<:timeout cross-axis arm must fire before the \
21491             starve arm when both apply"
21492        );
21493    }
21494
21495    #[test]
21496    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
21497        // Equivalence pin: the substrate-canonical
21498        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
21499        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21500        // arm must discriminate the same set on every pair covered
21501        // by their shared invariant. A future refactor of either
21502        // side that breaks the equivalence trips here rather than as
21503        // a divergence between the predicate's Boolean answer and
21504        // the validate gate's Ok/Err arm — the same
21505        // predicate-vs-gate coherence discipline the sibling
21506        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
21507        // carries against `AplicacaoSpec::validate_politicas`. The
21508        // sweep covers both arms of the invariant (strictly below,
21509        // exactly at, strictly above) and both vacuous arms (None
21510        // `:rate-limit`, None `:circuit-breaker`), so the
21511        // equivalence holds exhaustively over the axis-covered
21512        // accept and reject sets. Clears `:timeout` throughout so
21513        // the sibling `:window<:timeout` gate is vacuous on every
21514        // input.
21515        let rl = |rate: u32, secs: u64| {
21516            Some(RateLimit {
21517                rate,
21518                window: Duration::from_secs(secs),
21519            })
21520        };
21521        let cb = |max_failures: u32, secs: u64| {
21522            Some(CircuitBreaker {
21523                max_failures,
21524                window: Duration::from_secs(secs),
21525            })
21526        };
21527        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
21528            // starving pairs (predicate = false, gate = Err)
21529            (rl(1, 3600), cb(5, 10)),
21530            (rl(4, 1), cb(5, 1)),
21531            // boundary + coherent pairs (predicate = true, gate = Ok)
21532            (rl(5, 1), cb(5, 1)),
21533            (rl(100, 1), cb(5, 10)),
21534            // vacuous arms
21535            (None, cb(5, 10)),
21536            (rl(1, 3600), None),
21537            (None, None),
21538        ];
21539        for (rate_limit, circuit_breaker) in cases.iter().copied() {
21540            let politicas = MeshPolicy {
21541                circuit_breaker,
21542                rate_limit,
21543                ..Default::default()
21544            };
21545            let predicate = politicas.breaker_can_trip_under_rate_limit();
21546
21547            let mut s = three_member_spec();
21548            s.politicas = politicas.clone();
21549            s.politicas.timeout = None;
21550            let gate_ok = !matches!(
21551                s.validate(),
21552                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
21553            );
21554
21555            assert_eq!(
21556                predicate, gate_ok,
21557                "predicate must agree with validate arm on pair \
21558                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
21559            );
21560        }
21561    }
21562
21563    #[test]
21564    fn rejects_retries_saturate_breaker_trip_threshold() {
21565        // The fail-before-pass-after pin on the cross-axis
21566        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
21567        // axis is individually well-formed under its own per-axis
21568        // bracket (both above the zero floor, both below the cap), but
21569        // the pair is a structurally-truncated retry policy: one
21570        // client's `retries + 1 = 4` failing attempts hit the trip
21571        // threshold on the third attempt, the breaker opens, and the
21572        // fourth attempt (the last declared retry) is blocked by the
21573        // open breaker — the substrate declared four attempts and
21574        // structurally allows three.
21575        //
21576        // Envoy's `retry_policy.num_retries` paired against
21577        // `outlier_detection.consecutive_5xx` carries the identical
21578        // relation; every production playbook that pairs the two axes
21579        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
21580        // trip threshold strictly above any single client's retry
21581        // budget so the breaker distinguishes one persistently-failing
21582        // client from sustained multi-client failure.
21583        //
21584        // Pin both the diagnostic arm and the payload values so a
21585        // future re-shape of the arm surfaces here as a deliberate
21586        // test edit. Clears `:timeout` and `:rate-limit` so the
21587        // sibling cross-axis
21588        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
21589        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
21590        // arms do not fire first on the ordering-precedent they hold
21591        // over this arm.
21592        let mut s = three_member_spec();
21593        s.politicas.timeout = None;
21594        s.politicas.retries = Some(3);
21595        s.politicas.circuit_breaker = Some(CircuitBreaker {
21596            max_failures: 3,
21597            window: Duration::from_secs(1),
21598        });
21599        s.politicas.rate_limit = None;
21600        assert_eq!(
21601            s.validate().unwrap_err(),
21602            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21603                retries: 3,
21604                max_failures: 3,
21605            }
21606        );
21607    }
21608
21609    #[test]
21610    fn accepts_retries_below_breaker_trip_threshold() {
21611        // Positive-control sweep across the production-playbook band
21612        // — every pair a real playbook recommends where the breaker's
21613        // trip threshold is strictly above the client's retry budget
21614        // must validate. Envoy default `num_retries: 3` with
21615        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
21616        // opens on multi-client failures beyond that); Istio
21617        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
21618        // `execution.isolation.thread.timeoutInMilliseconds` + 3
21619        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
21620        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
21621        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
21622        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
21623        // arms are vacuous on this sweep.
21624        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
21625        {
21626            let mut s = three_member_spec();
21627            s.politicas.timeout = None;
21628            s.politicas.retries = Some(retries);
21629            s.politicas.circuit_breaker = Some(CircuitBreaker {
21630                max_failures,
21631                window: Duration::from_secs(60),
21632            });
21633            s.politicas.rate_limit = None;
21634            s.validate().unwrap_or_else(|e| {
21635                panic!(
21636                    "production-playbook pair retries={retries} \
21637                     max_failures={max_failures} must validate; got {e:?}"
21638                )
21639            });
21640        }
21641    }
21642
21643    #[test]
21644    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
21645        // Boundary pin: `max_failures == retries + 1` is the smallest
21646        // trip threshold that admits one client's exhausted retries
21647        // through completion (the R+1th failure — the last declared
21648        // retry — trips the breaker exactly as it completes, so
21649        // retries fully executed). The invariant is `>`, not `>=`,
21650        // stated in the coherent direction `max_failures > retries`.
21651        // Catches a future off-by-one tightening to
21652        // `max_failures > retries + 1` that would drift the accept set
21653        // away from the codified
21654        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
21655        // predicate.
21656        let mut s = three_member_spec();
21657        s.politicas.timeout = None;
21658        s.politicas.retries = Some(3);
21659        s.politicas.circuit_breaker = Some(CircuitBreaker {
21660            max_failures: 4,
21661            window: Duration::from_secs(60),
21662        });
21663        s.politicas.rate_limit = None;
21664        s.validate()
21665            .expect("max_failures == retries + 1 is the boundary accept case");
21666    }
21667
21668    #[test]
21669    fn rejects_retries_equal_to_breaker_trip_threshold() {
21670        // Off-by-one boundary pin: exactly at the trip threshold is
21671        // still structurally truncating (the invariant is `>`, so `<=`
21672        // refuses even the tight boundary). `retries = 3` with
21673        // `max_failures = 3` means the breaker trips on the third
21674        // failure — the last declared retry attempt is blocked.
21675        // Catches a future relaxation to `>=` that would silently
21676        // drift the accept boundary.
21677        let mut s = three_member_spec();
21678        s.politicas.timeout = None;
21679        s.politicas.retries = Some(3);
21680        s.politicas.circuit_breaker = Some(CircuitBreaker {
21681            max_failures: 3,
21682            window: Duration::from_secs(60),
21683        });
21684        s.politicas.rate_limit = None;
21685        assert_eq!(
21686            s.validate().unwrap_err(),
21687            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
21688                retries: 3,
21689                max_failures: 3,
21690            }
21691        );
21692    }
21693
21694    #[test]
21695    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
21696        // The predicate is vacuously `true` when `:retries` is None —
21697        // a `:circuit-breaker` alone declares a failure counter whose
21698        // per-client attempt count is unconstrained by the substrate,
21699        // so no per-client saturation bound on failures-per-client-call
21700        // is knowable at author time. The substrate takes no position
21701        // on whether an omitted `:retries` axis means zero retries or
21702        // "the client picks its own retry policy" — either way, the
21703        // pair is undeclared and the cross-axis gate has nothing to
21704        // check. Pin so a future tightening that made the gate
21705        // opinionated on half-declared pairs surfaces here.
21706        let mut s = three_member_spec();
21707        s.politicas.timeout = None;
21708        s.politicas.retries = None;
21709        s.politicas.circuit_breaker = Some(CircuitBreaker {
21710            max_failures: 1,
21711            window: Duration::from_secs(60),
21712        });
21713        s.politicas.rate_limit = None;
21714        s.validate().expect(
21715            "cross-axis retries gate must be vacuous when :retries is None, \
21716             however low :max-failures is",
21717        );
21718    }
21719
21720    #[test]
21721    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
21722        // Peer of the sibling `:retries`-absent case: a `:retries`
21723        // without a `:circuit-breaker` declares a client-retry policy
21724        // with no failure counter to trip, so the pair is undeclared
21725        // and the cross-axis gate has nothing to check.
21726        let mut s = three_member_spec();
21727        s.politicas.timeout = None;
21728        s.politicas.retries = Some(POLICY_RETRIES_MAX);
21729        s.politicas.circuit_breaker = None;
21730        s.politicas.rate_limit = None;
21731        s.validate().expect(
21732            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
21733             however high :retries is",
21734        );
21735    }
21736
21737    #[test]
21738    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
21739        // Ordering pin: a pair whose retries is *both* zero-floor-
21740        // violating and structurally at-or-below the trip threshold
21741        // must surface the per-axis zero-floor arm first — the
21742        // zero-floor diagnostic is more self-locating (its omit-axis
21743        // remediation is directly named), where the cross-axis arm
21744        // would send the author to reconcile two values one of which
21745        // is not a meaningful retry count at all. Same ordering
21746        // discipline every per-axis bracket carries internally
21747        // (zero-floor before canonical-form before cap), and the
21748        // sibling cross-axis
21749        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
21750        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
21751        let mut s = three_member_spec();
21752        s.politicas.timeout = None;
21753        s.politicas.retries = Some(0);
21754        s.politicas.circuit_breaker = Some(CircuitBreaker {
21755            max_failures: 3,
21756            window: Duration::from_secs(60),
21757        });
21758        s.politicas.rate_limit = None;
21759        assert_eq!(
21760            s.validate().unwrap_err(),
21761            AplicacaoError::PolicyRetriesZero,
21762            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
21763        );
21764    }
21765
21766    #[test]
21767    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
21768        // Cross-axis ordering pin: a `:politicas` whose axes trip
21769        // BOTH cross-axis arms — `:rate-limit` starves the breaker
21770        // within `:window` (the sibling
21771        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
21772        // `:retries + 1` saturates `:max-failures` (this arm) — must
21773        // surface the rate-limit-starve diagnostic first. The
21774        // rate-limit-starve arm reasons across the token-bucket
21775        // admission axis every rate-limited edge carries whether or
21776        // not `:retries` is declared, so its diagnostic is more
21777        // self-locating; the retries-saturate arm reasons across a
21778        // per-client retry-policy budget the starve arm does not
21779        // touch.
21780        //
21781        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
21782        // pair trips both: the rate structurally cannot deliver 5
21783        // failures per 10s breaker window, and simultaneously
21784        // one client's `retries + 1 = 6` attempts alone would
21785        // saturate the 5-`max_failures` threshold.
21786        let mut s = three_member_spec();
21787        s.politicas.timeout = None;
21788        s.politicas.retries = Some(5);
21789        s.politicas.circuit_breaker = Some(CircuitBreaker {
21790            max_failures: 5,
21791            window: Duration::from_secs(10),
21792        });
21793        s.politicas.rate_limit = Some(RateLimit {
21794            rate: 1,
21795            window: Duration::from_secs(3600),
21796        });
21797        assert_eq!(
21798            s.validate().unwrap_err(),
21799            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21800                rate: 1,
21801                rl_window: Duration::from_secs(3600),
21802                max_failures: 5,
21803                cb_window: Duration::from_secs(10),
21804            },
21805            "sibling :rate-limit-starve cross-axis arm must fire before the \
21806             retries-saturate arm when both apply"
21807        );
21808    }
21809
21810    #[test]
21811    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
21812        // Equivalence pin: the substrate-canonical
21813        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
21814        // predicate and the [`AplicacaoSpec::validate_politicas`]
21815        // cross-axis arm must discriminate the same set on every pair
21816        // covered by their shared invariant. A future refactor of
21817        // either side that breaks the equivalence trips here rather
21818        // than as a divergence between the predicate's Boolean answer
21819        // and the validate gate's Ok/Err arm — the same
21820        // predicate-vs-gate coherence discipline the sibling
21821        // [`MeshPolicy::breaker_window_observes_timeout`] and
21822        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
21823        // carry against `AplicacaoSpec::validate_politicas`. The
21824        // sweep covers both arms of the invariant (strictly below,
21825        // exactly at the boundary, strictly above) and both vacuous
21826        // arms (None `:retries`, None `:circuit-breaker`), so the
21827        // equivalence holds exhaustively over the axis-covered accept
21828        // and reject sets. Clears `:timeout` and `:rate-limit`
21829        // throughout so the sibling cross-axis arms are vacuous on
21830        // every input.
21831        let cb = |max_failures: u32| {
21832            Some(CircuitBreaker {
21833                max_failures,
21834                window: Duration::from_secs(60),
21835            })
21836        };
21837        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
21838            // saturating pairs (predicate = false, gate = Err)
21839            (Some(3), cb(3)),
21840            (Some(3), cb(1)),
21841            (Some(10), cb(5)),
21842            // boundary + coherent pairs (predicate = true, gate = Ok)
21843            (Some(3), cb(4)),
21844            (Some(1), cb(5)),
21845            (Some(3), cb(20)),
21846            // vacuous arms
21847            (None, cb(1)),
21848            (Some(10), None),
21849            (None, None),
21850        ];
21851        for (retries, circuit_breaker) in cases.iter().copied() {
21852            let politicas = MeshPolicy {
21853                retries,
21854                circuit_breaker,
21855                ..Default::default()
21856            };
21857            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
21858
21859            let mut s = three_member_spec();
21860            s.politicas = politicas.clone();
21861            let gate_ok = !matches!(
21862                s.validate(),
21863                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
21864            );
21865
21866            assert_eq!(
21867                predicate, gate_ok,
21868                "predicate must agree with validate arm on pair \
21869                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
21870            );
21871        }
21872    }
21873
21874    #[test]
21875    fn rejects_rate_limit_cannot_admit_retry_burst() {
21876        // The fail-before-pass-after pin on the cross-axis
21877        // `(:retries, :rate-limit)` invariant. Each axis is
21878        // individually well-formed under its own per-axis bracket (both
21879        // above the zero floor, both below the cap), but the pair is a
21880        // structurally-truncated retry policy: one client's
21881        // `retries + 1 = 6` failing attempts consume 6 tokens from a
21882        // bucket that admits at most 3 per refill window, so the fourth
21883        // attempt onward is 429ed by the local rate limiter and the
21884        // declared retry policy is silently truncated by the same rate
21885        // limiter it feeds through — the substrate declared six
21886        // attempts and structurally allows three.
21887        //
21888        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
21889        // against `retry_policy.num_retries` carries the identical
21890        // relation; every production playbook that pairs the two axes
21891        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
21892        // capacity strictly above any single client's retry budget so
21893        // the limiter distinguishes one client's declared retries from
21894        // sustained multi-client load.
21895        //
21896        // Pin both the diagnostic arm and the payload values so a
21897        // future re-shape of the arm surfaces here as a deliberate
21898        // test edit. Clears `:timeout` and `:circuit-breaker` so the
21899        // sibling cross-axis
21900        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
21901        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
21902        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
21903        // arms do not fire first on the ordering-precedent they hold
21904        // over this arm.
21905        let mut s = three_member_spec();
21906        s.politicas.timeout = None;
21907        s.politicas.retries = Some(5);
21908        s.politicas.circuit_breaker = None;
21909        s.politicas.rate_limit = Some(RateLimit {
21910            rate: 3,
21911            window: Duration::from_secs(1),
21912        });
21913        assert_eq!(
21914            s.validate().unwrap_err(),
21915            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
21916                retries: 5,
21917                rate: 3,
21918            }
21919        );
21920    }
21921
21922    #[test]
21923    fn accepts_rate_limit_admits_retry_burst() {
21924        // Positive-control sweep across the production-playbook band
21925        // — every pair a real playbook recommends where the bucket
21926        // capacity is strictly above the client's retry budget must
21927        // validate. Envoy default `num_retries: 3` with 100/s (100
21928        // tokens per window admits 4 attempts per client with 96 to
21929        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
21930        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
21931        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
21932        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
21933        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
21934        // arms are vacuous on this sweep.
21935        for (retries, rate, secs) in [
21936            (3u32, 100u32, 1u64),
21937            (3, 50, 1),
21938            (2, 10, 1),
21939            (5, 1000, 1),
21940            (3, 1_000_000, 3600),
21941            (10, POLICY_RATE_LIMIT_MAX, 1),
21942        ] {
21943            let mut s = three_member_spec();
21944            s.politicas.timeout = None;
21945            s.politicas.retries = Some(retries);
21946            s.politicas.circuit_breaker = None;
21947            s.politicas.rate_limit = Some(RateLimit {
21948                rate,
21949                window: Duration::from_secs(secs),
21950            });
21951            s.validate().unwrap_or_else(|e| {
21952                panic!(
21953                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
21954                     must validate; got {e:?}"
21955                )
21956            });
21957        }
21958    }
21959
21960    #[test]
21961    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
21962        // Boundary pin: `rate == retries + 1` is the smallest bucket
21963        // capacity that structurally admits one client's exhausted
21964        // retries through completion (each attempt draws exactly one
21965        // token; `retries + 1` tokens available admits `retries + 1`
21966        // attempts, retries fully executed). The invariant is `>=`,
21967        // stated in the coherent direction `rate >= retries + 1`.
21968        // Catches a future off-by-one tightening to `rate > retries + 1`
21969        // that would drift the accept set away from the codified
21970        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
21971        let mut s = three_member_spec();
21972        s.politicas.timeout = None;
21973        s.politicas.retries = Some(3);
21974        s.politicas.circuit_breaker = None;
21975        s.politicas.rate_limit = Some(RateLimit {
21976            rate: 4,
21977            window: Duration::from_secs(1),
21978        });
21979        s.validate()
21980            .expect("rate == retries + 1 is the boundary accept case");
21981    }
21982
21983    #[test]
21984    fn rejects_rate_one_below_retry_burst() {
21985        // Off-by-one boundary pin: exactly one token short of the
21986        // retry burst is still structurally truncating (the invariant
21987        // is `>=`, so `<` refuses even a one-token shortfall).
21988        // `retries = 3` with `rate = 3` means one client's four
21989        // attempts consume four tokens from a three-token bucket —
21990        // the fourth attempt is 429ed. Catches a future relaxation to
21991        // `>` on the wrong side (`rate > retries`, accepting equal)
21992        // that would silently drift the accept boundary and admit a
21993        // structurally-truncated retry policy at the emit boundary.
21994        let mut s = three_member_spec();
21995        s.politicas.timeout = None;
21996        s.politicas.retries = Some(3);
21997        s.politicas.circuit_breaker = None;
21998        s.politicas.rate_limit = Some(RateLimit {
21999            rate: 3,
22000            window: Duration::from_secs(1),
22001        });
22002        assert_eq!(
22003            s.validate().unwrap_err(),
22004            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22005                retries: 3,
22006                rate: 3,
22007            }
22008        );
22009    }
22010
22011    #[test]
22012    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
22013        // The predicate is vacuously `true` when `:retries` is None —
22014        // a `:rate-limit` alone declares a token-bucket rate whose
22015        // per-client attempt count is unconstrained by the substrate,
22016        // so no per-client saturation bound on tokens-per-client-call
22017        // is knowable at author time. The substrate takes no position
22018        // on whether an omitted `:retries` axis means zero retries or
22019        // "the client picks its own retry policy" — either way, the
22020        // pair is undeclared and the cross-axis gate has nothing to
22021        // check. Pin so a future tightening that made the gate
22022        // opinionated on half-declared pairs surfaces here.
22023        let mut s = three_member_spec();
22024        s.politicas.timeout = None;
22025        s.politicas.retries = None;
22026        s.politicas.circuit_breaker = None;
22027        s.politicas.rate_limit = Some(RateLimit {
22028            rate: 1,
22029            window: Duration::from_secs(1),
22030        });
22031        s.validate().expect(
22032            "cross-axis burst gate must be vacuous when :retries is None, \
22033             however low :rate is",
22034        );
22035    }
22036
22037    #[test]
22038    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
22039        // Peer of the sibling `:retries`-absent case: a `:retries`
22040        // without a `:rate-limit` declares a client-retry policy with
22041        // no rate limiter to saturate, so the pair is undeclared and
22042        // the cross-axis gate has nothing to check. Uses
22043        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
22044        // authored retry budget the per-axis cap admits — a `:retries
22045        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
22046        // or not `:rate-limit` is declared.
22047        let mut s = three_member_spec();
22048        s.politicas.timeout = None;
22049        s.politicas.retries = Some(POLICY_RETRIES_MAX);
22050        s.politicas.circuit_breaker = None;
22051        s.politicas.rate_limit = None;
22052        s.validate().expect(
22053            "cross-axis burst gate must be vacuous when :rate-limit is None, \
22054             however high :retries is",
22055        );
22056    }
22057
22058    #[test]
22059    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
22060        // Ordering pin: a pair whose retries is *both* zero-floor-
22061        // violating and structurally below the retry-burst threshold
22062        // must surface the per-axis zero-floor arm first — the
22063        // zero-floor diagnostic is more self-locating (its omit-axis
22064        // remediation is directly named), where the cross-axis arm
22065        // would send the author to reconcile two values one of which
22066        // is not a meaningful retry count at all. Same ordering
22067        // discipline every per-axis bracket carries internally
22068        // (zero-floor before canonical-form before cap), and the
22069        // sibling cross-axis
22070        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
22071        // ordering pin on the `(:retries, :max-failures)` pair.
22072        let mut s = three_member_spec();
22073        s.politicas.timeout = None;
22074        s.politicas.retries = Some(0);
22075        s.politicas.circuit_breaker = None;
22076        s.politicas.rate_limit = Some(RateLimit {
22077            rate: 1,
22078            window: Duration::from_secs(1),
22079        });
22080        assert_eq!(
22081            s.validate().unwrap_err(),
22082            AplicacaoError::PolicyRetriesZero,
22083            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
22084        );
22085    }
22086
22087    #[test]
22088    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
22089        // Cross-axis ordering pin: a `:politicas` whose axes trip
22090        // BOTH cross-axis arms — `:rate-limit` starves the breaker
22091        // within `:window` (the sibling
22092        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
22093        // `:retries + 1` exceeds the bucket capacity (this arm) —
22094        // must surface the rate-limit-starve diagnostic first. The
22095        // starve arm is the token-bucket admission invariant every
22096        // rate-limited edge carries against the breaker whether or
22097        // not `:retries` is declared, so its diagnostic is more
22098        // self-locating; the burst arm reasons across a per-client
22099        // retry-policy budget the starve arm does not touch. Same
22100        // "more foundational cross-axis first" ordering discipline the
22101        // sibling
22102        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
22103        // pin on the peer pair carries.
22104        //
22105        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
22106        // pair trips both: the rate structurally cannot deliver 5
22107        // failures per 10s breaker window (starve arm), and
22108        // simultaneously one client's `retries + 1 = 6` attempts alone
22109        // would exhaust the 1-token bucket (burst arm).
22110        let mut s = three_member_spec();
22111        s.politicas.timeout = None;
22112        s.politicas.retries = Some(5);
22113        s.politicas.circuit_breaker = Some(CircuitBreaker {
22114            max_failures: 5,
22115            window: Duration::from_secs(10),
22116        });
22117        s.politicas.rate_limit = Some(RateLimit {
22118            rate: 1,
22119            window: Duration::from_secs(3600),
22120        });
22121        assert_eq!(
22122            s.validate().unwrap_err(),
22123            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22124                rate: 1,
22125                rl_window: Duration::from_secs(3600),
22126                max_failures: 5,
22127                cb_window: Duration::from_secs(10),
22128            },
22129            "sibling :rate-limit-starve cross-axis arm must fire before the \
22130             burst arm when both apply"
22131        );
22132    }
22133
22134    #[test]
22135    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
22136        // Cross-axis ordering pin: a `:politicas` whose axes trip
22137        // BOTH the retries-saturate arm and this burst arm — one
22138        // client's `retries + 1` failures saturate the breaker's trip
22139        // threshold (the sibling
22140        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
22141        // `retries + 1` exceeds the bucket capacity (this arm) —
22142        // must surface the retries-saturate diagnostic first. The
22143        // saturate arm is the per-client-vs-breaker relation every
22144        // retry-with-breaker pair carries whether or not `:rate-limit`
22145        // is declared, so its diagnostic is more self-locating; the
22146        // burst arm reasons across the rate-limit token-bucket
22147        // admission axis the saturate arm does not touch. Same
22148        // "more foundational cross-axis first" ordering discipline
22149        // carries here.
22150        //
22151        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
22152        // rate: 3/s }` pair trips both: the breaker's `max_failures
22153        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
22154        // one client's `retries + 1 = 6` attempts alone would exhaust
22155        // the 3-token bucket (burst arm). Clears `:timeout` so the
22156        // sibling `:window<:timeout` gate is vacuous, and the
22157        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
22158        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
22159        // the arm that fires first.
22160        let mut s = three_member_spec();
22161        s.politicas.timeout = None;
22162        s.politicas.retries = Some(5);
22163        s.politicas.circuit_breaker = Some(CircuitBreaker {
22164            max_failures: 3,
22165            window: Duration::from_secs(60),
22166        });
22167        s.politicas.rate_limit = Some(RateLimit {
22168            rate: 3,
22169            window: Duration::from_secs(1),
22170        });
22171        assert_eq!(
22172            s.validate().unwrap_err(),
22173            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22174                retries: 5,
22175                max_failures: 3,
22176            },
22177            "sibling :retries-saturate cross-axis arm must fire before the \
22178             burst arm when both apply"
22179        );
22180    }
22181
22182    #[test]
22183    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
22184        // Equivalence pin: the substrate-canonical
22185        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
22186        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
22187        // must discriminate the same set on every pair covered by
22188        // their shared invariant. A future refactor of either side
22189        // that breaks the equivalence trips here rather than as a
22190        // divergence between the predicate's Boolean answer and the
22191        // validate gate's Ok/Err arm — the same predicate-vs-gate
22192        // coherence discipline the three sibling cross-axis
22193        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
22194        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
22195        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
22196        // carry against `AplicacaoSpec::validate_politicas`. The sweep
22197        // covers both arms of the invariant (strictly below, exactly
22198        // at the boundary, strictly above) and both vacuous arms
22199        // (None `:retries`, None `:rate-limit`), so the equivalence
22200        // holds exhaustively over the axis-covered accept and reject
22201        // sets. Clears `:timeout` and `:circuit-breaker` throughout
22202        // so the three sibling cross-axis arms are vacuous on every
22203        // input.
22204        let rl = |rate: u32, secs: u64| {
22205            Some(RateLimit {
22206                rate,
22207                window: Duration::from_secs(secs),
22208            })
22209        };
22210        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
22211            // burst-exceeding pairs (predicate = false, gate = Err)
22212            (Some(3), rl(3, 1)),
22213            (Some(5), rl(1, 1)),
22214            (Some(10), rl(5, 1)),
22215            // boundary + coherent pairs (predicate = true, gate = Ok)
22216            (Some(3), rl(4, 1)),
22217            (Some(1), rl(5, 1)),
22218            (Some(3), rl(1_000_000, 3600)),
22219            // vacuous arms
22220            (None, rl(1, 1)),
22221            (Some(10), None),
22222            (None, None),
22223        ];
22224        for (retries, rate_limit) in cases.iter().copied() {
22225            let politicas = MeshPolicy {
22226                retries,
22227                rate_limit,
22228                ..Default::default()
22229            };
22230            let predicate = politicas.rate_limit_admits_retry_burst();
22231
22232            let mut s = three_member_spec();
22233            s.politicas = politicas.clone();
22234            let gate_ok = !matches!(
22235                s.validate(),
22236                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
22237            );
22238
22239            assert_eq!(
22240                predicate, gate_ok,
22241                "predicate must agree with validate arm on pair \
22242                 (retries={retries:?}, rate_limit={rate_limit:?})"
22243            );
22244        }
22245    }
22246
22247    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
22248    /// equivalence pin — assert that on each `(label, politicas,
22249    /// expected)` case the substrate-canonical fold and the validate
22250    /// cascade agree byte-for-byte. Extracted so each pin's own body
22251    /// stays under `clippy::too_many_lines`.
22252    fn assert_first_cross_axis_violation_agrees_with_gate(
22253        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
22254    ) {
22255        for (label, politicas, expected) in cases {
22256            let fold = politicas.first_cross_axis_violation();
22257            assert_eq!(
22258                fold.as_ref(),
22259                expected.as_ref(),
22260                "fold must return {expected:?} on `{label}`; got {fold:?}"
22261            );
22262
22263            let mut s = three_member_spec();
22264            s.politicas = politicas.clone();
22265            let gate = s.validate();
22266            match expected {
22267                None => {
22268                    // No cross-axis violation: validate must pass (the
22269                    // per-axis brackets pass by construction on every
22270                    // fixture above; every fixture's non-`:politicas`
22271                    // slots come from `three_member_spec`).
22272                    gate.as_ref()
22273                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
22274                }
22275                Some(want) => {
22276                    let got =
22277                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
22278                    assert_eq!(
22279                        &got, want,
22280                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
22281                    );
22282                }
22283            }
22284        }
22285    }
22286
22287    #[test]
22288    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
22289        // Equivalence pin on the compound cross-axis fold: the
22290        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
22291        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
22292        // cascade must return identical `AplicacaoError` variants on
22293        // every axis-covered input — the "compound-fold ≡ gate"
22294        // contract that generalizes the four sibling per-arm pins
22295        // onto the compound primitive that folds all four. A future
22296        // refactor of either side that breaks the equivalence trips
22297        // here rather than as a divergence between what the substrate
22298        // primitive answers and what `feira build` accepts.
22299        //
22300        // Half-A of the sweep: every single-arm violation (one arm
22301        // fires with the three sibling arms vacuous), the vacuous
22302        // shape (empty policy — no arm fires), and the fully-coherent
22303        // shape (every axis declared inside the coherence surface —
22304        // no arm fires). Half-B (pairwise-ordering coverage — the
22305        // "which arm wins when two apply" contract) lives in the
22306        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
22307        // pin; splitting keeps each pin's body under
22308        // `clippy::too_many_lines`.
22309        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
22310            max_failures,
22311            window: Duration::from_secs(secs),
22312        };
22313        let rl = |rate: u32, secs: u64| RateLimit {
22314            rate,
22315            window: Duration::from_secs(secs),
22316        };
22317        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22318            (
22319                "window-below-timeout only",
22320                MeshPolicy {
22321                    timeout: Some(Duration::from_secs(30)),
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 only",
22332                MeshPolicy {
22333                    rate_limit: Some(rl(1, 3600)),
22334                    circuit_breaker: Some(cb(5, 10)),
22335                    ..Default::default()
22336                },
22337                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22338                    rate: 1,
22339                    rl_window: Duration::from_secs(3600),
22340                    max_failures: 5,
22341                    cb_window: Duration::from_secs(10),
22342                }),
22343            ),
22344            (
22345                "retries-saturate only",
22346                MeshPolicy {
22347                    retries: Some(3),
22348                    circuit_breaker: Some(cb(3, 60)),
22349                    ..Default::default()
22350                },
22351                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22352                    retries: 3,
22353                    max_failures: 3,
22354                }),
22355            ),
22356            (
22357                "retries-burst only",
22358                MeshPolicy {
22359                    retries: Some(5),
22360                    rate_limit: Some(rl(3, 1)),
22361                    ..Default::default()
22362                },
22363                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22364                    retries: 5,
22365                    rate: 3,
22366                }),
22367            ),
22368            ("empty policy", MeshPolicy::default(), None),
22369            (
22370                "fully-coherent policy",
22371                MeshPolicy {
22372                    timeout: Some(Duration::from_secs(30)),
22373                    retries: Some(3),
22374                    circuit_breaker: Some(cb(5, 60)),
22375                    mtls_required: Some(true),
22376                    rate_limit: Some(rl(100, 1)),
22377                },
22378                None,
22379            ),
22380        ];
22381        assert_first_cross_axis_violation_agrees_with_gate(cases);
22382    }
22383
22384    #[test]
22385    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
22386        // Half-B of the compound-fold ≡ gate equivalence pin: the
22387        // load-bearing pairwise-ordering coverage. Every ordered pair
22388        // of the four cross-axis arms — six combinations — where two
22389        // arms are simultaneously eligible must surface the
22390        // more-foundational arm's diagnostic verbatim. Pins the fold's
22391        // arm-ordering byte-for-byte against the validate cascade's
22392        // arm-ordering, so a future reshuffle of either side that
22393        // silently drifts the ordering trips here rather than as a
22394        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
22395        // pins cannot catch (they clear every sibling arm, so their
22396        // sweeps are pairwise-ordering-agnostic by construction).
22397        //
22398        // The six pairs the four-arm cascade admits:
22399        // window-before-starve, window-before-saturate,
22400        // window-before-burst, starve-before-saturate,
22401        // starve-before-burst, saturate-before-burst.
22402        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
22403            max_failures,
22404            window: Duration::from_secs(secs),
22405        };
22406        let rl = |rate: u32, secs: u64| RateLimit {
22407            rate,
22408            window: Duration::from_secs(secs),
22409        };
22410        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22411            (
22412                "window+starve → window wins",
22413                MeshPolicy {
22414                    timeout: Some(Duration::from_secs(30)),
22415                    rate_limit: Some(rl(1, 3600)),
22416                    circuit_breaker: Some(cb(5, 10)),
22417                    ..Default::default()
22418                },
22419                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22420                    window: Duration::from_secs(10),
22421                    timeout: Duration::from_secs(30),
22422                }),
22423            ),
22424            (
22425                "window+retries-saturate → window wins",
22426                MeshPolicy {
22427                    timeout: Some(Duration::from_secs(30)),
22428                    retries: Some(5),
22429                    circuit_breaker: Some(cb(3, 10)),
22430                    ..Default::default()
22431                },
22432                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22433                    window: Duration::from_secs(10),
22434                    timeout: Duration::from_secs(30),
22435                }),
22436            ),
22437            (
22438                "window+retries-burst → window wins",
22439                MeshPolicy {
22440                    timeout: Some(Duration::from_secs(30)),
22441                    retries: Some(5),
22442                    rate_limit: Some(rl(3, 1)),
22443                    circuit_breaker: Some(cb(5, 10)),
22444                    ..Default::default()
22445                },
22446                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22447                    window: Duration::from_secs(10),
22448                    timeout: Duration::from_secs(30),
22449                }),
22450            ),
22451            (
22452                "starve+retries-saturate → starve wins",
22453                MeshPolicy {
22454                    retries: Some(5),
22455                    rate_limit: Some(rl(1, 3600)),
22456                    circuit_breaker: Some(cb(5, 10)),
22457                    ..Default::default()
22458                },
22459                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22460                    rate: 1,
22461                    rl_window: Duration::from_secs(3600),
22462                    max_failures: 5,
22463                    cb_window: Duration::from_secs(10),
22464                }),
22465            ),
22466            (
22467                "starve+retries-burst → starve wins",
22468                MeshPolicy {
22469                    retries: Some(5),
22470                    rate_limit: Some(rl(1, 3600)),
22471                    circuit_breaker: Some(cb(10, 10)),
22472                    ..Default::default()
22473                },
22474                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22475                    rate: 1,
22476                    rl_window: Duration::from_secs(3600),
22477                    max_failures: 10,
22478                    cb_window: Duration::from_secs(10),
22479                }),
22480            ),
22481            (
22482                "retries-saturate+retries-burst → saturate wins",
22483                MeshPolicy {
22484                    retries: Some(5),
22485                    rate_limit: Some(rl(3, 1)),
22486                    circuit_breaker: Some(cb(3, 60)),
22487                    ..Default::default()
22488                },
22489                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22490                    retries: 5,
22491                    max_failures: 3,
22492                }),
22493            ),
22494        ];
22495        assert_first_cross_axis_violation_agrees_with_gate(cases);
22496    }
22497
22498    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
22499    /// equivalence pin — assert that on each `(label, politicas,
22500    /// expected)` case both the substrate primitive
22501    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
22502    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
22503    /// same `three_member_spec` fixture whose non-`:politicas` slots
22504    /// always validate cleanly) return identical `AplicacaoError` variants.
22505    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
22506    /// the sibling cross-axis-only surface — extended here onto the
22507    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
22508    /// own body stays under `clippy::too_many_lines`.
22509    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
22510        for (label, politicas, expected) in cases {
22511            let direct = politicas.validate();
22512            match (expected, &direct) {
22513                (None, Ok(())) => {}
22514                (None, Err(got)) => {
22515                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
22516                }
22517                (Some(want), Ok(())) => {
22518                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
22519                }
22520                (Some(want), Err(got)) => assert_eq!(
22521                    got, want,
22522                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
22523                ),
22524            }
22525
22526            let mut s = three_member_spec();
22527            s.politicas = politicas.clone();
22528            let gate = s.validate();
22529            match (expected, &gate) {
22530                (None, Ok(())) => {}
22531                (None, Err(got)) => {
22532                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
22533                }
22534                (Some(want), Ok(())) => {
22535                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
22536                }
22537                (Some(want), Err(got)) => assert_eq!(
22538                    got, want,
22539                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
22540                ),
22541            }
22542        }
22543    }
22544
22545    #[test]
22546    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
22547        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
22548        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
22549        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
22550        // :max-failures`, `:rate-limit` rate) that discriminate the
22551        // "per-axis phase fires" arm of the compound gate, plus one
22552        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
22553        // ZERO }`) that pins the phase-boundary ordering — the per-axis
22554        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
22555        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
22556        // diagnostic wins over the window-below-timeout diagnostic. Peer
22557        // of the sibling
22558        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
22559        // + `_on_pairwise_orderings` pins on the compound cross-axis
22560        // fold, extended here onto the outer compound entry gate that
22561        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
22562        // clean-pass surfaces) lives in the sibling
22563        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
22564        // pin; splitting keeps each pin's body under
22565        // `clippy::too_many_lines`.
22566        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22567            (
22568                "per-axis: timeout zero",
22569                MeshPolicy {
22570                    timeout: Some(Duration::ZERO),
22571                    ..Default::default()
22572                },
22573                Some(AplicacaoError::PolicyTimeoutZero),
22574            ),
22575            (
22576                "per-axis: retries zero",
22577                MeshPolicy {
22578                    retries: Some(0),
22579                    ..Default::default()
22580                },
22581                Some(AplicacaoError::PolicyRetriesZero),
22582            ),
22583            (
22584                "per-axis: breaker max-failures zero",
22585                MeshPolicy {
22586                    circuit_breaker: Some(CircuitBreaker {
22587                        max_failures: 0,
22588                        window: Duration::from_secs(60),
22589                    }),
22590                    ..Default::default()
22591                },
22592                Some(AplicacaoError::PolicyBreakerZeroFailures),
22593            ),
22594            (
22595                "per-axis: rate-limit rate zero",
22596                MeshPolicy {
22597                    rate_limit: Some(RateLimit {
22598                        rate: 0,
22599                        window: Duration::from_secs(1),
22600                    }),
22601                    ..Default::default()
22602                },
22603                Some(AplicacaoError::PolicyRateLimitZero),
22604            ),
22605            (
22606                "per-axis before cross-axis: zero-window wins over window-below-timeout",
22607                MeshPolicy {
22608                    timeout: Some(Duration::from_secs(30)),
22609                    circuit_breaker: Some(CircuitBreaker {
22610                        max_failures: 5,
22611                        window: Duration::ZERO,
22612                    }),
22613                    ..Default::default()
22614                },
22615                Some(AplicacaoError::PolicyBreakerZeroWindow),
22616            ),
22617        ];
22618        assert_validate_matches_gate(cases);
22619    }
22620
22621    #[test]
22622    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
22623        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
22624        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
22625        // arm that discriminates the "cross-axis phase fires" arm of
22626        // the compound gate (window-below-timeout — sibling per-arm
22627        // coverage lives in the two
22628        // `first_cross_axis_violation_matches_gate_on_*` pins above),
22629        // plus the two clean-pass shapes (empty policy — every axis
22630        // absent — and fully-coherent — every axis inside the coherence
22631        // surface) that pin the compound gate's `Ok(())` arm. Half-A
22632        // (per-axis + phase-boundary surfaces) lives in the sibling
22633        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
22634        // pin; splitting keeps each pin's body under
22635        // `clippy::too_many_lines`.
22636        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22637            (
22638                "cross-axis: window-below-timeout",
22639                MeshPolicy {
22640                    timeout: Some(Duration::from_secs(30)),
22641                    circuit_breaker: Some(CircuitBreaker {
22642                        max_failures: 5,
22643                        window: Duration::from_secs(10),
22644                    }),
22645                    ..Default::default()
22646                },
22647                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22648                    window: Duration::from_secs(10),
22649                    timeout: Duration::from_secs(30),
22650                }),
22651            ),
22652            ("clean pass: empty policy", MeshPolicy::default(), None),
22653            (
22654                "clean pass: every axis coherent",
22655                MeshPolicy {
22656                    timeout: Some(Duration::from_secs(30)),
22657                    retries: Some(3),
22658                    circuit_breaker: Some(CircuitBreaker {
22659                        max_failures: 5,
22660                        window: Duration::from_secs(60),
22661                    }),
22662                    mtls_required: Some(true),
22663                    rate_limit: Some(RateLimit {
22664                        rate: 100,
22665                        window: Duration::from_secs(1),
22666                    }),
22667                },
22668                None,
22669            ),
22670        ];
22671        assert_validate_matches_gate(cases);
22672    }
22673
22674    #[test]
22675    fn empty_politicas_validates() {
22676        // Omitting every policy axis is fine — defaults express "no
22677        // policy on this axis", not "policy = 0". The fixture's typical
22678        // values continue to validate; this test pins that
22679        // MeshPolicy::default() is a clean pass through validate().
22680        let mut s = three_member_spec();
22681        s.politicas = MeshPolicy::default();
22682        s.validate().unwrap();
22683    }
22684
22685    #[test]
22686    fn typical_politicas_validates_with_every_axis_set() {
22687        // The full §III.1 example block (timeout + retries + breaker +
22688        // mtls + rate-limit) — every axis nonzero — must remain a
22689        // clean pass.
22690        let mut s = three_member_spec();
22691        s.politicas = MeshPolicy {
22692            timeout: Some(Duration::from_secs(30)),
22693            retries: Some(3),
22694            circuit_breaker: Some(CircuitBreaker {
22695                max_failures: 5,
22696                window: Duration::from_secs(60),
22697            }),
22698            mtls_required: Some(true),
22699            rate_limit: Some(RateLimit {
22700                rate: 100,
22701                window: Duration::from_secs(1),
22702            }),
22703        };
22704        s.validate().unwrap();
22705    }
22706
22707    #[test]
22708    fn rejects_empty_cluster_name() {
22709        let mut s = three_member_spec();
22710        s.placement.clusters = vec!["rio".into(), String::new()];
22711        assert_eq!(
22712            s.validate().unwrap_err(),
22713            AplicacaoError::PlacementClusterEmpty
22714        );
22715    }
22716
22717    #[test]
22718    fn rejects_duplicate_cluster_names() {
22719        let mut s = three_member_spec();
22720        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
22721        let err = s.validate().unwrap_err();
22722        assert!(
22723            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
22724            "got {err:?}"
22725        );
22726    }
22727
22728    #[test]
22729    fn rejects_placement_cluster_with_uppercase() {
22730        // The canonical "I copied the cluster's display name verbatim"
22731        // typo — K8s context names are lowercase per DNS-1123 label
22732        // rule, but org docs often round-trip a TitleCase identifier
22733        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
22734        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
22735        // on the peer name axis.
22736        let mut s = three_member_spec();
22737        s.placement.clusters = vec!["Rio".into(), "mar".into()];
22738        let err = s.validate().unwrap_err();
22739        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22740            panic!("expected PlacementClusterInvalid, got other variant");
22741        };
22742        assert_eq!(cluster, "Rio");
22743        assert!(
22744            reason.contains("uppercase"),
22745            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
22746        );
22747        assert!(
22748            reason.contains("\"rio\""),
22749            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
22750        );
22751    }
22752
22753    #[test]
22754    fn rejects_placement_cluster_with_underscore() {
22755        // The canonical "I'm thinking of an env var / hostname slug"
22756        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
22757        // schema. K8s context filtering on `my_cluster` silently misses
22758        // the cluster the author intended; the gate moves it to caixa-
22759        // build time. Same shape as `rejects_membro_caixa_with_underscore`
22760        // (3f9d7a0).
22761        let mut s = three_member_spec();
22762        s.placement.clusters = vec!["my_cluster".into()];
22763        let err = s.validate().unwrap_err();
22764        assert!(
22765            matches!(
22766                err,
22767                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22768                    if cluster == "my_cluster" && reason.contains('_')
22769            ),
22770            "got {err:?}"
22771        );
22772    }
22773
22774    #[test]
22775    fn rejects_placement_cluster_with_dot() {
22776        // A `:placement :clusters` entry is a single DNS-1123 *label*,
22777        // not a subdomain — even though K8s context names sometimes
22778        // carry a dotted form via kubeconfig conventions, the strictest
22779        // floor among the use sites (DNS-1035 cluster.x-k8s.io
22780        // `metadata.name`, Cilium identity label values) wins. The "I
22781        // want to namespace my cluster names with `.`" intent is
22782        // expressed via `-` (`mar-east`).
22783        let mut s = three_member_spec();
22784        s.placement.clusters = vec!["team.rio".into()];
22785        let err = s.validate().unwrap_err();
22786        assert!(
22787            matches!(
22788                err,
22789                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22790                    if cluster == "team.rio" && reason.contains('.')
22791            ),
22792            "got {err:?}"
22793        );
22794    }
22795
22796    #[test]
22797    fn rejects_placement_cluster_with_leading_hyphen() {
22798        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
22799        // with an alphanumeric. The K8s apiserver rejects `-rio`
22800        // outright; the rendered fan-out would emit a `metadata.name:
22801        // "-rio"` that fails admission far from the source caixa.lisp.
22802        let mut s = three_member_spec();
22803        s.placement.clusters = vec!["-rio".into()];
22804        let err = s.validate().unwrap_err();
22805        assert!(
22806            matches!(
22807                err,
22808                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
22809                    if cluster == "-rio" && reason.contains("start and end")
22810            ),
22811            "got {err:?}"
22812        );
22813    }
22814
22815    #[test]
22816    fn rejects_placement_cluster_with_trailing_hyphen() {
22817        // The symmetric arm of the boundary rule. Pin separately so
22818        // both ends are covered against a future relaxation that only
22819        // checks one boundary (parallel to
22820        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
22821        let mut s = three_member_spec();
22822        s.placement.clusters = vec!["rio-".into()];
22823        let err = s.validate().unwrap_err();
22824        assert!(
22825            matches!(
22826                err,
22827                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22828                    if cluster == "rio-"
22829            ),
22830            "got {err:?}"
22831        );
22832    }
22833
22834    #[test]
22835    fn rejects_placement_cluster_with_unicode() {
22836        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
22837        // before it reaches K8s. The byte-by-byte ASCII validity check
22838        // rejects multi-byte UTF-8 sequences by the first byte that
22839        // fails `[a-z0-9-]`.
22840        let mut s = three_member_spec();
22841        s.placement.clusters = vec!["rió".into()];
22842        let err = s.validate().unwrap_err();
22843        assert!(
22844            matches!(
22845                err,
22846                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22847                    if cluster == "rió"
22848            ),
22849            "got {err:?}"
22850        );
22851    }
22852
22853    #[test]
22854    fn rejects_placement_cluster_with_whitespace() {
22855        // Whitespace is the canonical "I pasted from a sketch / doc"
22856        // footgun. The apiserver rejects every cluster `metadata.name`
22857        // value carrying whitespace.
22858        let mut s = three_member_spec();
22859        s.placement.clusters = vec!["rio cluster".into()];
22860        let err = s.validate().unwrap_err();
22861        assert!(
22862            matches!(
22863                err,
22864                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
22865                    if cluster == "rio cluster"
22866            ),
22867            "got {err:?}"
22868        );
22869    }
22870
22871    #[test]
22872    fn rejects_placement_cluster_too_long() {
22873        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
22874        // pin. The diagnostic names both the cap (63) and the actual
22875        // length so the author can shorten in one edit. Mirrors
22876        // `rejects_membro_caixa_too_long` (3f9d7a0).
22877        let mut s = three_member_spec();
22878        let too_long = "a".repeat(64);
22879        s.placement.clusters = vec![too_long.clone()];
22880        let err = s.validate().unwrap_err();
22881        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22882            panic!("expected PlacementClusterInvalid");
22883        };
22884        assert_eq!(cluster, too_long);
22885        assert!(
22886            reason.contains("63") && reason.contains("64"),
22887            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
22888        );
22889    }
22890
22891    #[test]
22892    fn placement_cluster_max_length_validates() {
22893        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
22894        // future tightening (e.g. dropping to 62) surfaces here as a
22895        // regression, mirroring `membro_caixa_max_length_validates`
22896        // (3f9d7a0).
22897        let mut s = three_member_spec();
22898        s.placement.clusters = vec!["a".repeat(63)];
22899        s.validate().unwrap();
22900    }
22901
22902    #[test]
22903    fn accepts_canonical_placement_cluster_forms() {
22904        // The DNS-1123 label shapes a caixa author is realistically
22905        // going to write for cluster names: single-word lowercase
22906        // (`rio`), regional hyphen-joined (`mar-east`), single
22907        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
22908        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
22909        // Pin every leg so a future tightening that bans (e.g.) digit-
22910        // start identifiers surfaces here.
22911        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
22912            let mut s = three_member_spec();
22913            s.placement.clusters = vec![form.into()];
22914            s.validate().unwrap_or_else(|e| {
22915                panic!("canonical cluster form {form:?} must validate, got {e:?}")
22916            });
22917        }
22918    }
22919
22920    #[test]
22921    fn placement_cluster_empty_takes_precedence_over_invalid() {
22922        // Order pin: the existing `PlacementClusterEmpty` diagnostic
22923        // (which doesn't try to parse) fires before the new
22924        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
22925        // `:clusters` entry keeps its narrower error message — the new
22926        // gate would also reject `""`, but the empty-string arm is the
22927        // more self-locating diagnostic. Mirrors the
22928        // `membro_caixa_empty_takes_precedence_over_invalid` pin
22929        // (3f9d7a0).
22930        let mut s = three_member_spec();
22931        s.placement.clusters = vec!["rio".into(), String::new()];
22932        let err = s.validate().unwrap_err();
22933        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
22934    }
22935
22936    #[test]
22937    fn placement_cluster_invalid_fires_before_duplicate_check() {
22938        // Order pin: a malformed-shape `:clusters` entry surfaces *its
22939        // own* diagnostic, even when a later entry would otherwise
22940        // collapse onto a duplicate name. The per-entry shape gate runs
22941        // inline before the duplicate-key insert, parallel to
22942        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
22943        let mut s = three_member_spec();
22944        s.placement.clusters = vec!["Rio".into(), "rio".into()];
22945        let err = s.validate().unwrap_err();
22946        assert!(
22947            matches!(
22948                err,
22949                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
22950            ),
22951            "got {err:?}"
22952        );
22953    }
22954
22955    #[test]
22956    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
22957        // The diagnostic-shape pin: the error names the offending
22958        // `:clusters` value verbatim so the author can grep their
22959        // caixa.lisp without re-running the build, and carries a
22960        // non-empty `reason` naming the specific violation. Same shape
22961        // every typed-shape gate enshrines
22962        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
22963        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
22964        let mut s = three_member_spec();
22965        s.placement.clusters = vec!["BAD_CLUSTER".into()];
22966        let err = s.validate().unwrap_err();
22967        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
22968            panic!("expected PlacementClusterInvalid");
22969        };
22970        assert_eq!(cluster, "BAD_CLUSTER");
22971        assert!(
22972            !reason.is_empty(),
22973            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
22974        );
22975    }
22976
22977    #[test]
22978    fn rejects_sharded_with_empty_clusters() {
22979        // §III.1: Sharded uses :clusters as the shard pool. An empty
22980        // pool means "shard across no clusters" — meaningless, same as
22981        // Replicated with no hosts.
22982        let mut s = three_member_spec();
22983        s.placement.estrategia = PlacementStrategy::Sharded;
22984        s.placement.shard_key = Some("$tenantId".into());
22985        s.placement.clusters = vec![];
22986        assert!(matches!(
22987            s.validate().unwrap_err(),
22988            AplicacaoError::PlacementWithoutClusters {
22989                estrategia: PlacementStrategy::Sharded
22990            }
22991        ));
22992    }
22993
22994    #[test]
22995    fn rejects_sharded_with_empty_shard_key() {
22996        let mut s = three_member_spec();
22997        s.placement.estrategia = PlacementStrategy::Sharded;
22998        s.placement.shard_key = Some(String::new());
22999        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
23000    }
23001
23002    #[test]
23003    fn rejects_shard_key_under_replicated_strategy() {
23004        // The fail-before-pass-after pin: a `:placement (:estrategia
23005        // Replicated :shard-key "tenantId")` manifest carries the
23006        // hash-keyed-distribution slot on a strategy that never consumes
23007        // it. Before the gate the typed slot's value silently vanished
23008        // at the renderer layer (caixa-mesh emits `placement.shardKey`
23009        // verbatim regardless of strategy; the Akka-style cluster-
23010        // sharding reconciler keys off `estrategia == Sharded` and
23011        // ignores the slot otherwise), with no diagnostic. Lifting the
23012        // rejection to a build-time gate makes the
23013        // `shard_key.is_some() == matches!(estrategia, Sharded)`
23014        // partition a structural property of every validated
23015        // [`Placement`].
23016        let mut s = three_member_spec();
23017        // The fixture already uses Replicated; just add a shard-key.
23018        s.placement.shard_key = Some("$tenantId".into());
23019        let err = s.validate().unwrap_err();
23020        let AplicacaoError::ShardKeyOnNonSharded {
23021            estrategia,
23022            shard_key,
23023        } = err
23024        else {
23025            panic!("expected ShardKeyOnNonSharded, got {err:?}");
23026        };
23027        assert_eq!(estrategia, PlacementStrategy::Replicated);
23028        assert_eq!(shard_key, "$tenantId");
23029    }
23030
23031    #[test]
23032    fn rejects_shard_key_under_singlenode_strategy() {
23033        // Peer of the Replicated case above on the SingleNode arm: OTP
23034        // distributed-app takeover (one cluster runs at a time) has no
23035        // hash-keyed routing axis to consume `:shard-key` either, so
23036        // the rejection fires on both non-Sharded arms uniformly.
23037        let mut s = three_member_spec();
23038        s.placement.estrategia = PlacementStrategy::SingleNode;
23039        s.placement.shard_key = Some("$tenantId".into());
23040        let err = s.validate().unwrap_err();
23041        let AplicacaoError::ShardKeyOnNonSharded {
23042            estrategia,
23043            shard_key,
23044        } = err
23045        else {
23046            panic!("expected ShardKeyOnNonSharded, got {err:?}");
23047        };
23048        assert_eq!(estrategia, PlacementStrategy::SingleNode);
23049        assert_eq!(shard_key, "$tenantId");
23050    }
23051
23052    #[test]
23053    fn rejects_empty_shard_key_under_replicated_strategy() {
23054        // The `Some("")` case under non-Sharded is rejected by
23055        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
23056        // fires before the empty-value gate), not
23057        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
23058        // the `Sharded` arm). Pin the partition so a future reorder of
23059        // the validate_placement match arms doesn't silently swap which
23060        // diagnostic the author sees — both are author errors, but
23061        // ShardKeyOnNonSharded names which strategy is the actual fix
23062        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
23063        // only says "pick a non-empty key".
23064        let mut s = three_member_spec();
23065        s.placement.shard_key = Some(String::new());
23066        let err = s.validate().unwrap_err();
23067        assert!(
23068            matches!(
23069                err,
23070                AplicacaoError::ShardKeyOnNonSharded {
23071                    estrategia: PlacementStrategy::Replicated,
23072                    ref shard_key,
23073                } if shard_key.is_empty()
23074            ),
23075            "got {err:?}"
23076        );
23077    }
23078
23079    #[test]
23080    fn replicated_without_shard_key_validates() {
23081        // The complement of the rejection: `:placement :estrategia
23082        // Replicated` with `:shard-key None` is the canonical happy
23083        // path on every existing fixture. Pin the no-shard-key case so
23084        // the new gate doesn't accidentally fire on `None`.
23085        let mut s = three_member_spec();
23086        assert!(matches!(
23087            s.placement.estrategia,
23088            PlacementStrategy::Replicated
23089        ));
23090        s.placement.shard_key = None;
23091        s.validate().unwrap();
23092    }
23093
23094    #[test]
23095    fn singlenode_without_shard_key_validates() {
23096        // Peer of the Replicated no-shard-key case on the SingleNode
23097        // arm — both non-Sharded strategies must validate cleanly when
23098        // the slot is omitted.
23099        let mut s = three_member_spec();
23100        s.placement.estrategia = PlacementStrategy::SingleNode;
23101        s.placement.shard_key = None;
23102        s.validate().unwrap();
23103    }
23104
23105    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
23106        // Fixture builder for the `:placement :shard-key` shape gate
23107        // tests: a three-member Aplicacao on the `Sharded` strategy
23108        // with the supplied `:shard-key` slot. Co-locates the
23109        // arm-construction so every test below carries one line of
23110        // setup (the offending `:shard-key` value) and the assertion.
23111        let mut s = three_member_spec();
23112        s.placement.estrategia = PlacementStrategy::Sharded;
23113        s.placement.shard_key = Some(key.into());
23114        s
23115    }
23116
23117    #[test]
23118    fn rejects_shard_key_with_embedded_space() {
23119        // The canonical paste-from-aligned-doc footgun:
23120        // `:shard-key "$tenant Id"` — the Akka-style entity-id
23121        // extractor reads the slot as a single-token reference, and an
23122        // embedded space breaks the token boundary at the runtime
23123        // hash-extractor pass with no diagnostic naming the offending
23124        // entry.
23125        let s = sharded_spec_with_key("$tenant Id");
23126        let err = s.validate().unwrap_err();
23127        assert!(
23128            matches!(
23129                err,
23130                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23131                    if shard_key == "$tenant Id" && reason.contains("space")
23132            ),
23133            "got {err:?}"
23134        );
23135    }
23136
23137    #[test]
23138    fn rejects_shard_key_with_leading_space() {
23139        // Leading-space arm of the embedded-whitespace footgun — the
23140        // paste-from-aligned-doc / paste-from-CSV-cell variant where
23141        // the leading column-padding leaked into the slot.
23142        let s = sharded_spec_with_key(" $tenantId");
23143        let err = s.validate().unwrap_err();
23144        assert!(
23145            matches!(
23146                err,
23147                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
23148                    if shard_key == " $tenantId"
23149            ),
23150            "got {err:?}"
23151        );
23152    }
23153
23154    #[test]
23155    fn rejects_shard_key_with_trailing_newline() {
23156        // The canonical paste-from-shell-heredoc footgun — every
23157        // `<<EOF` heredoc terminator paste leaves a trailing newline
23158        // the YAML emitter then folds away inconsistently across
23159        // emitter implementations.
23160        let s = sharded_spec_with_key("$tenantId\n");
23161        let err = s.validate().unwrap_err();
23162        assert!(
23163            matches!(
23164                err,
23165                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23166                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
23167            ),
23168            "got {err:?}"
23169        );
23170    }
23171
23172    #[test]
23173    fn rejects_shard_key_with_embedded_tab() {
23174        // The paste-from-aligned-doc tab-stop variant — tabs land
23175        // alongside spaces in copy-paste from formatted columns.
23176        let s = sharded_spec_with_key("$tenant\tId");
23177        let err = s.validate().unwrap_err();
23178        assert!(
23179            matches!(
23180                err,
23181                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23182                    if shard_key == "$tenant\tId" && reason.contains("tab")
23183            ),
23184            "got {err:?}"
23185        );
23186    }
23187
23188    #[test]
23189    fn rejects_shard_key_with_control_character() {
23190        // The paste-from-binary / paste-from-screen-cleared-terminal
23191        // footgun — an embedded `\x01` (SOH) byte that some YAML
23192        // emitters silently strip and others escape as ``,
23193        // breaking round-trip across emitter implementations.
23194        let s = sharded_spec_with_key("$tenant\u{0001}Id");
23195        let err = s.validate().unwrap_err();
23196        assert!(
23197            matches!(
23198                err,
23199                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23200                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
23201            ),
23202            "got {err:?}"
23203        );
23204    }
23205
23206    #[test]
23207    fn rejects_shard_key_with_non_ascii() {
23208        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
23209        // footgun — non-ASCII bytes normalize differently between the
23210        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
23211        // YAML parser, the same entity ID can silently map to two
23212        // distinct shards on a re-render.
23213        let s = sharded_spec_with_key("$tenàntId");
23214        let err = s.validate().unwrap_err();
23215        assert!(
23216            matches!(
23217                err,
23218                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23219                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
23220            ),
23221            "got {err:?}"
23222        );
23223    }
23224
23225    #[test]
23226    fn rejects_shard_key_too_long() {
23227        // Length cap pin: 64 bytes — one byte over the
23228        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
23229        // here is a paste-from-doc multi-line blob landing in
23230        // `:shard-key` instead of a single-token extractor expression.
23231        let too_long = "a".repeat(64);
23232        let s = sharded_spec_with_key(&too_long);
23233        let err = s.validate().unwrap_err();
23234        let AplicacaoError::ShardKeyInvalid {
23235            ref shard_key,
23236            ref reason,
23237        } = err
23238        else {
23239            panic!("expected ShardKeyInvalid, got {err:?}");
23240        };
23241        assert_eq!(shard_key, &too_long);
23242        assert!(
23243            reason.contains("63") && reason.contains("64"),
23244            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23245        );
23246    }
23247
23248    #[test]
23249    fn shard_key_max_length_validates() {
23250        // Boundary pin: 63 bytes exactly — the
23251        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
23252        // dropping to 62) surfaces here as a regression, mirroring
23253        // `placement_cluster_max_length_validates` /
23254        // `placement_affinity_max_length_validates` on the peer
23255        // identifier-shaped slots.
23256        let s = sharded_spec_with_key(&"a".repeat(63));
23257        s.validate().unwrap();
23258    }
23259
23260    #[test]
23261    fn accepts_canonical_shard_key_forms() {
23262        // The Akka-style entity-id extractor shapes a caixa author is
23263        // realistically going to write — pin every leg so a future
23264        // tightening that bans (e.g.) the `${...}` interpolation
23265        // variant or the `metadata.<field>` JSONPath form surfaces
23266        // here as a regression. The canonical forms span:
23267        //
23268        //   - bare property name (`tenantId`, `customerId`)
23269        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
23270        //   - JSONPath-style nested reference (`metadata.tenantId`,
23271        //     `$.user.id`)
23272        //   - interpolation-style template (`${tenant}`)
23273        //   - snake_case property name (`customer_id`)
23274        //   - kebab-case property name (`customer-id` — accepted
23275        //     because the slot is a printable-ASCII single-token
23276        //     reference, not a DNS-1123 label like
23277        //     `:placement :affinity` / `:clusters`)
23278        //   - single character (`a`, `$` — boundary)
23279        for form in [
23280            "tenantId",
23281            "customerId",
23282            "$tenantId",
23283            "metadata.tenantId",
23284            "$.user.id",
23285            "${tenant}",
23286            "customer_id",
23287            "customer-id",
23288            "a",
23289            "$",
23290        ] {
23291            let s = sharded_spec_with_key(form);
23292            s.validate().unwrap_or_else(|e| {
23293                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
23294            });
23295        }
23296    }
23297
23298    #[test]
23299    fn shard_key_empty_takes_precedence_over_invalid() {
23300        // Order pin: the existing `ShardedKeyEmpty` diagnostic
23301        // (reserved for the `Sharded` `Some("")` arm) fires before the
23302        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
23303        // `:shard-key` keeps its narrower error message — the new gate
23304        // would also reject `""` defensively, but the empty-string arm
23305        // is the more self-locating diagnostic. Mirrors the
23306        // `placement_cluster_empty_takes_precedence_over_invalid` pin
23307        // on the peer identifier-shaped slot.
23308        let s = sharded_spec_with_key("");
23309        let err = s.validate().unwrap_err();
23310        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
23311    }
23312
23313    #[test]
23314    fn shard_key_invalid_diagnostic_carries_offending_value() {
23315        // The diagnostic-shape pin: the error names the offending
23316        // `:shard-key` value verbatim so the author can grep their
23317        // caixa.lisp without re-running the build, and carries a
23318        // parser-shaped `reason:` naming the specific violation —
23319        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
23320        // on the peer identifier-shaped slot.
23321        let s = sharded_spec_with_key("$tenant Id");
23322        let err = s.validate().unwrap_err();
23323        let AplicacaoError::ShardKeyInvalid {
23324            ref shard_key,
23325            ref reason,
23326        } = err
23327        else {
23328            panic!("expected ShardKeyInvalid, got {err:?}");
23329        };
23330        assert_eq!(shard_key, "$tenant Id");
23331        assert!(
23332            !reason.is_empty(),
23333            "reason must name the specific violation, got empty string"
23334        );
23335    }
23336
23337    #[test]
23338    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
23339        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
23340        // `:shard-key` carried on non-Sharded strategies) fires before
23341        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
23342        // a `Replicated` strategy surfaces the more self-locating
23343        // strategy-mismatch diagnostic (naming the actual fix — drop
23344        // the slot, or switch to Sharded) rather than the shape
23345        // diagnostic. The strategy-mismatch arm is the more actionable
23346        // diagnostic: a malformed shard-key on Replicated is "you
23347        // shouldn't have a :shard-key here at all", not "your
23348        // :shard-key value is malformed".
23349        let mut s = three_member_spec();
23350        // Replicated is the default fixture strategy.
23351        s.placement.shard_key = Some("$tenant Id".into());
23352        let err = s.validate().unwrap_err();
23353        assert!(
23354            matches!(
23355                err,
23356                AplicacaoError::ShardKeyOnNonSharded {
23357                    estrategia: PlacementStrategy::Replicated,
23358                    ..
23359                }
23360            ),
23361            "got {err:?}"
23362        );
23363    }
23364
23365    #[test]
23366    fn rejects_empty_affinity_hint() {
23367        let mut s = three_member_spec();
23368        s.placement.affinity = Some(String::new());
23369        assert_eq!(
23370            s.validate().unwrap_err(),
23371            AplicacaoError::PlacementAffinityEmpty
23372        );
23373    }
23374
23375    #[test]
23376    fn placement_without_affinity_validates() {
23377        // Omitting :affinity is fine — the placement engine falls back
23378        // to the default heuristic. Pin the no-hint case so the
23379        // affinity-empty rejection doesn't accidentally fire on `None`.
23380        let mut s = three_member_spec();
23381        s.placement.affinity = None;
23382        s.validate().unwrap();
23383    }
23384
23385    #[test]
23386    fn rejects_placement_affinity_with_uppercase() {
23387        // The canonical "I copied the ADR's display name verbatim" typo
23388        // — placement hints land verbatim in K8s label-selector
23389        // territory, where the apiserver enforces the DNS-1123 label
23390        // rule (lowercase-only) on every identity-keyed admission axis.
23391        // Mirrors `rejects_placement_cluster_with_uppercase` on the
23392        // sibling slot.
23393        let mut s = three_member_spec();
23394        s.placement.affinity = Some("DataLocality".into());
23395        let err = s.validate().unwrap_err();
23396        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23397            panic!("expected PlacementAffinityInvalid, got other variant");
23398        };
23399        assert_eq!(affinity, "DataLocality");
23400        assert!(
23401            reason.contains("uppercase"),
23402            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
23403        );
23404        assert!(
23405            reason.contains("\"datalocality\""),
23406            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
23407        );
23408    }
23409
23410    #[test]
23411    fn rejects_placement_affinity_with_underscore() {
23412        // The canonical "I'm thinking of an env var / Python identifier"
23413        // leak — `_` is forbidden by every DNS-1123 label schema. Same
23414        // shape as `rejects_placement_cluster_with_underscore` on the
23415        // sibling slot.
23416        let mut s = three_member_spec();
23417        s.placement.affinity = Some("data_locality".into());
23418        let err = s.validate().unwrap_err();
23419        assert!(
23420            matches!(
23421                err,
23422                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23423                    if affinity == "data_locality" && reason.contains('_')
23424            ),
23425            "got {err:?}"
23426        );
23427    }
23428
23429    #[test]
23430    fn rejects_placement_affinity_with_dot() {
23431        // A `:placement :affinity` value is a single DNS-1123 *label*
23432        // (it lands as a K8s label value selector key), not a subdomain.
23433        // The "I want to namespace my hint with `.`" intent is expressed
23434        // via `-` (`data-locality-east`).
23435        let mut s = three_member_spec();
23436        s.placement.affinity = Some("data.locality".into());
23437        let err = s.validate().unwrap_err();
23438        assert!(
23439            matches!(
23440                err,
23441                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23442                    if affinity == "data.locality" && reason.contains('.')
23443            ),
23444            "got {err:?}"
23445        );
23446    }
23447
23448    #[test]
23449    fn rejects_placement_affinity_with_unicode() {
23450        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
23451        // before it reaches K8s. The byte-by-byte ASCII validity check
23452        // rejects multi-byte UTF-8 sequences by the first byte that
23453        // fails `[a-z0-9-]`.
23454        let mut s = three_member_spec();
23455        s.placement.affinity = Some("data-localité".into());
23456        let err = s.validate().unwrap_err();
23457        assert!(
23458            matches!(
23459                err,
23460                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23461                    if affinity == "data-localité"
23462            ),
23463            "got {err:?}"
23464        );
23465    }
23466
23467    #[test]
23468    fn rejects_placement_affinity_with_leading_hyphen() {
23469        // DNS-1123 boundary rule: labels must start with an
23470        // alphanumeric. Pin separately from the trailing-hyphen arm so
23471        // a future relaxation that only checks one boundary surfaces
23472        // here as a regression (parallel to
23473        // `rejects_placement_cluster_with_leading_hyphen`).
23474        let mut s = three_member_spec();
23475        s.placement.affinity = Some("-data-locality".into());
23476        let err = s.validate().unwrap_err();
23477        assert!(
23478            matches!(
23479                err,
23480                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23481                    if affinity == "-data-locality" && reason.contains("start and end")
23482            ),
23483            "got {err:?}"
23484        );
23485    }
23486
23487    #[test]
23488    fn rejects_placement_affinity_with_trailing_hyphen() {
23489        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
23490        // ends are covered against a future relaxation.
23491        let mut s = three_member_spec();
23492        s.placement.affinity = Some("data-locality-".into());
23493        let err = s.validate().unwrap_err();
23494        assert!(
23495            matches!(
23496                err,
23497                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23498                    if affinity == "data-locality-"
23499            ),
23500            "got {err:?}"
23501        );
23502    }
23503
23504    #[test]
23505    fn rejects_placement_affinity_with_whitespace() {
23506        // Whitespace is the canonical "I pasted from a sketch / doc"
23507        // footgun. The apiserver rejects every label-selector value
23508        // carrying whitespace.
23509        let mut s = three_member_spec();
23510        s.placement.affinity = Some("data locality".into());
23511        let err = s.validate().unwrap_err();
23512        assert!(
23513            matches!(
23514                err,
23515                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23516                    if affinity == "data locality"
23517            ),
23518            "got {err:?}"
23519        );
23520    }
23521
23522    #[test]
23523    fn rejects_placement_affinity_too_long() {
23524        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
23525        // pin. The diagnostic names both the cap (63) and the actual
23526        // length so the author can shorten in one edit. Mirrors
23527        // `rejects_placement_cluster_too_long`.
23528        let mut s = three_member_spec();
23529        let too_long = "a".repeat(64);
23530        s.placement.affinity = Some(too_long.clone());
23531        let err = s.validate().unwrap_err();
23532        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23533            panic!("expected PlacementAffinityInvalid");
23534        };
23535        assert_eq!(affinity, too_long);
23536        assert!(
23537            reason.contains("63") && reason.contains("64"),
23538            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23539        );
23540    }
23541
23542    #[test]
23543    fn placement_affinity_max_length_validates() {
23544        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
23545        // future tightening (e.g. dropping to 62) surfaces here as a
23546        // regression, mirroring `placement_cluster_max_length_validates`.
23547        let mut s = three_member_spec();
23548        s.placement.affinity = Some("a".repeat(63));
23549        s.validate().unwrap();
23550    }
23551
23552    #[test]
23553    fn accepts_canonical_placement_affinity_forms() {
23554        // The DNS-1123 label shapes a caixa author is realistically
23555        // going to write for placement hints: the M3 canonical examples
23556        // (`data-locality`, `low-latency`, `anti-affinity`), the
23557        // single-token form (`affinity`), the single-character boundary
23558        // (`a`), the digit-start (DNS-1123 allows this, unlike
23559        // DNS-1035), and a regional-suffixed form. Pin every leg so a
23560        // future tightening that bans (e.g.) digit-start identifiers
23561        // surfaces here.
23562        for form in [
23563            "data-locality",
23564            "low-latency",
23565            "anti-affinity",
23566            "affinity",
23567            "a",
23568            "3-tier",
23569            "locality-east",
23570        ] {
23571            let mut s = three_member_spec();
23572            s.placement.affinity = Some(form.into());
23573            s.validate().unwrap_or_else(|e| {
23574                panic!("canonical affinity form {form:?} must validate, got {e:?}")
23575            });
23576        }
23577    }
23578
23579    #[test]
23580    fn placement_affinity_empty_takes_precedence_over_invalid() {
23581        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
23582        // (which doesn't try to parse) fires before the new
23583        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
23584        // `:affinity` keeps its narrower error message — the new gate
23585        // would also reject `""`, but the empty-string arm is the more
23586        // self-locating diagnostic. Mirrors the
23587        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
23588        let mut s = three_member_spec();
23589        s.placement.affinity = Some(String::new());
23590        let err = s.validate().unwrap_err();
23591        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
23592    }
23593
23594    #[test]
23595    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
23596        // The diagnostic shape pin: every rejection carries the offending
23597        // `affinity:` verbatim plus a parser-shaped `reason:` so the
23598        // author can grep their caixa.lisp for `:affinity "<hint>"` and
23599        // fix it in one edit. Mirrors the
23600        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
23601        // pin on the sibling slot.
23602        let mut s = three_member_spec();
23603        s.placement.affinity = Some("Data_Locality".into());
23604        let err = s.validate().unwrap_err();
23605        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23606            panic!("expected PlacementAffinityInvalid");
23607        };
23608        assert_eq!(affinity, "Data_Locality");
23609        assert!(
23610            !reason.is_empty(),
23611            "diagnostic reason must not be empty (got: {reason:?})"
23612        );
23613    }
23614
23615    #[test]
23616    fn singlenode_with_takeover_candidates_validates() {
23617        // OTP distributed-application convention (MESH-COMPOSITION
23618        // §II.1): SingleNode runs on one cluster at a time but the
23619        // :clusters list enumerates the takeover candidates. Multiple
23620        // entries are not a contradiction — they are the failover pool.
23621        let mut s = three_member_spec();
23622        s.placement.estrategia = PlacementStrategy::SingleNode;
23623        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
23624        s.validate().unwrap();
23625    }
23626
23627    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
23628
23629    #[test]
23630    fn mesh_policy_default_is_empty() {
23631        // The Default impl carries None on every axis — the typed
23632        // analog of an unset `:politicas (())` slot. Renderers that
23633        // overlay the policy onto a cluster artifact key off this
23634        // predicate to skip the slot entirely; pinning so a future
23635        // axis added to MeshPolicy can't silently break the contract
23636        // (a new field whose Default is non-None would flip is_empty
23637        // to false on every existing caixa, surfacing here).
23638        assert!(MeshPolicy::default().is_empty());
23639    }
23640
23641    #[test]
23642    fn mesh_policy_with_only_timeout_is_not_empty() {
23643        let p = MeshPolicy {
23644            timeout: Some(Duration::from_secs(30)),
23645            ..Default::default()
23646        };
23647        assert!(!p.is_empty());
23648    }
23649
23650    #[test]
23651    fn mesh_policy_with_only_retries_is_not_empty() {
23652        let p = MeshPolicy {
23653            retries: Some(3),
23654            ..Default::default()
23655        };
23656        assert!(!p.is_empty());
23657    }
23658
23659    #[test]
23660    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
23661        let p = MeshPolicy {
23662            circuit_breaker: Some(CircuitBreaker {
23663                max_failures: 5,
23664                window: Duration::from_secs(60),
23665            }),
23666            ..Default::default()
23667        };
23668        assert!(!p.is_empty());
23669    }
23670
23671    #[test]
23672    fn mesh_policy_with_only_mtls_required_is_not_empty() {
23673        // Even `mtls_required: Some(false)` (an explicit opt-out) is
23674        // not empty — the author *named* the axis, the renderer needs
23675        // to honor that vs. fall back to the cluster default.
23676        let p = MeshPolicy {
23677            mtls_required: Some(false),
23678            ..Default::default()
23679        };
23680        assert!(!p.is_empty());
23681    }
23682
23683    #[test]
23684    fn mesh_policy_with_only_rate_limit_is_not_empty() {
23685        let p = MeshPolicy {
23686            rate_limit: Some(RateLimit {
23687                rate: 100,
23688                window: Duration::from_secs(1),
23689            }),
23690            ..Default::default()
23691        };
23692        assert!(!p.is_empty());
23693    }
23694
23695    #[test]
23696    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
23697        // The three-member happy-path fixture sets timeout + retries +
23698        // mtls_required — every populated axis must read non-empty.
23699        // Pin the round-trip so the M3.x per-:politicas emitter (the
23700        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
23701        // on is_empty() to decide whether to emit at all without
23702        // re-deriving the contract from inline field probes.
23703        assert!(!three_member_spec().politicas.is_empty());
23704    }
23705
23706    // ── shared duration codec: cross-slot integer-magnitude gate ──
23707    //
23708    // The integer-magnitude discipline applied to
23709    // `supervisor::duration_codec::parse` lifts onto every typed slot
23710    // that routes through the shared codec — `MeshPolicy::timeout`
23711    // (`:politicas :timeout`) and `CircuitBreaker::window`
23712    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
23713    // These cross-slot tests pin that the gate fires at the serde
23714    // layer for both typed slots, not just for the supervisor side.
23715
23716    #[test]
23717    fn policy_timeout_serde_rejects_fractional_seconds() {
23718        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
23719        // so the shared codec's integer-magnitude gate applies on
23720        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
23721        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
23722        // deserialize with the canonical-form diagnostic naming the
23723        // offending `"1.5"` and the remediation `"1500ms"`.
23724        let payload = r#"{"timeout":"1.5s"}"#;
23725        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23726        let msg = err.to_string();
23727        assert!(
23728            msg.contains("not a non-negative integer"),
23729            "expected integer-magnitude diagnostic in {msg:?}"
23730        );
23731        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
23732        assert!(
23733            msg.contains("\"1500ms\""),
23734            "missing canonical-form remediation in {msg:?}"
23735        );
23736    }
23737
23738    #[test]
23739    fn policy_timeout_serde_rejects_leading_plus_sign() {
23740        // Pin the leading-`+` arm cross-slot — the prior f64 parser
23741        // accepted `"+30s"` silently and round-tripped to `"30s"`.
23742        let payload = r#"{"timeout":"+30s"}"#;
23743        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23744        let msg = err.to_string();
23745        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
23746    }
23747
23748    #[test]
23749    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
23750        // `CircuitBreaker::window` uses `with =
23751        // "supervisor::duration_codec_required"` (the required-Duration
23752        // variant that delegates to the same shared parser). `"0.5m"`
23753        // parsed to 30s and round-tripped to `"30s"` on next emit —
23754        // DRIFT closed.
23755        let payload = format!(
23756            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
23757            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23758            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
23759        );
23760        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
23761        let msg = err.to_string();
23762        assert!(
23763            msg.contains("not a non-negative integer"),
23764            "expected integer-magnitude diagnostic in {msg:?}"
23765        );
23766        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
23767        assert!(
23768            msg.contains("\"30s\""),
23769            "missing canonical-form remediation in {msg:?}"
23770        );
23771    }
23772
23773    #[test]
23774    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
23775        // Pin the happy-path on the cross-slot side: every canonical
23776        // author shape `render` ever emits parses cleanly through the
23777        // shared codec on the `CircuitBreaker` slot. The
23778        // codec's accepted set (post-gate) is exactly its emitted set
23779        // for the integer-magnitude class.
23780        for window_lit in ["30s", "500ms", "2m", "1h"] {
23781            let payload = format!(
23782                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
23783                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
23784                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
23785            );
23786            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
23787                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
23788            });
23789            assert_eq!(cb.max_failures, 5);
23790        }
23791    }
23792
23793    // ── rate_limit_codec: integer-magnitude gate ──
23794    //
23795    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
23796    // / 737a676 / d53c922 trajectory landed on every typed-duration /
23797    // typed-byte-size codec in caixa-core lifts onto the fifth typed
23798    // codec — `rate_limit_codec` — through the digit-only magnitude
23799    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
23800    // These tests pin the gate at the serde layer for `:politicas
23801    // :rate-limit` (the only typed slot the codec backs), and at the
23802    // codec-internal `parse` layer for the canonical positive cases.
23803
23804    #[test]
23805    fn rate_limit_serde_rejects_fractional_rate() {
23806        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
23807        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
23808        // wording, which didn't name the canonical-form remediation or
23809        // the round-trip drift the next emit would produce. Now refused
23810        // at deserialize with the canonical-form diagnostic naming the
23811        // offending `"1.5"` magnitude and the round-trip drift wording.
23812        let payload = r#"{"rateLimit":"1.5/s"}"#;
23813        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23814        let msg = err.to_string();
23815        assert!(
23816            msg.contains("not a non-negative integer"),
23817            "expected integer-magnitude diagnostic in {msg:?}"
23818        );
23819        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
23820        assert!(
23821            msg.contains("THEORY.md"),
23822            "missing render-determinism contract citation in {msg:?}"
23823        );
23824    }
23825
23826    #[test]
23827    fn rate_limit_serde_rejects_leading_plus_sign() {
23828        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
23829        // permissive-`+` parse), so `"+100/s"` silently parsed to
23830        // `RateLimit { 100, 1s }` and round-tripped through `render` to
23831        // `"100/s"` — a *different* canonical string on the next emit,
23832        // breaking the THEORY.md Part V render-determinism contract
23833        // exactly the way the peer duration codecs' `"+30s"` case did.
23834        // This is the load-bearing class the digit-only gate closes
23835        // beyond what `u32::from_str`'s strictness covers on its own.
23836        let payload = r#"{"rateLimit":"+100/s"}"#;
23837        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23838        let msg = err.to_string();
23839        assert!(
23840            msg.contains("not a non-negative integer"),
23841            "expected integer-magnitude diagnostic in {msg:?}"
23842        );
23843        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
23844    }
23845
23846    #[test]
23847    fn rate_limit_serde_rejects_leading_minus_sign() {
23848        // The signed-negative arm: `"-1/s"` lands on the
23849        // non-canonical-but-numeric branch via the `i64` fallback (the
23850        // `f64` parse also succeeds), surfacing the canonical-form
23851        // diagnostic. Replaces the prior value-laundered "not a u32"
23852        // wording with the unified diagnostic across signs.
23853        let payload = r#"{"rateLimit":"-1/s"}"#;
23854        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23855        let msg = err.to_string();
23856        assert!(
23857            msg.contains("not a non-negative integer"),
23858            "expected integer-magnitude diagnostic in {msg:?}"
23859        );
23860        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
23861    }
23862
23863    #[test]
23864    fn rate_limit_serde_rejects_decimal_shaped_integer() {
23865        // `"100.0/s"` is integer-valued numerically but not in the
23866        // codec's accepted set — `render` emits `"100/s"`, so the
23867        // round-trip would drift. Lifted to the canonical-form
23868        // diagnostic peer with the duration codec's `"1.0s"` case
23869        // (1c55a2a).
23870        let payload = r#"{"rateLimit":"100.0/s"}"#;
23871        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23872        let msg = err.to_string();
23873        assert!(
23874            msg.contains("not a non-negative integer"),
23875            "expected integer-magnitude diagnostic in {msg:?}"
23876        );
23877        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
23878    }
23879
23880    #[test]
23881    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
23882        // Non-numeric, non-digit-only input lands on the existing
23883        // narrower `"not a u32"` arm (preserved for diagnostic-shape
23884        // stability on the parser-shape footgun case). Pin this so a
23885        // future relaxation of the numeric-fallback predicate doesn't
23886        // silently collapse garbage onto the canonical-form arm — same
23887        // partition the peer duration codecs draw between
23888        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
23889        let payload = r#"{"rateLimit":"abc/s"}"#;
23890        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23891        let msg = err.to_string();
23892        assert!(
23893            msg.contains("not a u32"),
23894            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
23895        );
23896        assert!(
23897            !msg.contains("not a non-negative integer"),
23898            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
23899        );
23900    }
23901
23902    #[test]
23903    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
23904        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
23905        // u32's range. The digit-only gate passes; `u32::from_str`
23906        // fails on overflow. Surface that with the overflow-shaped
23907        // diagnostic naming the offending magnitude verbatim, peer
23908        // with `supervisor::duration_codec`'s overflow arm. Pinning
23909        // the wording so a future refactor doesn't silently collapse
23910        // overflow onto the canonical-form arm.
23911        let payload = r#"{"rateLimit":"4294967296/s"}"#;
23912        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23913        let msg = err.to_string();
23914        assert!(
23915            msg.contains("overflows u32"),
23916            "expected overflow diagnostic in {msg:?}"
23917        );
23918        assert!(
23919            msg.contains("\"4294967296\""),
23920            "missing offending magnitude in {msg:?}"
23921        );
23922    }
23923
23924    #[test]
23925    fn rate_limit_serde_rejects_leading_zero_magnitude() {
23926        // `"0100/s"` is digit-only, so the existing
23927        // non-digit-only / sign / fractional arm doesn't catch it —
23928        // `u32::from_str("0100")` returns `Ok(100)`, so before this
23929        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
23930        // round-tripped through `render` to `"100/s"` — a *different*
23931        // canonical string on the next emit, breaking the THEORY.md
23932        // Part V render-determinism contract exactly the way the
23933        // peer `"+100/s"` case did before the leading-`+` arm landed.
23934        // This is the load-bearing class the leading-zero gate closes
23935        // beyond what the existing digit-only / sign / fractional
23936        // gates cover, and the peer arm to the leading-`+` test
23937        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
23938        // canonical-form-drift axis.
23939        let payload = r#"{"rateLimit":"0100/s"}"#;
23940        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23941        let msg = err.to_string();
23942        assert!(
23943            msg.contains("non-canonical leading zero"),
23944            "expected leading-zero diagnostic in {msg:?}"
23945        );
23946        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
23947        assert!(
23948            msg.contains("THEORY.md"),
23949            "missing render-determinism contract citation in {msg:?}"
23950        );
23951    }
23952
23953    #[test]
23954    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
23955        // `"00/s"` is the degenerate leading-zero case — every byte
23956        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
23957        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
23958        // a *different* canonical string, same render-determinism
23959        // violation. The single-byte `"0/s"` itself is in the
23960        // accepted set (round-trips losslessly through `render`,
23961        // refused downstream by `PolicyRateLimitZero`); the
23962        // multi-byte `"00/s"` is not. Pins the boundary between the
23963        // accepted single-`0` and the rejected leading-zero class.
23964        let payload = r#"{"rateLimit":"00/s"}"#;
23965        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23966        let msg = err.to_string();
23967        assert!(
23968            msg.contains("non-canonical leading zero"),
23969            "expected leading-zero diagnostic in {msg:?}"
23970        );
23971        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
23972    }
23973
23974    #[test]
23975    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
23976        // Cross-window pin — the gate is window-agnostic; the
23977        // leading-zero class is a property of the magnitude, not the
23978        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
23979        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
23980        // single-window coverage extended across the three canonical
23981        // windows the codec accepts.
23982        let payload = r#"{"rateLimit":"007/h"}"#;
23983        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
23984        let msg = err.to_string();
23985        assert!(
23986            msg.contains("non-canonical leading zero"),
23987            "expected leading-zero diagnostic in {msg:?}"
23988        );
23989        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
23990    }
23991
23992    #[test]
23993    fn rate_limit_serde_rejects_leading_whitespace() {
23994        // `" 100/s"` — the canonical paste-from-aligned-doc /
23995        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
23996        // the top-level `s.trim()` silently ate the leading space and
23997        // parsed the value to `RateLimit { 100, 1s }`, which then
23998        // round-tripped through `render` to `"100/s"` (a *different*
23999        // canonical string on the next emit) — the exact
24000        // canonical-form-drift class the leading-`+` / leading-zero
24001        // arms already close, extended to the whitespace byte class.
24002        let payload = r#"{"rateLimit":" 100/s"}"#;
24003        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24004        let msg = err.to_string();
24005        assert!(
24006            msg.contains("contains whitespace byte"),
24007            "expected whitespace diagnostic in {msg:?}"
24008        );
24009        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24010        assert!(
24011            msg.contains("THEORY.md"),
24012            "missing render-determinism contract citation in {msg:?}"
24013        );
24014    }
24015
24016    #[test]
24017    fn rate_limit_serde_rejects_trailing_whitespace() {
24018        // `"100/s "` — the canonical shell-history / trailing-space
24019        // paste footgun. Before this gate the top-level `s.trim()`
24020        // silently ate the trailing space and parsed to
24021        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
24022        // next emit — same canonical-form drift as the leading-space
24023        // sibling, closed on the same whitespace-byte arm.
24024        let payload = r#"{"rateLimit":"100/s "}"#;
24025        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24026        let msg = err.to_string();
24027        assert!(
24028            msg.contains("contains whitespace byte"),
24029            "expected whitespace diagnostic in {msg:?}"
24030        );
24031        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24032    }
24033
24034    #[test]
24035    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
24036        // `"100 / s"` — the canonical typographically-spaced author
24037        // shape (the same idiom every prose reference to a rate limit
24038        // renders as, mistakenly retained when the value is pasted
24039        // into a codec-shaped slot). Before this gate the per-part
24040        // `rate_str.trim()` / `unit.trim()` calls silently ate both
24041        // spaces on either side of `/` and parsed to
24042        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
24043        // codec's *internal* whitespace-tolerance vector, orthogonal
24044        // to the leading / trailing surface but the same canonical-
24045        // form-drift class. Pins the arm as strictly stronger than the
24046        // pre-existing top-level `s.trim()` behavior: it fires on
24047        // whitespace anywhere in the value, not just at the string
24048        // boundary.
24049        let payload = r#"{"rateLimit":"100 / s"}"#;
24050        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24051        let msg = err.to_string();
24052        assert!(
24053            msg.contains("contains whitespace byte"),
24054            "expected whitespace diagnostic in {msg:?}"
24055        );
24056        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24057    }
24058
24059    #[test]
24060    fn rate_limit_serde_rejects_tab_byte() {
24061        // `"\t100/s"` — the canonical paste-from-indented-doc /
24062        // paste-from-YAML-block-scalar footgun where a tab byte leads
24063        // the magnitude. Pins that the gate covers tab (`0x09`) as
24064        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
24065        // members and both would be silently swallowed by `s.trim()`
24066        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
24067        // space alone to the full ASCII-whitespace set (space `0x20`,
24068        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
24069        // the tab arm as a representative of the non-space members.
24070        let payload = r#"{"rateLimit":"\t100/s"}"#;
24071        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24072        let msg = err.to_string();
24073        assert!(
24074            msg.contains("contains whitespace byte"),
24075            "expected whitespace diagnostic in {msg:?}"
24076        );
24077        assert!(
24078            msg.contains("0x09"),
24079            "missing offending tab byte in {msg:?}"
24080        );
24081    }
24082
24083    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
24084    //
24085    // Successor to the ASCII-whitespace arm (1ad7755) on
24086    // `rate_limit_codec` — closes the strictly-complementary class the
24087    // byte-scan cannot see, through the lifted
24088    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
24089
24090    #[test]
24091    fn rate_limit_serde_rejects_leading_nbsp() {
24092        // NBSP prefix — paste-from-typography footgun. Byte-scan
24093        // misses, `str::trim` silently strips it, value drifts to
24094        // `"100/s"` on next serialize.
24095        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
24096        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24097        let msg = err.to_string();
24098        assert!(
24099            msg.contains("non-ASCII Unicode whitespace character"),
24100            "expected non-ASCII whitespace diagnostic in {msg:?}"
24101        );
24102        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
24103    }
24104
24105    #[test]
24106    fn rate_limit_serde_rejects_internal_em_space() {
24107        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
24108        // paste-from-typography footgun on the `<integer>/<unit>`
24109        // shape.
24110        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
24111        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24112        let msg = err.to_string();
24113        assert!(
24114            msg.contains("non-ASCII Unicode whitespace character"),
24115            "expected non-ASCII whitespace diagnostic in {msg:?}"
24116        );
24117        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
24118    }
24119
24120    #[test]
24121    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
24122        // Positive-control pin: every ASCII-only canonical form the
24123        // renderer emits stays accepted through the new arm.
24124        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
24125            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
24126            let p: MeshPolicy = serde_json::from_str(&payload)
24127                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
24128            assert!(p.rate_limit.is_some());
24129        }
24130    }
24131
24132    #[test]
24133    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
24134        // The boundary case — `"0/s"` is the canonical form
24135        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
24136        // it at the parse layer; the downstream
24137        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
24138        // `rate == 0` at the typed-validate layer above. Pins the
24139        // partition: the leading-zero gate at the codec layer does
24140        // not poach the rate-zero semantic-validation arm at the
24141        // typed-validate layer above (a future stricter codec must
24142        // not reject `"0/s"` here, or it'd collapse the diagnostic
24143        // partitioning that lets `PolicyRateLimitZero` name the
24144        // offending typed slot).
24145        let payload = r#"{"rateLimit":"0/s"}"#;
24146        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
24147            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
24148        });
24149        let rl = policy.rate_limit.expect("rate_limit must be Some");
24150        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
24151        assert_eq!(
24152            rl.window,
24153            Duration::from_secs(1),
24154            "single-`0` magnitude with `s` unit must parse to window=1s"
24155        );
24156    }
24157
24158    #[test]
24159    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
24160        // The complementary boundary pin — every magnitude
24161        // `render` emits starts with `[1-9]` (or is the single byte
24162        // `"0"`), so the canonical-form predicate is `(len == 1) ||
24163        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
24164        // '1'` case explicitly so a future tightening of the gate
24165        // (e.g. an over-eager "no leading digit < 5" rule, or a
24166        // mistakenly anchored start-of-magnitude byte check) lands
24167        // here before the canonical-forms-iterating test would catch
24168        // it.
24169        let payload = r#"{"rateLimit":"100/s"}"#;
24170        let policy: MeshPolicy = serde_json::from_str(payload)
24171            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
24172        let rl = policy.rate_limit.expect("rate_limit must be Some");
24173        assert_eq!(
24174            rl.rate, 100,
24175            "canonical-100 magnitude must parse to rate=100"
24176        );
24177    }
24178
24179    #[test]
24180    fn rate_limit_serde_accepts_integer_canonical_forms() {
24181        // Pin the happy-path: every canonical author shape `render`
24182        // ever emits parses cleanly through the codec post-gate. The
24183        // codec's accepted set (post-gate) is exactly its emitted set
24184        // for the integer-magnitude class — same property
24185        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
24186        // gates guarantee on the peer codecs. Iterating across rate
24187        // magnitudes (including `"0"`, which the codec accepts even
24188        // though `validate_politicas` rejects `rate == 0` at the typed
24189        // layer above) closes the codec contract at the parse layer
24190        // independently of the validate layer.
24191        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
24192            for unit_lit in ["s", "m", "h"] {
24193                let lit = format!("{rate_lit}/{unit_lit}");
24194                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
24195                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
24196                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
24197                });
24198                let rl = policy.rate_limit.expect("rate_limit must be Some");
24199                assert_eq!(
24200                    rl.rate,
24201                    rate_lit.parse::<u32>().unwrap(),
24202                    "rate mismatch for {lit:?}"
24203                );
24204            }
24205        }
24206    }
24207
24208    #[test]
24209    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
24210        // The structural property the gate enforces: serialize ∘
24211        // deserialize is the identity on every canonical author shape.
24212        // Peer of `parse_byte_size`'s and `parse_duration`'s
24213        // `_round_trips_through_render_for_every_canonical_form` tests
24214        // on the rate-limit axis. Before the gate, `"+100/s"` violated
24215        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
24216        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
24217        for rate in [1u32, 100, 5000, 1_000_000] {
24218            for (window, unit) in [
24219                (Duration::from_secs(1), "s"),
24220                (Duration::from_secs(60), "m"),
24221                (Duration::from_secs(3600), "h"),
24222            ] {
24223                let policy = MeshPolicy {
24224                    rate_limit: Some(RateLimit { rate, window }),
24225                    ..Default::default()
24226                };
24227                let json = serde_json::to_string(&policy).unwrap();
24228                let expected = format!("\"{rate}/{unit}\"");
24229                assert!(
24230                    json.contains(&expected),
24231                    "expected {expected:?} in {json:?}"
24232                );
24233                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24234                assert_eq!(
24235                    back.rate_limit, policy.rate_limit,
24236                    "round-trip for {json:?}"
24237                );
24238            }
24239        }
24240    }
24241
24242    // ── self-membership cross-slot gate ──────────────────────────────
24243
24244    #[test]
24245    fn validate_no_self_membership_rejects_self_named_membro() {
24246        // An Aplicacao whose `:membros` lists its own `:nome` is a
24247        // one-node lacre-closure recursion — rejected, naming the parent.
24248        let membros = vec![
24249            membro("catalog", "^0.1"),
24250            membro("checkout", "^0.1"),
24251            membro("cart", "^0.1"),
24252        ];
24253        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
24254        assert!(
24255            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
24256            "got {err:?}"
24257        );
24258    }
24259
24260    #[test]
24261    fn validate_no_self_membership_accepts_distinct_membros() {
24262        // Positive control: distinct member names (including a member
24263        // that is itself an Aplicacao — recursive composition is valid,
24264        // MESH-COMPOSITION §V) pass the gate.
24265        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
24266        validate_no_self_membership(&membros, "checkout").unwrap();
24267    }
24268
24269    #[test]
24270    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
24271        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
24272        // `NoMembros` arm (the more-fundamental "graph must have nodes"
24273        // gate), not by this cross-slot self-edge gate. Keeping the
24274        // self-membership predicate vacuously-ok on the empty input
24275        // matches its supervisor-axis peer
24276        // (`validate_no_self_supervision_empty_children_is_ok`) and
24277        // makes the gate composable from any future call site (an M4
24278        // CR materializer's per-membros validator) without re-checking
24279        // emptiness.
24280        validate_no_self_membership(&[], "checkout").unwrap();
24281    }
24282
24283    #[test]
24284    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
24285        // Pinning the Display: the self-membership diagnostic must name
24286        // the offending caixa verbatim + the "lists itself" framing the
24287        // author can grep for, so the cluster-far failure surfaces at
24288        // build time with one-line remediation. Same diagnostic shape
24289        // as the supervisor-axis `ChildSupervisesSelf` peer.
24290        let membros = vec![membro("orquestra", "^0.1")];
24291        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
24292        let msg = err.to_string();
24293        assert!(
24294            msg.contains("orquestra"),
24295            "diagnostic must name the offending caixa nome (got: {msg:?})"
24296        );
24297        assert!(
24298            msg.contains("lists itself"),
24299            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
24300        );
24301    }
24302
24303    #[test]
24304    fn default_servico_port_constant_pins_canonical_8080_literal() {
24305        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
24306        // at the verbatim `8080` literal both consumers (the
24307        // `Entrada::port` serde default via [`default_port`] and the
24308        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
24309        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
24310        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
24311        // discipline (a085b26) on the per-renderer canonical-K8s-axis
24312        // string-constant axis: a future refactor that drifts the
24313        // constant out from under either consumer surfaces here ahead
24314        // of every per-renderer's first emission. The literal value
24315        // matches the well-known HTTP-alt port the `pleme-computeunit`
24316        // library chart already emits as its `trigger.service.port`
24317        // default — by construction the same value the substrate
24318        // assumes about every Servico's in-cluster L4 listener.
24319        assert_eq!(
24320            DEFAULT_SERVICO_PORT, 8080,
24321            "canonical Servico port literal must remain `8080` verbatim — \
24322             this is the value both the `Entrada::port` serde default and the \
24323             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
24324        );
24325    }
24326
24327    #[test]
24328    fn default_port_helper_returns_canonical_servico_port_constant() {
24329        // The bridge-arm — pins that the [`default_port`] helper
24330        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
24331        // attribute hooks routes through the lifted
24332        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
24333        // literal. A future refactor that re-introduces the `8080`
24334        // literal at the helper's return site (silently re-opening
24335        // the drift footgun this lift closed) surfaces here ahead of
24336        // every author-side `(:entrada (:host … :para …))` slot
24337        // without an explicit `:port`. Peer with the
24338        // `default_namespace_re_export_points_at_caixa_core_canonical`
24339        // pin on the caixa-mesh-side re-export axis.
24340        assert_eq!(
24341            default_port(),
24342            DEFAULT_SERVICO_PORT,
24343            "the serde-default helper must route through the lifted constant"
24344        );
24345    }
24346
24347    #[test]
24348    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
24349        // The end-to-end pin — an author-surface `(:entrada (:host …
24350        // :para …))` without an explicit `:port` slot deserializes to
24351        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
24352        // verbatim. Routes the canonical lifted constant through both
24353        // the serde-default machinery (the `#[serde(default =
24354        // "default_port")]` attribute) and the typed-value-shape
24355        // contract (the resulting [`Entrada::port`] value). A future
24356        // refactor that drifts either axis — replacing the serde
24357        // hook's helper, changing the typed slot's wire shape — would
24358        // surface here before any per-renderer's CNP / Gateway /
24359        // HTTPRoute emission consumed the drifted default.
24360        let entrada: Entrada =
24361            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
24362        assert_eq!(
24363            entrada.port, DEFAULT_SERVICO_PORT,
24364            "the serde default must materialize as the lifted canonical Servico port"
24365        );
24366    }
24367
24368    #[test]
24369    fn servico_port_min_pins_canonical_accept_set_floor() {
24370        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
24371        // verbatim `1` literal every typed `:entrada :port` acceptance
24372        // gate keys off. Peer with the
24373        // [`default_servico_port_constant_pins_canonical_8080_literal`]
24374        // discipline on the canonical-Servico-port-constant axis: a
24375        // future refactor that drifts the accept-set floor out from
24376        // under the sole consumer at [`AplicacaoSpec::validate`]'s
24377        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
24378        // every per-`:entrada` `EntradaPortZero` diagnostic. The
24379        // literal value matches the IANA-registered TCP/UDP port
24380        // space floor (`1..=65535` — port `0` is the "any ephemeral"
24381        // sentinel, not a well-defined destination the substrate's
24382        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
24383        // axis can honor).
24384        assert_eq!(
24385            SERVICO_PORT_MIN, 1,
24386            "canonical Servico port accept-set floor must remain `1` verbatim — \
24387             this is the value the `AplicacaoSpec::validate` gate at \
24388             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
24389        );
24390    }
24391
24392    #[test]
24393    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
24394        // The cross-const invariant pin — the substrate's canonical
24395        // default port must satisfy its own accept-set floor by
24396        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
24397        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
24398        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
24399        // override the operator pins through a future
24400        // `:placement :default-port` slot that lands out-of-range, a
24401        // per-edition Servico-port migration that lifted the floor
24402        // above the previous default without coordinating the pair —
24403        // would silently invalidate the serde-default emission at
24404        // every author-side `(:entrada (:host … :para …))` slot
24405        // without an explicit `:port`: the default port would fall
24406        // below the accept-set floor, the `AplicacaoSpec::validate`
24407        // gate would reject every default-carrying Aplicacao as
24408        // `EntradaPortZero`, and the substrate's typed
24409        // `(defcaixa … :kind Aplicacao)` surface would fail validate
24410        // on every Aplicacao whose author omitted `:entrada :port`
24411        // for the substrate's chosen default — a class of authoring-
24412        // surface footguns the compile-time pin structurally closes.
24413        // Peer with the
24414        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
24415        // (27f9b34) cross-const invariant pin discipline on the peer
24416        // canonical-Helm-per-values-block child-chart-enablement-toggle
24417        // axis pair.
24418        const {
24419            assert!(
24420                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
24421                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
24422                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
24423                 every default-carrying `(:entrada (:host … :para …))` slot \
24424                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
24425                 through the serde default hook and must pass the \
24426                 `AplicacaoSpec::validate` floor gate by construction",
24427            );
24428        }
24429    }
24430
24431    #[test]
24432    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
24433        // The gate-site pin — asserts the `AplicacaoSpec::validate`
24434        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
24435        // `EntradaPortZero` diagnostic on the below-floor input
24436        // `port: 0` (the only below-floor value the `u16` field can
24437        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
24438        // is the singleton `{0}`). A future refactor that drifts the
24439        // gate off the lifted const (silently re-introducing an
24440        // inline `if e.port == 0` byte-check) surfaces here — the
24441        // pin cannot distinguish `< 1` from `== 0` on the current
24442        // floor, but it *does* pin that the diagnostic fires on `0`
24443        // through whichever gate is wired, so any future accept-set
24444        // floor migration (a hypothetical unprivileged-only
24445        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
24446        // update this test alongside the const declaration —
24447        // structurally guaranteeing the gate + accept-set + pin
24448        // trio move together. Peer with the
24449        // [`rejects_zero_entrada_port`] behavioral pin on the same
24450        // per-`:entrada :port` axis — that pin asserts the pre-lift
24451        // behavioral contract (`port: 0` → `EntradaPortZero`); this
24452        // pin adds the structural link to the lifted floor const.
24453        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
24454        let mut s = three_member_spec();
24455        s.entrada.as_mut().unwrap().port = 0;
24456        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
24457    }
24458
24459    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
24460
24461    #[test]
24462    fn membro_serde_keys_match_lifted_membro_key_consts() {
24463        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
24464        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
24465        // name the exact camelCase JSON keys the
24466        // `#[serde(rename_all = "camelCase")]` attribute on
24467        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
24468        // that each canonical byte-sequence appears verbatim in the
24469        // JSON — a future accidental `rename_all = "snake_case"` /
24470        // `"kebab-case"` / verbatim-field-name flip at the derive
24471        // attribute (any of which would silently break every downstream
24472        // JSON consumer that reaches for one of the two consts via
24473        // `Value::get(...)`) surfaces here as a build-time test failure
24474        // at `aplicacao.rs`, not as an apply-time
24475        // `.get(<stale-canonical-const>)` returning `None` far from the
24476        // derive-attr drift's commit. Peer with the sibling
24477        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
24478        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
24479        // same discipline the SupervisorSpec top-level lift established,
24480        // extended here to the M3 [`Membro`] per-`:membros` axis.
24481        let m = Membro {
24482            caixa: "catalog".into(),
24483            versao: "^0.1".into(),
24484        };
24485        let json = serde_json::to_string(&m).unwrap();
24486        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
24487            let quoted = format!("\"{key}\"");
24488            assert!(
24489                json.contains(&quoted),
24490                "serialized Membro must carry the lifted MEMBRO_KEY_* \
24491                 byte-sequence {quoted} verbatim in the JSON emission \
24492                 (got: {json})",
24493            );
24494        }
24495    }
24496
24497    #[test]
24498    fn membro_key_consts_are_pairwise_distinct() {
24499        // Cross-axis drift-detection pin: a future collapse of the two
24500        // canonical [`Membro`] per-entry byte-strings onto the same
24501        // value (e.g. an accidental copy-paste flip of
24502        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
24503        // silently reroute every downstream probe on one axis onto the
24504        // sibling axis's overlay entry and pass every propagation-probe
24505        // test that expected only the stale axis's value. Peer of the
24506        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
24507        // (40cc4e5).
24508        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
24509        for (i, a) in all.iter().enumerate() {
24510            for b in all.iter().skip(i + 1) {
24511                assert_ne!(
24512                    a, b,
24513                    "MEMBRO_KEY_* consts must be pairwise-distinct \
24514                     canonical byte-sequences — got `{a}` == `{b}`",
24515                );
24516            }
24517        }
24518    }
24519
24520    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
24521    //    URL-path fallback resolver every HTTPRoute-aware renderer
24522    //    reaching for a per-rule path-list resolution routes through.
24523    //    The four pin tests below fix the four-way accept-set the
24524    //    resolver must always honor: (:paths-non-empty-verbatim,
24525    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
24526    //    :paths-preserves-order-across-multiple-entries) — drift on any
24527    //    arm surfaces at caixa-core build time rather than at cluster-
24528    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
24529    //    sibling `:politicas` typed-primitive dispatch axis.
24530
24531    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
24532        Entrada {
24533            host: "example.com".into(),
24534            para: "cart".into(),
24535            paths: paths.into_iter().map(String::from).collect(),
24536            port: DEFAULT_SERVICO_PORT,
24537        }
24538    }
24539
24540    #[test]
24541    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
24542        // The typed `:entrada :paths` slot carries an author-declared
24543        // list — the resolver returns each entry verbatim, no
24544        // catch-all substitution. The canonical "author declared
24545        // paths, honor them verbatim" arm of the path-list dispatch.
24546        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
24547        assert_eq!(
24548            e.resolved_paths(),
24549            vec!["/api/cart", "/api/products"],
24550            "resolved_paths must return each `:entrada :paths` entry \
24551             verbatim when the typed slot is non-empty (got {:?})",
24552            e.resolved_paths(),
24553        );
24554    }
24555
24556    #[test]
24557    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
24558        // Empty `:entrada :paths` slot — the resolver substitutes the
24559        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
24560        // catch-all fallback verbatim. Pins the empty-arm of the
24561        // resolver's four-way accept-set against a future silent
24562        // detour that returned an empty Vec (which would emit an
24563        // HTTPRoute with zero rules — silently dropping every
24564        // external `:entrada` flow at admission time), routed to a
24565        // different fallback shape, or dropped the catch-all
24566        // altogether.
24567        let e = entrada_with_paths(vec![]);
24568        assert_eq!(
24569            e.resolved_paths(),
24570            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
24571            "resolved_paths on empty `:entrada :paths` must fall back \
24572             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
24573             all — got {:?}",
24574            e.resolved_paths(),
24575        );
24576    }
24577
24578    #[test]
24579    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
24580        // Single-entry `:entrada :paths` — the resolver returns the
24581        // single declared path verbatim, NOT the catch-all fallback
24582        // (author declared a path, honor it — the empty-arm and the
24583        // len-1 arm are semantically distinct axes of the resolver's
24584        // accept-set). Pins that the resolver treats "author declared
24585        // one path" as authored input, not as the empty case.
24586        let e = entrada_with_paths(vec!["/api/only"]);
24587        assert_eq!(
24588            e.resolved_paths(),
24589            vec!["/api/only"],
24590            "resolved_paths on single-entry `:entrada :paths` must \
24591             return the declared path verbatim, NOT the catch-all \
24592             fallback (got {:?})",
24593            e.resolved_paths(),
24594        );
24595    }
24596
24597    #[test]
24598    fn resolved_paths_preserves_author_declared_order() {
24599        // The `:entrada :paths` list is author-ordered — the resolver
24600        // preserves the author's declaration order verbatim, since
24601        // per-rule dispatch order at the K8s Gateway API HTTPRoute
24602        // consumer is significant (first-match-wins under the
24603        // path-prefix matcher). Pins against a future silent
24604        // re-sort / dedup / normalize detour that reordered author
24605        // input.
24606        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
24607        assert_eq!(
24608            e.resolved_paths(),
24609            vec!["/z/last", "/a/first", "/m/mid"],
24610            "resolved_paths must preserve author-declared `:entrada \
24611             :paths` order verbatim — got {:?}",
24612            e.resolved_paths(),
24613        );
24614    }
24615
24616    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
24617    //    slot `&[String]` slice accessor every per-`:entrada` consumer
24618    //    that must see the author's declaration verbatim (not the
24619    //    fallback-applied projection the sibling `resolved_paths`
24620    //    returns) routes through. The three pin tests below fix the
24621    //    accept-set the accessor must honor: (:non-empty-byte-equal,
24622    //    :empty-projects-empty-slice, :preserves-author-declared-order)
24623    //    — drift on any arm surfaces at caixa-core build time rather
24624    //    than at cluster-apply time. Peer discipline with the sibling
24625    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
24626    //    peer M3 mesh-slot `Vec<String>`-carry axis.
24627
24628    #[test]
24629    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
24630        // Byte-equal pin: [`Entrada::paths`] must project the raw
24631        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
24632        // slice borrowed from the typed slot's own [`Vec<String>`]
24633        // storage — no re-ordering, no dedup, no per-entry normalization,
24634        // no fallback substitution (the fallback-applying projection is
24635        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
24636        // a future silent detour that re-normalized the list, dropped
24637        // duplicates the [`AplicacaoSpec::validate`]
24638        // `EntradaPathDuplicate` refusal already rejects at build time,
24639        // or (most severe) accidentally routed through the fallback-
24640        // applying sibling and returned the substrate catch-all when
24641        // the author declared an empty list — collapsing the raw-slot
24642        // and fallback-applied axes into one and breaking the
24643        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
24644        //
24645        // Peer of the sibling
24646        // [`Placement::clusters`]-shape byte-equal pin
24647        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24648        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
24649        let fixtures: Vec<Vec<String>> = vec![
24650            Vec::new(),
24651            vec!["/api/cart".into()],
24652            vec!["/api/cart".into(), "/api/products".into()],
24653            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
24654        ];
24655        for paths in fixtures {
24656            let e = Entrada {
24657                host: "example.com".into(),
24658                para: "cart".into(),
24659                paths: paths.clone(),
24660                port: DEFAULT_SERVICO_PORT,
24661            };
24662            assert_eq!(
24663                e.paths(),
24664                paths.as_slice(),
24665                "Entrada::paths must return :entrada :paths verbatim \
24666                 (got {:?}, expected {:?})",
24667                e.paths(),
24668                paths.as_slice(),
24669            );
24670            assert_eq!(
24671                e.paths(),
24672                e.paths.as_slice(),
24673                "Entrada::paths accessor and .paths.as_slice() field \
24674                 access must byte-equal — the accessor is the substrate-\
24675                 primitive typed dispatch every downstream per-`:entrada` \
24676                 raw-slot path-list consumer must route through",
24677            );
24678            assert_eq!(
24679                e.paths().len(),
24680                e.paths.len(),
24681                "Entrada::paths().len() must byte-equal self.paths.len() \
24682                 — a length drift would silently split the paired \
24683                 pre-flight cascade-head `.is_empty()` probe input in \
24684                 the sibling [`Entrada::resolved_paths`] resolver from \
24685                 the per-entry validate loop's traversal input in \
24686                 [`AplicacaoSpec::validate`]",
24687            );
24688        }
24689    }
24690
24691    #[test]
24692    fn resolved_paths_reads_through_lifted_paths_accessor() {
24693        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
24694        // pre-flight `.paths().is_empty()` cascade-head probe (which
24695        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
24696        // catch-all fallback arm when the accessor projects the empty
24697        // slice) and the per-entry `.paths().iter().map(String::as_str)`
24698        // projection (which must reach every entry in the same order
24699        // the accessor projects, so the sibling
24700        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
24701        // per-entry projection stay in lockstep by construction) must
24702        // both key off the lifted accessor. Pins the two-site coherence
24703        // by exercising each production consumer end-to-end: (1) the
24704        // catch-all-fallback arm under the empty slice, (2) the
24705        // author-declared-verbatim arm under a two-entry cohort whose
24706        // per-entry projection must byte-equal the input's per-entry
24707        // author-declared paths in the author's declared order.
24708        //
24709        // Peer of the sibling M3
24710        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
24711        // `validate_placement_reads_through_lifted_clusters_accessor`
24712        // on the sibling `Placement::clusters` reader-site convergence.
24713        let empty = entrada_with_paths(vec![]);
24714        assert_eq!(
24715            empty.resolved_paths(),
24716            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
24717            "resolved_paths on empty :entrada :paths must trip the \
24718             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
24719             catch-all fallback — routing through the lifted paths() \
24720             accessor must not silently drop the fallback arm",
24721        );
24722
24723        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
24724        assert_eq!(
24725            declared.resolved_paths(),
24726            vec!["/api/cart", "/api/products"],
24727            "resolved_paths on non-empty :entrada :paths must return each \
24728             entry verbatim in the author's declared order — routing \
24729             through the lifted paths() accessor must not silently \
24730             reorder or drop entries",
24731        );
24732        // Byte-equal pin against the raw-slot accessor to keep the
24733        // fallback-applying resolver's per-entry projection input in
24734        // lockstep with the raw-slot accessor's projection.
24735        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
24736        assert_eq!(
24737            declared.resolved_paths(),
24738            raw_projected,
24739            "resolved_paths non-empty projection must byte-equal the \
24740             lifted paths() accessor's per-entry String::as_str projection \
24741             — the two projections share the same input slice by \
24742             construction, so any drift here would surface a silent \
24743             re-ordering / dedup / normalization detour in the resolver",
24744        );
24745    }
24746
24747    #[test]
24748    fn validate_reads_through_lifted_entrada_paths_accessor() {
24749        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
24750        // per-entry value-shape gate's `for p in e.paths()` traversal
24751        // (which must reach every entry in the same order the accessor
24752        // projects, so both the per-entry `EntradaPathEmpty` /
24753        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
24754        // the duplicate-detection HashSet insert that trips
24755        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
24756        // projection) must route through the lifted accessor. Pins the
24757        // coherence by exercising each production consumer end-to-end:
24758        // (1) the `EntradaPathEmpty` refusal fires on the second entry
24759        // of a two-entry cohort whose head is valid but tail is empty
24760        // (which requires the loop to reach the second entry through
24761        // the accessor), and (2) the `EntradaPathDuplicate` refusal
24762        // fires on the second entry of a two-entry cohort that shares
24763        // a path (which requires the loop to reach both entries — a
24764        // first-entry-only projection would silently pass since the
24765        // dedup HashSet has room for the first insert).
24766        //
24767        // Peer of the sibling
24768        // `validate_placement_reads_through_lifted_clusters_accessor`
24769        // on the sibling `Placement::clusters` reader-site convergence.
24770        let base = crate::AplicacaoSpec {
24771            membros: vec![crate::Membro {
24772                caixa: "cart".into(),
24773                versao: "^0.1".into(),
24774            }],
24775            contratos: Vec::new(),
24776            politicas: crate::MeshPolicy::default(),
24777            placement: crate::Placement {
24778                estrategia: crate::PlacementStrategy::SingleNode,
24779                clusters: vec!["rio".into()],
24780                shard_key: None,
24781                affinity: None,
24782            },
24783            entrada: Some(Entrada {
24784                host: "example.com".into(),
24785                para: "cart".into(),
24786                paths: vec!["/api/cart".into(), String::new()],
24787                port: DEFAULT_SERVICO_PORT,
24788            }),
24789        };
24790        assert_eq!(
24791            base.validate(),
24792            Err(crate::AplicacaoError::EntradaPathEmpty),
24793            "validate must trip EntradaPathEmpty on the second entry of \
24794             a two-entry cohort — routing through the lifted paths() \
24795             accessor must not silently short-circuit the loop at the \
24796             valid head entry",
24797        );
24798
24799        let mut dup = base;
24800        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
24801        assert_eq!(
24802            dup.validate(),
24803            Err(crate::AplicacaoError::EntradaPathDuplicate {
24804                path: "/api/cart".into(),
24805            }),
24806            "validate must trip EntradaPathDuplicate on the second entry \
24807             of a two-entry cohort that shares a path — routing through \
24808             the lifted paths() accessor must not silently short-circuit \
24809             the dedup HashSet insert at the first entry",
24810        );
24811    }
24812
24813    // ── Entrada::hostname / Entrada::hostnames — the substrate-
24814    //    canonical per-`:entrada` DNS-hostname resolver pair every
24815    //    Gateway-API-aware renderer reaching for a per-listener
24816    //    singular `hostname:` filter (Gateway) or a per-route plural
24817    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
24818    //    The three pin tests below fix the two-way accept-set the pair
24819    //    must always honor: (:singular-byte-equal-to-host,
24820    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
24821    //    on any arm surfaces at caixa-core build time rather than at
24822    //    cluster-apply time when the API server refuses the HTTPRoute
24823    //    for non-intersecting hostname filters. Peer discipline with
24824    //    the sibling `resolved_paths` accept-set pin block above on the
24825    //    per-`:entrada` path-list resolver axis.
24826
24827    fn entrada_with_host(host: &str) -> Entrada {
24828        Entrada {
24829            host: host.into(),
24830            para: "cart".into(),
24831            paths: Vec::new(),
24832            port: DEFAULT_SERVICO_PORT,
24833        }
24834    }
24835
24836    #[test]
24837    fn hostname_returns_entrada_host_byte_equal() {
24838        // The canonical singular-axis pin: [`Entrada::hostname`] must
24839        // return the `:entrada :host` field byte-for-byte, borrowed
24840        // from the typed slot's own [`String`] storage. Pins against a
24841        // future silent detour that re-normalized the host (an
24842        // accidental `.to_lowercase()` — validate_entrada_host already
24843        // enforces lowercase, so any re-normalization is redundant + a
24844        // drift surface between the validator and the accessor), a
24845        // trailing-`.` fully-qualified DNS shape substitution, or a
24846        // Punycode round-trip that lowered a Unicode host through IDNA.
24847        let e = entrada_with_host("checkout.quero.cloud");
24848        assert_eq!(
24849            e.hostname(),
24850            "checkout.quero.cloud",
24851            "Entrada::hostname must return :entrada :host verbatim \
24852             (got {:?})",
24853            e.hostname(),
24854        );
24855        assert_eq!(
24856            e.hostname(),
24857            e.host.as_str(),
24858            "Entrada::hostname must byte-equal the .host field access",
24859        );
24860    }
24861
24862    #[test]
24863    fn hostnames_returns_singleton_of_hostname_accessor() {
24864        // The pair-invariant pin: [`Entrada::hostnames`] must always
24865        // return exactly `vec![hostname()]` — the singleton list whose
24866        // sole entry is the substrate's canonical per-`:entrada`
24867        // singular hostname. Pins the two-consumer coherence axis: the
24868        // Gateway listener's singular `hostname:` filter and the
24869        // HTTPRoute's plural `spec.hostnames[]` filter list must
24870        // agree, else the Gateway API v1.x conformance layer rejects
24871        // the HTTPRoute at attach time with
24872        // `Accepted:False/NoMatchingParent` (the parent Gateway's
24873        // listener hostname doesn't intersect the route's hostname
24874        // filter list) — a divergence whose apply-time symptom is far
24875        // from any single-site commit and never surfaces in the
24876        // emitted YAML. Pinning the pair-invariant here makes any
24877        // future accidental split (an accidental `.to_string() + "."`
24878        // trailing-`.` on the plural side that didn't land on the
24879        // singular side, an accidental prefix stripping on one axis,
24880        // an accidental wildcard prepend the SNI fan-out overlay
24881        // authors on the plural side without a paired singular
24882        // migration) trip at caixa-core build time.
24883        let e = entrada_with_host("checkout.quero.cloud");
24884        assert_eq!(
24885            e.hostnames(),
24886            vec![e.hostname()],
24887            "Entrada::hostnames must return `vec![hostname()]` under \
24888             the pair-invariant — got {:?} vs. singleton {:?}",
24889            e.hostnames(),
24890            vec![e.hostname()],
24891        );
24892    }
24893
24894    #[test]
24895    fn hostnames_is_singleton_under_single_host_author_surface() {
24896        // The singleton-shape pin: under today's single-hostname-per-
24897        // `:entrada` author surface (the `:host` slot is a single
24898        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
24899        // must always return a list of length exactly one. Pins
24900        // against a future silent detour that returned an empty list
24901        // (which would emit an HTTPRoute with `spec.hostnames: []` —
24902        // matching every incoming Host header regardless of the
24903        // Aplicacao's declared ingress apex, silently over-matching
24904        // every foreign VirtualHost the parent Gateway also fronts) or
24905        // a duplicated entry (which the Gateway API v1.x parser
24906        // accepts as a `[]-length-2 list of equal hostnames]` but
24907        // whose semantics differ from the intended singleton). The
24908        // author-surface extension point ("a future `:entrada
24909        // :alt-hosts` list overlay" the docstring names) is the sole
24910        // future axis that flips this pin — that migration will re-
24911        // author this test to pin the new plural cardinality.
24912        let e = entrada_with_host("checkout.quero.cloud");
24913        assert_eq!(
24914            e.hostnames().len(),
24915            1,
24916            "Entrada::hostnames must be a singleton under today's \
24917             single-hostname-per-`:entrada` author surface — got \
24918             length {}: {:?}",
24919            e.hostnames().len(),
24920            e.hostnames(),
24921        );
24922    }
24923
24924    // ── Entrada::destination — the substrate-canonical per-`:entrada`
24925    //    destination-Servico scalar accessor every Gateway-API
24926    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
24927    //    discriminator arg (HTTPRoute name composer) or a per-rule
24928    //    `backendRefs[0].name` axis routes through. The two pin tests
24929    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
24930    //    either arm surfaces at caixa-core build time rather than at
24931    //    cluster-apply time when an HTTPRoute's `metadata.name` and
24932    //    `backendRefs[]` silently disagree on which destination Servico
24933    //    the ingress fronts. Peer discipline with the sibling
24934    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
24935    //    blocks above on the per-`:entrada` path-list / DNS-hostname
24936    //    resolver axes.
24937
24938    #[test]
24939    fn destination_returns_entrada_para_byte_equal() {
24940        // The canonical destination-scalar pin: [`Entrada::destination`]
24941        // must return the `:entrada :para` field byte-for-byte, borrowed
24942        // from the typed slot's own [`String`] storage. Pins against a
24943        // future silent detour that re-normalized the destination (an
24944        // accidental `.to_lowercase()` — the destination Servico is
24945        // already validated as a DNS-1123 label upstream, so any
24946        // re-normalization is redundant + a drift surface between the
24947        // validator and the accessor), a namespace-prefix rewrite (an
24948        // accidental `format!("{namespace}/{para}")` per-CR fully-
24949        // qualified rewrite that didn't land on the peer axis), or a
24950        // per-cluster suffix stamp the operator authors on one
24951        // consumer without the other.
24952        for para in ["cart", "checkout", "catalog", "orders-v2"] {
24953            let e = Entrada {
24954                host: "checkout.quero.cloud".into(),
24955                para: para.into(),
24956                paths: Vec::new(),
24957                port: DEFAULT_SERVICO_PORT,
24958            };
24959            assert_eq!(
24960                e.destination(),
24961                para,
24962                "Entrada::destination must return :entrada :para verbatim \
24963                 (got {:?}, expected {para:?})",
24964                e.destination(),
24965            );
24966            assert_eq!(
24967                e.destination(),
24968                e.para.as_str(),
24969                "Entrada::destination must byte-equal the .para field access",
24970            );
24971        }
24972    }
24973
24974    #[test]
24975    fn destination_borrows_from_entrada_para_storage() {
24976        // The borrow-not-copy pin: [`Entrada::destination`] must
24977        // return a `&str` slice that borrows from the typed slot's
24978        // own [`String`] storage — same-address invariant with
24979        // `entrada.para.as_str()`. Pins against a future silent detour
24980        // that allocated a fresh `String` (`self.para.clone()` in the
24981        // body would type-check but silently drop the borrow, and
24982        // every downstream consumer that assumed the returned slice
24983        // outlives `&self` would break on a stale-reference use-after-
24984        // free). Peer with the sibling `hostname_returns_entrada_
24985        // host_byte_equal` on the singular-DNS-hostname axis.
24986        let e = entrada_with_host("checkout.quero.cloud");
24987        let dest = e.destination();
24988        let para_slice = e.para.as_str();
24989        assert_eq!(
24990            dest.as_ptr(),
24991            para_slice.as_ptr(),
24992            "Entrada::destination must borrow from the .para String's \
24993             backing storage — a fresh allocation here means the \
24994             accessor no longer names the substrate-primitive typed \
24995             dispatch and every downstream consumer would silently \
24996             carry a detached copy",
24997        );
24998        assert_eq!(
24999            dest.len(),
25000            para_slice.len(),
25001            "Entrada::destination and .para.as_str() must byte-equal in \
25002             length as well as in address",
25003        );
25004    }
25005
25006    #[test]
25007    fn port_returns_entrada_port_verbatim_across_permutations() {
25008        // The canonical L4-port-scalar pin: [`Entrada::port`] must
25009        // return the `:entrada :port` field verbatim as a `u16` across
25010        // every author-declared value in the validated accept-set
25011        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
25012        // silent detour that clamped the port (an accidental
25013        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
25014        // land on the peer [`AplicacaoSpec::port_for_destination`]
25015        // resolver), rewrote it through a per-cluster port-remap table
25016        // the operator authors on one consumer without the other, or
25017        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
25018        // serde-default value (which would silently collapse the
25019        // distinction between "author explicitly declared `:port 8080`"
25020        // and "author omitted the slot and inherited the default" the
25021        // future per-cluster override slot depends on). Peer with the
25022        // sibling `destination_returns_entrada_para_byte_equal` +
25023        // `hostname_returns_entrada_host_byte_equal` pins on the
25024        // per-`:entrada` `&str` scalar axes.
25025        for port in [
25026            SERVICO_PORT_MIN,
25027            DEFAULT_SERVICO_PORT,
25028            8443u16,
25029            9090u16,
25030            u16::MAX,
25031        ] {
25032            let e = Entrada {
25033                host: "checkout.quero.cloud".into(),
25034                para: "cart".into(),
25035                paths: Vec::new(),
25036                port,
25037            };
25038            assert_eq!(
25039                e.port(),
25040                port,
25041                "Entrada::port must return :entrada :port verbatim \
25042                 (got {}, expected {port})",
25043                e.port(),
25044            );
25045            assert_eq!(
25046                e.port(),
25047                e.port,
25048                "Entrada::port accessor and .port field access must \
25049                 byte-equal — the accessor is the substrate-primitive \
25050                 typed dispatch every downstream L4-port consumer must \
25051                 route through",
25052            );
25053        }
25054    }
25055
25056    #[test]
25057    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
25058        // Two-consumer coherence pin: the
25059        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
25060        // (which reads through [`Entrada::port`] to compare against
25061        // [`SERVICO_PORT_MIN`]) and the
25062        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
25063        // through [`Entrada::port`] to emit the per-destination
25064        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
25065        // lifted accessor, so any future rebrand on the typed slot's
25066        // reader shape lands at exactly one place. Pins the two-site
25067        // coherence by exercising a below-floor port through validate
25068        // (which must reject) and a validated in-accept-set port through
25069        // port_for_destination (which must emit the same value the
25070        // accessor returns).
25071        let mut spec = three_member_spec();
25072        if let Some(e) = spec.entrada.as_mut() {
25073            e.port = 0;
25074        }
25075        assert_eq!(
25076            spec.validate().unwrap_err(),
25077            AplicacaoError::EntradaPortZero,
25078            "validate must reject `:entrada :port 0` through the lifted \
25079             Entrada::port accessor — port zero lies below \
25080             SERVICO_PORT_MIN and the validator routes through port() \
25081             to name the floor",
25082        );
25083
25084        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
25085            let mut spec = three_member_spec();
25086            if let Some(e) = spec.entrada.as_mut() {
25087                e.port = port;
25088            }
25089            spec.validate().expect(
25090                "entrada with in-accept-set :port must validate — the \
25091                 structural-floor gate reads through Entrada::port",
25092            );
25093            let entrada_ref = spec.entrada().expect(":entrada present");
25094            assert_eq!(
25095                spec.port_for_destination(entrada_ref.destination()),
25096                entrada_ref.port(),
25097                "port_for_destination(entrada.destination()) must equal \
25098                 entrada.port() — the two consumers of the per-:entrada \
25099                 L4-port axis (validator, per-destination resolver) both \
25100                 route through Entrada::port",
25101            );
25102        }
25103    }
25104
25105    #[test]
25106    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
25107        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
25108        // must return the `:contratos :de` field byte-for-byte, borrowed
25109        // from the typed slot's own [`String`] storage. Peer of the
25110        // sibling `destination_returns_entrada_para_byte_equal` pin on
25111        // the per-`:entrada` axis — same "the substrate-primitive
25112        // accessor must byte-equal the raw field access verbatim across
25113        // every author-declared value" discipline extended to the
25114        // per-`:contratos` caller arm. Pins against a future silent
25115        // detour that re-normalized the caller (an accidental
25116        // `.to_lowercase()` — every `:contratos :de` is validated as a
25117        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
25118        // re-normalization is redundant + a drift surface between the
25119        // validator and the accessor), a namespace-prefix rewrite (an
25120        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
25121        // rewrite that didn't land on the peer axis), or a per-cluster
25122        // suffix stamp the operator authors on one consumer without the
25123        // other.
25124        for de in ["cart", "checkout", "catalog", "orders-v2"] {
25125            let c = WitContract {
25126                de: de.into(),
25127                para: "downstream".into(),
25128                wit: "wasi:http/proxy".into(),
25129                endpoint: Some("/lookup".into()),
25130                subject: None,
25131                slot: None,
25132            };
25133            assert_eq!(
25134                c.source(),
25135                de,
25136                "WitContract::source must return :contratos :de verbatim \
25137                 (got {:?}, expected {de:?})",
25138                c.source(),
25139            );
25140            assert_eq!(
25141                c.source(),
25142                c.de.as_str(),
25143                "WitContract::source must byte-equal the .de field access",
25144            );
25145        }
25146    }
25147
25148    #[test]
25149    fn wit_contract_source_borrows_from_de_storage() {
25150        // The borrow-not-copy pin: [`WitContract::source`] must return a
25151        // `&str` slice that borrows from the typed slot's own [`String`]
25152        // storage — same-address invariant with `c.de.as_str()`. Pins
25153        // against a future silent detour that allocated a fresh `String`
25154        // (`self.de.clone()` in the body would type-check but silently
25155        // drop the borrow, and every downstream consumer that assumed
25156        // the returned slice outlives `&self` would break on a stale-
25157        // reference use-after-free). Peer of the sibling
25158        // `destination_borrows_from_entrada_para_storage` on the
25159        // per-`:entrada` axis.
25160        let c = WitContract {
25161            de: "cart".into(),
25162            para: "catalog".into(),
25163            wit: "wasi:http/proxy".into(),
25164            endpoint: Some("/lookup".into()),
25165            subject: None,
25166            slot: None,
25167        };
25168        let src = c.source();
25169        let de_slice = c.de.as_str();
25170        assert_eq!(
25171            src.as_ptr(),
25172            de_slice.as_ptr(),
25173            "WitContract::source must borrow from the .de String's \
25174             backing storage — a fresh allocation here means the \
25175             accessor no longer names the substrate-primitive typed \
25176             dispatch and every downstream consumer would silently \
25177             carry a detached copy",
25178        );
25179        assert_eq!(
25180            src.len(),
25181            de_slice.len(),
25182            "WitContract::source and .de.as_str() must byte-equal in \
25183             length as well as in address",
25184        );
25185    }
25186
25187    #[test]
25188    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
25189        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
25190        // must return the `:contratos :para` field byte-for-byte,
25191        // borrowed from the typed slot's own [`String`] storage. Peer of
25192        // the sibling `destination_returns_entrada_para_byte_equal` on
25193        // the per-`:entrada` axis — both accessors name "the destination-
25194        // Servico byte-string" concept on their respective mesh-slot
25195        // atoms (per-ingress apex vs. per-typed-edge callee) and both
25196        // must project the underlying `.para` field verbatim so every
25197        // downstream renderer that composes them with peer accessors
25198        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
25199        // per-edge L4 port emit site) reads the same byte-string the
25200        // author declared.
25201        for para in ["catalog", "payment", "orders", "inventory-v3"] {
25202            let c = WitContract {
25203                de: "cart".into(),
25204                para: para.into(),
25205                wit: "wasi:http/proxy".into(),
25206                endpoint: Some("/lookup".into()),
25207                subject: None,
25208                slot: None,
25209            };
25210            assert_eq!(
25211                c.destination(),
25212                para,
25213                "WitContract::destination must return :contratos :para \
25214                 verbatim (got {:?}, expected {para:?})",
25215                c.destination(),
25216            );
25217            assert_eq!(
25218                c.destination(),
25219                c.para.as_str(),
25220                "WitContract::destination must byte-equal the .para \
25221                 field access",
25222            );
25223        }
25224    }
25225
25226    #[test]
25227    fn wit_contract_destination_borrows_from_para_storage() {
25228        // The borrow-not-copy pin: [`WitContract::destination`] must
25229        // return a `&str` slice that borrows from the typed slot's own
25230        // [`String`] storage — same-address invariant with
25231        // `c.para.as_str()`. Peer of the sibling
25232        // `destination_borrows_from_entrada_para_storage` on the
25233        // per-`:entrada` axis.
25234        let c = WitContract {
25235            de: "cart".into(),
25236            para: "catalog".into(),
25237            wit: "wasi:http/proxy".into(),
25238            endpoint: Some("/lookup".into()),
25239            subject: None,
25240            slot: None,
25241        };
25242        let dest = c.destination();
25243        let para_slice = c.para.as_str();
25244        assert_eq!(
25245            dest.as_ptr(),
25246            para_slice.as_ptr(),
25247            "WitContract::destination must borrow from the .para \
25248             String's backing storage — a fresh allocation here means \
25249             the accessor no longer names the substrate-primitive typed \
25250             dispatch and every downstream consumer would silently \
25251             carry a detached copy",
25252        );
25253        assert_eq!(
25254            dest.len(),
25255            para_slice.len(),
25256            "WitContract::destination and .para.as_str() must byte-equal \
25257             in length as well as in address",
25258        );
25259    }
25260
25261    #[test]
25262    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
25263        // The canonical per-`:contratos` WIT-world-reference scalar pin:
25264        // [`WitContract::world_ref`] must return the `:contratos :wit`
25265        // field byte-for-byte, borrowed from the typed slot's own
25266        // [`String`] storage. Sibling of the peer per-`:contratos`
25267        // [`WitContract::source`] / [`WitContract::destination`]
25268        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
25269        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
25270        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
25271        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
25272        // "the substrate-primitive accessor must byte-equal the raw
25273        // field access verbatim across every author-declared value"
25274        // discipline extended to the per-`:contratos` WIT-world arm.
25275        // Pins against a future silent detour that re-canonicalized the
25276        // WIT world reference (an accidental `.to_lowercase()` pass that
25277        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
25278        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
25279        // gate is already lowercase-prefixed so any re-normalization is
25280        // redundant + a drift surface between the validator and the
25281        // accessor), an M4-promotion-shape rewrite that formatted a
25282        // typed WIT-world enum through [`Display`] and silently drifted
25283        // the printer output from the source `caixa.lisp`, or a per-
25284        // cluster WIT-alias rewrite that didn't land on the peer field-
25285        // access sites. Five values sweep the shape-dispatch accept-set
25286        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
25287        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
25288        // `wasi:keyvalue/`).
25289        for (wit, endpoint, subject, slot) in [
25290            ("wasi:http/proxy", Some("/lookup"), None, None),
25291            ("http:proxy", Some("/health"), None, None),
25292            ("nats:pub-sub", None, Some("orders.paid"), None),
25293            ("kafka:events", None, Some("checkout-events"), None),
25294            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
25295        ] {
25296            let c = WitContract {
25297                de: "cart".into(),
25298                para: "downstream".into(),
25299                wit: wit.into(),
25300                endpoint: endpoint.map(str::to_string),
25301                subject: subject.map(str::to_string),
25302                slot: slot.map(str::to_string),
25303            };
25304            assert_eq!(
25305                c.world_ref(),
25306                wit,
25307                "WitContract::world_ref must return :contratos :wit \
25308                 verbatim (got {:?}, expected {wit:?})",
25309                c.world_ref(),
25310            );
25311            assert_eq!(
25312                c.world_ref(),
25313                c.wit.as_str(),
25314                "WitContract::world_ref must byte-equal the .wit field \
25315                 access",
25316            );
25317        }
25318    }
25319
25320    #[test]
25321    fn wit_contract_world_ref_borrows_from_wit_storage() {
25322        // The borrow-not-copy pin: [`WitContract::world_ref`] must
25323        // return a `&str` slice that borrows from the typed slot's own
25324        // [`String`] storage — same-address invariant with
25325        // `c.wit.as_str()`. Pins against a future silent detour that
25326        // allocated a fresh `String` (`self.wit.clone()` in the body
25327        // would type-check but silently drop the borrow, and every
25328        // downstream consumer that assumed the returned slice outlives
25329        // `&self` would break on a stale-reference use-after-free — the
25330        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
25331        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
25332        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
25333        // / [`is_pubsub`][WitContract::is_pubsub] /
25334        // [`is_store`][WitContract::is_store] methods route through —
25335        // each borrow from the WitContract's own storage and each would
25336        // silently misbehave if this accessor produced a detached copy).
25337        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
25338        // [`WitContract::destination`] and per-`:entrada`
25339        // [`Entrada::destination`] / [`Entrada::hostname`] and
25340        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
25341        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
25342        let c = WitContract {
25343            de: "cart".into(),
25344            para: "catalog".into(),
25345            wit: "wasi:http/proxy".into(),
25346            endpoint: Some("/lookup".into()),
25347            subject: None,
25348            slot: None,
25349        };
25350        let world = c.world_ref();
25351        let wit_slice = c.wit.as_str();
25352        assert_eq!(
25353            world.as_ptr(),
25354            wit_slice.as_ptr(),
25355            "WitContract::world_ref must borrow from the .wit String's \
25356             backing storage — a fresh allocation here means the \
25357             accessor no longer names the substrate-primitive typed \
25358             dispatch and every downstream consumer would silently carry \
25359             a detached copy",
25360        );
25361        assert_eq!(
25362            world.len(),
25363            wit_slice.len(),
25364            "WitContract::world_ref and .wit.as_str() must byte-equal in \
25365             length as well as in address",
25366        );
25367    }
25368
25369    #[test]
25370    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
25371        // Sibling-triple invariant pin composing all three per-`:contratos`
25372        // substrate-primitive typed dispatches — [`WitContract::source`]
25373        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
25374        // [`WitContract::world_ref`] — at the joint
25375        // `(source(), destination(), world_ref())` call shape every
25376        // renderer that fans on per-edge caller-callee-shape identity
25377        // keys off. The invariant, evaluated per-contract:
25378        //
25379        //   (c.source(), c.destination(), c.world_ref())
25380        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
25381        //
25382        // Closes the last unlifted per-`:contratos` scalar axis — every
25383        // downstream consumer that reads the triple now routes through
25384        // exactly three typed dispatches on the substrate primitive,
25385        // not two typed + one open-coded field access. A future refactor
25386        // that silently split any one accessor's projection (an
25387        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
25388        // canonicalization that didn't reach the peer `source`/
25389        // `destination` arms, an accidental `source()` per-cluster
25390        // caller-alias rewrite that didn't land on the `world_ref` peer)
25391        // surfaces at caixa-core build time. Peer of the sibling per-
25392        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
25393        // per-`:entrada` `(hostname(), destination())` (6db982c /
25394        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
25395        // axes, extended to the per-`:contratos` triple.
25396        for (de, para, wit, endpoint, subject, slot) in [
25397            (
25398                "cart",
25399                "catalog",
25400                "wasi:http/proxy",
25401                Some("/lookup"),
25402                None,
25403                None,
25404            ),
25405            (
25406                "checkout",
25407                "orders",
25408                "nats:pub-sub",
25409                None,
25410                Some("orders.paid"),
25411                None,
25412            ),
25413            (
25414                "cart",
25415                "kv",
25416                "wasi:keyvalue/store",
25417                None,
25418                None,
25419                Some("carts/{cart_id}"),
25420            ),
25421            (
25422                "orders-v2",
25423                "inventory-v3",
25424                "http:proxy",
25425                Some("/reserve"),
25426                None,
25427                None,
25428            ),
25429        ] {
25430            let c = WitContract {
25431                de: de.into(),
25432                para: para.into(),
25433                wit: wit.into(),
25434                endpoint: endpoint.map(str::to_string),
25435                subject: subject.map(str::to_string),
25436                slot: slot.map(str::to_string),
25437            };
25438            assert_eq!(
25439                (c.source(), c.destination(), c.world_ref()),
25440                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
25441                "(WitContract::source, ::destination, ::world_ref) must \
25442                 project (.de, .para, .wit) verbatim across every author-\
25443                 declared triple (got ({:?}, {:?}, {:?}), expected \
25444                 ({de:?}, {para:?}, {wit:?}))",
25445                c.source(),
25446                c.destination(),
25447                c.world_ref(),
25448            );
25449        }
25450    }
25451
25452    #[test]
25453    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
25454        // The canonical per-`:contratos` owned-form caller-callee-pair
25455        // pin: [`WitContract::edge_pair`] must return the
25456        // `(source(), destination())` tuple in owned form byte-for-byte,
25457        // projected through the lifted [`WitContract::source`] /
25458        // [`WitContract::destination`] scalar accessors. Pins the
25459        // composite-projection invariant on the per-`:contratos`
25460        // mesh-slot atom — every author-declared `(de, para)` pair must
25461        // round-trip verbatim through the substrate primitive's typed
25462        // dispatch, so the nine [`AplicacaoError`] diagnostic-
25463        // construction sites the accessor now feeds
25464        // ([`AplicacaoError::EmptyWit`],
25465        // [`AplicacaoError::ContratoEndpointEmpty`],
25466        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
25467        // [`AplicacaoError::ContratoEndpointInvalid`],
25468        // [`AplicacaoError::ContratoSubjectEmpty`],
25469        // [`AplicacaoError::ContratoSubjectInvalid`],
25470        // [`AplicacaoError::ContratoSlotEmpty`],
25471        // [`AplicacaoError::ContratoSlotInvalid`],
25472        // [`AplicacaoError::ContratoDuplicate`]) all read the same
25473        // `(de, para)` label pair every author sees at the source
25474        // `caixa.lisp`. Pins against a future silent detour that swapped
25475        // the `.0` / `.1` arms (an accidental `(destination(),
25476        // source())` re-order in the body would silently invert every
25477        // downstream diagnostic's `de:` / `para:` label pair, silently
25478        // reversing the direction of every operator-facing typed error
25479        // arrow), a fresh-allocation shape drift (an accidental
25480        // `.to_string()` on one arm but not the other would leave the
25481        // owned/borrowed pair mismatched vs. the sibling `source()` /
25482        // `destination()` returns), or an M4 per-cluster caller/callee-
25483        // alias rewrite that landed on `source()` without reaching
25484        // `destination()` (or vice versa). Peer of the sibling per-
25485        // `:contratos` `(source, destination, world_ref)` triple
25486        // pin above on the mesh-slot-atom scalar-value axes, extended
25487        // to the owned-form pair-projection axis.
25488        for (de, para, wit, endpoint, subject, slot) in [
25489            (
25490                "cart",
25491                "catalog",
25492                "wasi:http/proxy",
25493                Some("/lookup"),
25494                None,
25495                None,
25496            ),
25497            (
25498                "checkout",
25499                "orders",
25500                "nats:pub-sub",
25501                None,
25502                Some("orders.paid"),
25503                None,
25504            ),
25505            (
25506                "cart",
25507                "kv",
25508                "wasi:keyvalue/store",
25509                None,
25510                None,
25511                Some("carts/{cart_id}"),
25512            ),
25513            (
25514                "orders-v2",
25515                "inventory-v3",
25516                "http:proxy",
25517                Some("/reserve"),
25518                None,
25519                None,
25520            ),
25521        ] {
25522            let c = WitContract {
25523                de: de.into(),
25524                para: para.into(),
25525                wit: wit.into(),
25526                endpoint: endpoint.map(str::to_string),
25527                subject: subject.map(str::to_string),
25528                slot: slot.map(str::to_string),
25529            };
25530            assert_eq!(
25531                c.edge_pair(),
25532                (de.to_string(), para.to_string()),
25533                "WitContract::edge_pair must return (:contratos :de, \
25534                 :contratos :para) as an owned tuple verbatim (got {:?}, \
25535                 expected ({de:?}, {para:?}))",
25536                c.edge_pair(),
25537            );
25538        }
25539    }
25540
25541    #[test]
25542    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
25543        // The composition pin: [`WitContract::edge_pair`] must return
25544        // exactly `(source().to_string(), destination().to_string())` —
25545        // the owned form of the sibling accessor pair — so any future
25546        // refactor that silently re-authored the caller-arm / callee-arm
25547        // projection to bypass the lifted scalar accessors (an accidental
25548        // `(self.de.clone(), self.para.clone())` regression back to the
25549        // raw field-access shape, an M4-typed-caller-enum `Display`
25550        // re-canonicalization on `source()` that didn't reach
25551        // `edge_pair()`, a per-cluster alias rewrite the operator lands
25552        // on `destination()` without reaching this composite projection)
25553        // trips at caixa-core build time. Pins the "typed dispatch
25554        // composes with typed dispatch, not with raw field access"
25555        // discipline every downstream diagnostic-construction site now
25556        // routes through — a `de:` / `para:` label pair whose
25557        // projection silently drifted off the substrate primitive's
25558        // scalar accessors would silently split the diagnostic's self-
25559        // locating signal from the source `caixa.lisp` author's view.
25560        // Peer of the sibling per-`:politicas` `is_empty` /
25561        // `validate_politicas` accessor-routing-pin family on the M3
25562        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
25563        let c = WitContract {
25564            de: "cart".into(),
25565            para: "catalog".into(),
25566            wit: "wasi:http/proxy".into(),
25567            endpoint: Some("/lookup".into()),
25568            subject: None,
25569            slot: None,
25570        };
25571        assert_eq!(
25572            c.edge_pair(),
25573            (c.source().to_string(), c.destination().to_string()),
25574            "WitContract::edge_pair must compose exactly \
25575             (source().to_string(), destination().to_string()) — a \
25576             bypass of either sibling accessor here would silently \
25577             decouple the composite-projection axis from the \
25578             substrate-primitive scalar accessors every downstream \
25579             consumer routes through",
25580        );
25581    }
25582
25583    #[test]
25584    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
25585     {
25586        // The canonical per-`:contratos` owned-form
25587        // caller-callee-world-ref-triple pin:
25588        // [`WitContract::edge_triple`] must return the
25589        // `(source(), destination(), world_ref())` tuple in owned form
25590        // byte-for-byte, projected through the lifted
25591        // [`WitContract::source`] / [`WitContract::destination`] /
25592        // [`WitContract::world_ref`] scalar accessors. Pins the
25593        // composite-projection invariant on the per-`:contratos`
25594        // mesh-slot atom — every author-declared `(de, para, wit)`
25595        // triple must round-trip verbatim through the substrate
25596        // primitive's typed dispatch, so the nine
25597        // [`AplicacaoError`] diagnostic-construction sites the
25598        // accessor now feeds (the [`WitTarget`]-dispatch's eight
25599        // wrong-target / missing-target / invalid-wit / capability-
25600        // with-payload arms in [`WitContract::target`], plus the
25601        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
25602        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
25603        // read the same `(de, para, wit)` triple every author sees at
25604        // the source `caixa.lisp`. Pins against a future silent
25605        // detour that swapped any two arms (an accidental `(destination(),
25606        // source(), world_ref())` re-order in the body would silently
25607        // invert every downstream diagnostic's `de:` / `para:` label
25608        // pair, silently reversing the direction of every operator-
25609        // facing typed error arrow), a fresh-allocation shape drift
25610        // (an accidental `.to_string()` skipped on one arm would leave
25611        // the owned/borrowed triple mismatched vs. the sibling
25612        // `source()` / `destination()` / `world_ref()` returns), or an
25613        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
25614        // canonicalization pass that landed on one accessor without
25615        // reaching the peers. Peer of the sibling per-`:contratos`
25616        // caller-callee-pair
25617        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
25618        // pin on the mesh-slot-atom composite-projection axis,
25619        // extended to the triple-projection axis.
25620        for (de, para, wit, endpoint, subject, slot) in [
25621            (
25622                "cart",
25623                "catalog",
25624                "wasi:http/proxy",
25625                Some("/lookup"),
25626                None,
25627                None,
25628            ),
25629            (
25630                "checkout",
25631                "orders",
25632                "nats:pub-sub",
25633                None,
25634                Some("orders.paid"),
25635                None,
25636            ),
25637            (
25638                "cart",
25639                "kv",
25640                "wasi:keyvalue/store",
25641                None,
25642                None,
25643                Some("carts/{cart_id}"),
25644            ),
25645            (
25646                "orders-v2",
25647                "inventory-v3",
25648                "http:proxy",
25649                Some("/reserve"),
25650                None,
25651                None,
25652            ),
25653        ] {
25654            let c = WitContract {
25655                de: de.into(),
25656                para: para.into(),
25657                wit: wit.into(),
25658                endpoint: endpoint.map(str::to_string),
25659                subject: subject.map(str::to_string),
25660                slot: slot.map(str::to_string),
25661            };
25662            assert_eq!(
25663                c.edge_triple(),
25664                (de.to_string(), para.to_string(), wit.to_string()),
25665                "WitContract::edge_triple must return (:contratos :de, \
25666                 :contratos :para, :contratos :wit) as an owned triple \
25667                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
25668                c.edge_triple(),
25669            );
25670        }
25671    }
25672
25673    #[test]
25674    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
25675        // The composition pin: [`WitContract::edge_triple`] must return
25676        // exactly `(source().to_string(), destination().to_string(),
25677        // world_ref().to_string())` — the owned form of the sibling
25678        // scalar-accessor triple — so any future refactor that silently
25679        // re-authored one arm's projection to bypass the lifted scalar
25680        // accessors (an accidental `(self.de.clone(), self.para.clone(),
25681        // self.wit.clone())` regression back to the raw field-access
25682        // shape the internal `edge` closure and the ContratoDuplicate
25683        // diagnostic both carried before this lift landed, an
25684        // M4-typed-caller-enum `Display` re-canonicalization on
25685        // `source()` that didn't reach `edge_triple()`, a per-cluster
25686        // alias rewrite the operator lands on `destination()` /
25687        // `world_ref()` without reaching this composite projection)
25688        // trips at caixa-core build time. Pins the "typed dispatch
25689        // composes with typed dispatch, not with raw field access"
25690        // discipline every downstream diagnostic-construction site now
25691        // routes through — a `de:` / `para:` / `wit:` triple whose
25692        // projection silently drifted off the substrate primitive's
25693        // scalar accessors would silently split the diagnostic's self-
25694        // locating signal from the source `caixa.lisp` author's view.
25695        // Peer of the sibling per-`:contratos` edge_pair composition-
25696        // pin above on the mesh-slot-atom composite-projection axis.
25697        let c = WitContract {
25698            de: "cart".into(),
25699            para: "catalog".into(),
25700            wit: "wasi:http/proxy".into(),
25701            endpoint: Some("/lookup".into()),
25702            subject: None,
25703            slot: None,
25704        };
25705        assert_eq!(
25706            c.edge_triple(),
25707            (
25708                c.source().to_string(),
25709                c.destination().to_string(),
25710                c.world_ref().to_string(),
25711            ),
25712            "WitContract::edge_triple must compose exactly \
25713             (source().to_string(), destination().to_string(), \
25714             world_ref().to_string()) — a bypass of any sibling accessor \
25715             here would silently decouple the composite-projection axis \
25716             from the substrate-primitive scalar accessors every \
25717             downstream consumer routes through",
25718        );
25719    }
25720
25721    #[test]
25722    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
25723        // The canonical semantics-pin: [`WitContract::edge_triple`] must
25724        // project the full `(de, para, wit)` identity of a `:contratos`
25725        // edge — the sub-triple every triple-carrying
25726        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
25727        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
25728        // missing-target, capability-with-payload, invalid-wit, and the
25729        // duplicate-gate). Rejects a drift in shape (an accidental
25730        // silent detour that returned a `(de, para)` pair or added an
25731        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
25732        // would trip here because the return type would no longer
25733        // pattern-match the eight `let (de, para, wit) = edge();`
25734        // destructures the [`WitContract::target`] dispatch feeds off
25735        // + the paired duplicate-gate `let (de, para, wit) =
25736        // c.edge_triple();` destructure in
25737        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
25738        // `:contratos` caller-callee-pair pin above extended to the
25739        // triple projection surface: closes the "one composite
25740        // accessor per typed diagnostic-construction sub-tuple"
25741        // discipline on the per-`:contratos` mesh-slot-atom axis.
25742        let c = WitContract {
25743            de: "checkout".into(),
25744            para: "orders".into(),
25745            wit: "nats:pub-sub".into(),
25746            endpoint: None,
25747            subject: Some("orders.paid".into()),
25748            slot: None,
25749        };
25750        let (de, para, wit) = c.edge_triple();
25751        assert_eq!(de, "checkout");
25752        assert_eq!(para, "orders");
25753        assert_eq!(wit, "nats:pub-sub");
25754    }
25755
25756    #[test]
25757    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
25758     {
25759        // The composition pin: [`WitContract::identity`] must return
25760        // exactly `(source(), destination(), world_ref(), endpoint(),
25761        // subject(), slot())` — the borrowed form of the six-scalar-
25762        // accessor identity axis. Any future refactor that silently
25763        // re-authored one arm's projection to bypass a scalar accessor
25764        // (a `self.de.as_str()` regression back to raw field access on
25765        // any of the three required arms, a `self.endpoint.as_deref()`
25766        // regression on any of the three optional arms, an M4 per-
25767        // cluster caller/callee-alias rewrite the operator lands on
25768        // `source()` / `destination()` without reaching this composite
25769        // projection) trips at caixa-core build time. Sweeps four
25770        // permutations of the WIT-shape × payload lattice — HTTP with
25771        // endpoint, pub-sub with subject, store with slot, payload-less
25772        // capability — so every payload arm is exercised. Peer of the
25773        // sibling per-`:contratos`
25774        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
25775        // composition pin on the mesh-slot-atom composite-projection
25776        // axis; extends the discipline from the (de, para, wit) prefix
25777        // onto the full-identity axis carrying the three payload arms.
25778        for (de, para, wit, endpoint, subject, slot) in [
25779            (
25780                "cart",
25781                "catalog",
25782                "wasi:http/proxy",
25783                Some("/lookup"),
25784                None,
25785                None,
25786            ),
25787            (
25788                "checkout",
25789                "orders",
25790                "nats:pub-sub",
25791                None,
25792                Some("orders.paid"),
25793                None,
25794            ),
25795            (
25796                "cart",
25797                "kv",
25798                "wasi:keyvalue/store",
25799                None,
25800                None,
25801                Some("carts/{cart_id}"),
25802            ),
25803            ("audit", "sink", "wasi:logging", None, None, None),
25804        ] {
25805            let c = WitContract {
25806                de: de.into(),
25807                para: para.into(),
25808                wit: wit.into(),
25809                endpoint: endpoint.map(str::to_owned),
25810                subject: subject.map(str::to_owned),
25811                slot: slot.map(str::to_owned),
25812            };
25813            assert_eq!(
25814                c.identity(),
25815                (
25816                    c.source(),
25817                    c.destination(),
25818                    c.world_ref(),
25819                    c.endpoint(),
25820                    c.subject(),
25821                    c.slot(),
25822                ),
25823                "WitContract::identity must compose exactly \
25824                 (source(), destination(), world_ref(), endpoint(), \
25825                 subject(), slot()) — a bypass of any sibling accessor \
25826                 here would silently decouple the identity-projection \
25827                 axis from the substrate-primitive scalar accessors \
25828                 every dedup-key consumer routes through",
25829            );
25830        }
25831    }
25832
25833    #[test]
25834    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
25835        // The canonical semantics-pin: [`WitContract::identity`] must
25836        // project the six-axis (de, para, wit, endpoint, subject, slot)
25837        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
25838        // gate keys off — two `WitContract`s that agree on all six axes
25839        // are the same typed edge declared twice, the graph-edge
25840        // analogue of duplicate `:membros` / `:placement :clusters` /
25841        // `:entrada :paths` entries. Rejects a shape drift (an
25842        // accidental silent detour that returned a prefix tuple or
25843        // added an extra field) by pattern-matching the six-arm shape.
25844        // Peer of the sibling per-`:contratos`
25845        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
25846        // pin extended from the (de, para, wit) prefix onto the full
25847        // six-axis identity that the dedup key rides.
25848        let c = WitContract {
25849            de: "cart".into(),
25850            para: "catalog".into(),
25851            wit: "wasi:http/proxy".into(),
25852            endpoint: Some("/products/:id".into()),
25853            subject: None,
25854            slot: None,
25855        };
25856        let (de, para, wit, endpoint, subject, slot) = c.identity();
25857        assert_eq!(de, "cart");
25858        assert_eq!(para, "catalog");
25859        assert_eq!(wit, "wasi:http/proxy");
25860        assert_eq!(endpoint, Some("/products/:id"));
25861        assert_eq!(subject, None);
25862        assert_eq!(slot, None);
25863
25864        // Two byte-identical contracts must produce equal identities —
25865        // the dedup key's foundational invariant.
25866        let c2 = c.clone();
25867        assert_eq!(c.identity(), c2.identity());
25868
25869        // Any change on any of the six axes must break the identity —
25870        // sweeps by mutating one axis at a time.
25871        let mut mutated = c.clone();
25872        mutated.de = "search".into();
25873        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
25874        let mut mutated = c.clone();
25875        mutated.para = "warehouse".into();
25876        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
25877        let mut mutated = c.clone();
25878        mutated.wit = "http:legacy".into();
25879        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
25880        let mut mutated = c.clone();
25881        mutated.endpoint = Some("/search".into());
25882        assert_ne!(
25883            c.identity(),
25884            mutated.identity(),
25885            "endpoint axis must partition"
25886        );
25887        let mut mutated = c.clone();
25888        mutated.subject = Some("orders.paid".into());
25889        assert_ne!(
25890            c.identity(),
25891            mutated.identity(),
25892            "subject axis must partition"
25893        );
25894        let mut mutated = c;
25895        mutated.slot = Some("carts/{id}".into());
25896        assert_ne!(mutated.identity().5, None, "slot axis must partition");
25897    }
25898
25899    #[test]
25900    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
25901        // The canonical per-`:contratos` structural-self-edge pin:
25902        // [`WitContract::is_self_loop`] must return `true` when the
25903        // `:de` and `:para` fields agree byte-for-byte, across every
25904        // WIT-shape variant the per-edge shape family carries. Pins
25905        // the shape-agnostic identity-space partition the
25906        // [`AplicacaoSpec::validate`] self-edge gate at
25907        // caixa-core/src/aplicacao.rs:5559 fires against — all four
25908        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
25909        // under the same one predicate. Four permutations sweep the
25910        // accept-set: HTTP with endpoint, pub-sub with subject, KV
25911        // store with slot, and payload-less capability.
25912        for (nome, wit, endpoint, subject, slot) in [
25913            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
25914            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
25915            (
25916                "kv",
25917                "wasi:keyvalue/store",
25918                None,
25919                None,
25920                Some("carts/{cart_id}"),
25921            ),
25922            ("audit", "wasi:logging", None, None, None),
25923        ] {
25924            let c = WitContract {
25925                de: nome.into(),
25926                para: nome.into(),
25927                wit: wit.into(),
25928                endpoint: endpoint.map(str::to_string),
25929                subject: subject.map(str::to_string),
25930                slot: slot.map(str::to_string),
25931            };
25932            assert!(
25933                c.is_self_loop(),
25934                "WitContract::is_self_loop must return true when \
25935                 :contratos :de == :contratos :para (got false on \
25936                 {nome:?} under {wit:?})",
25937            );
25938        }
25939    }
25940
25941    #[test]
25942    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
25943        // The complement pin: [`WitContract::is_self_loop`] must return
25944        // `false` on every well-shaped inter-Servico contract (the
25945        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
25946        // names — "Servico A calls Servico B" between two distinct
25947        // graph nodes). Pins against a future silent detour that
25948        // inverted the predicate (an accidental `!= ` swap for `==`
25949        // would silently reject every legitimate inter-Servico edge
25950        // and admit every self-edge — the exact inversion of the
25951        // author-intended shape). Four permutations sweep the same
25952        // WIT-shape accept-set the sibling positive-arm test carries.
25953        for (de, para, wit, endpoint, subject, slot) in [
25954            (
25955                "cart",
25956                "catalog",
25957                "wasi:http/proxy",
25958                Some("/lookup"),
25959                None,
25960                None,
25961            ),
25962            (
25963                "checkout",
25964                "orders",
25965                "nats:pub-sub",
25966                None,
25967                Some("orders.paid"),
25968                None,
25969            ),
25970            (
25971                "cart",
25972                "kv",
25973                "wasi:keyvalue/store",
25974                None,
25975                None,
25976                Some("carts/{cart_id}"),
25977            ),
25978            ("audit", "sink", "wasi:logging", None, None, None),
25979        ] {
25980            let c = WitContract {
25981                de: de.into(),
25982                para: para.into(),
25983                wit: wit.into(),
25984                endpoint: endpoint.map(str::to_string),
25985                subject: subject.map(str::to_string),
25986                slot: slot.map(str::to_string),
25987            };
25988            assert!(
25989                !c.is_self_loop(),
25990                "WitContract::is_self_loop must return false when \
25991                 :contratos :de differs from :contratos :para (got true \
25992                 on {de:?} → {para:?} under {wit:?})",
25993            );
25994        }
25995    }
25996
25997    #[test]
25998    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
25999        // The composition pin: [`WitContract::is_self_loop`] must
26000        // resolve to exactly `self.source() == self.destination()` —
26001        // the equality probe of the sibling scalar-accessor pair — so
26002        // any future refactor that silently re-authored the predicate
26003        // to bypass the lifted scalar accessors (an accidental
26004        // `self.de == self.para` regression back to the raw field-
26005        // access shape, an M4-typed-caller-enum identity-comparison
26006        // rule that landed on `source()` without reaching
26007        // `destination()`, a per-cluster alias rewrite the operator
26008        // pins on `destination()` without reaching this predicate)
26009        // trips at caixa-core build time. Pins the "typed dispatch
26010        // composes with typed dispatch, not with raw field access"
26011        // discipline the sibling [`WitContract::edge_pair`] /
26012        // [`WitContract::edge_triple`] composite-projection accessors
26013        // already carry, extended onto the per-edge endpoint-equality
26014        // predicate axis. Positive and complement arms both fire.
26015        let self_edge = WitContract {
26016            de: "cart".into(),
26017            para: "cart".into(),
26018            wit: "wasi:http/proxy".into(),
26019            endpoint: Some("/lookup".into()),
26020            subject: None,
26021            slot: None,
26022        };
26023        assert_eq!(
26024            self_edge.is_self_loop(),
26025            self_edge.source() == self_edge.destination(),
26026            "WitContract::is_self_loop must compose exactly \
26027             `source() == destination()` — a bypass of either sibling \
26028             accessor here would silently decouple the endpoint-\
26029             equality predicate from the substrate-primitive scalar \
26030             accessors every downstream consumer routes through",
26031        );
26032        let inter_edge = WitContract {
26033            de: "cart".into(),
26034            para: "catalog".into(),
26035            wit: "wasi:http/proxy".into(),
26036            endpoint: Some("/lookup".into()),
26037            subject: None,
26038            slot: None,
26039        };
26040        assert_eq!(
26041            inter_edge.is_self_loop(),
26042            inter_edge.source() == inter_edge.destination(),
26043            "WitContract::is_self_loop must compose exactly \
26044             `source() == destination()` on the complement arm too",
26045        );
26046    }
26047
26048    #[test]
26049    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
26050        // The composition pin: [`WitContract::target`]'s invalid-wit
26051        // value-shape gate must feed the reason string through the
26052        // lifted [`WitContract::world_ref`] scalar accessor — the same
26053        // typed dispatch on the substrate primitive every peer
26054        // per-`:contratos` payload-carrier extraction in the same
26055        // method body already routes through
26056        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
26057        // [`WitContract::subject`] on the pub-sub-arm target extraction,
26058        // [`WitContract::slot`] on the store-arm target extraction) and
26059        // every peer composite-projection accessor
26060        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
26061        // [`WitContract::identity`]) already composes from. Any future
26062        // refactor that silently re-authored the gate to bypass the
26063        // lifted accessor (an accidental `&self.wit` regression back to
26064        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
26065        // re-canonicalization on `world_ref()` that didn't reach this
26066        // gate, a per-CR lowercasing canonicalization pass the M4
26067        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
26068        // per-tenant that lands on `world_ref()` without reaching this
26069        // gate) would silently split the invalid-wit diagnostic reason
26070        // from the substrate-primitive projection every downstream
26071        // consumer routes through. Same "typed dispatch composes with
26072        // typed dispatch, not with raw field access" discipline the
26073        // sibling
26074        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
26075        // pin already carries on the endpoint-equality predicate axis,
26076        // extended onto the invalid-wit value-shape gate axis inside
26077        // the same [`WitContract::target`] body. Closes the last
26078        // unlifted raw-field-access site inside `impl WitContract`.
26079        //
26080        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
26081        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
26082        // to a capability-only edge; the value-shape gate rejects it
26083        // through [`crate::render::is_wit_world_ref`] on the substrate
26084        // primitive's ASCII-lowercase-only accept-set, with a
26085        // parser-shaped reason string the test asserts round-trips
26086        // byte-for-byte between the direct-dispatch call (through the
26087        // predicate on the accessor's projection) and the
26088        // [`WitContract::target`] gate's produced reason field.
26089        let c = WitContract {
26090            de: "cart".into(),
26091            para: "catalog".into(),
26092            wit: "WASI:HTTP/proxy".into(),
26093            endpoint: Some("/lookup".into()),
26094            subject: None,
26095            slot: None,
26096        };
26097        let err = c.target().unwrap_err();
26098        let AplicacaoError::ContratoWitInvalid {
26099            ref de,
26100            ref para,
26101            ref wit,
26102            ref reason,
26103        } = err
26104        else {
26105            panic!("expected ContratoWitInvalid, got {err:?}");
26106        };
26107        assert_eq!(de, "cart");
26108        assert_eq!(para, "catalog");
26109        assert_eq!(wit, "WASI:HTTP/proxy");
26110        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
26111        assert_eq!(
26112            *reason, expected_reason,
26113            "WitContract::target's invalid-wit value-shape gate reason \
26114             must compose exactly is_wit_world_ref(self.world_ref()) — \
26115             a bypass here (e.g. a raw `&self.wit` field-access \
26116             regression, or a divergent predicate on a different \
26117             projection) would silently decouple the invalid-wit \
26118             diagnostic's reason field from the substrate-primitive \
26119             scalar accessor every peer per-`:contratos` extraction in \
26120             the same method body already routes through",
26121        );
26122    }
26123
26124    #[test]
26125    fn wit_contract_is_self_loop_predicate_is_const_fn() {
26126        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
26127        // caller-callee identity-space predicate's `const`-eval-surface
26128        // posture. The wrapper below dispatches through
26129        // [`WitContract::is_self_loop`] and is well-formed only when the
26130        // callee is itself `pub const fn` — any future accidental
26131        // downgrade to non-`const` fails the wrapper at caixa-core build
26132        // time with E0015 (`cannot call non-const method`), strictly
26133        // stronger than a runtime `assert!` and strictly stronger than a
26134        // module-scope `const _: () = assert!(…)` pin (the type's
26135        // `String` / `Option<String>` carriers rule out `const`-context
26136        // value construction; the `const fn` wrapper is the load-bearing
26137        // shape that side-steps the destructor-in-const restriction on
26138        // the value axis while still pinning the `const`-fn posture on
26139        // the callee — mirror of the sibling
26140        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
26141        // (279823b) and
26142        // [`wit_contract_identity_projection_accessor_is_const_fn`]
26143        // (1ab648c) pins' discipline verbatim on the peer scalar-
26144        // accessor and composite-projection surfaces). Closes the last
26145        // unlifted per-`:contratos` shape/identity predicate on the
26146        // const-eval surface — the peer WIT-shape-partition family
26147        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
26148        // [`WitContract::is_store`] / [`WitContract::is_capability`]
26149        // already carried the `pub const fn` posture on the peer
26150        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
26151        // this pin extends the same posture onto the caller-callee
26152        // identity-space partition. Sweeps every WIT-shape arm on both
26153        // the equal-endpoints (self-edge) and distinct-endpoints
26154        // (inter-edge) arms of the identity-space partition, plus one
26155        // same-length distinct-byte pair to pin the mid-loop `!=` arm
26156        // past the leading length-mismatch shortcut.
26157        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
26158            c.is_self_loop()
26159        }
26160        let mk = |de: &str, para: &str, wit: &str| WitContract {
26161            de: de.into(),
26162            para: para.into(),
26163            wit: wit.into(),
26164            endpoint: None,
26165            subject: None,
26166            slot: None,
26167        };
26168        for (nome, wit) in [
26169            ("cart", "wasi:http/proxy"),
26170            ("checkout", "nats:pub-sub"),
26171            ("kv", "wasi:keyvalue/store"),
26172            ("audit", "wasi:logging"),
26173        ] {
26174            let self_edge = mk(nome, nome, wit);
26175            assert!(
26176                is_self_loop_via_const_fn(&self_edge),
26177                "self-edge {nome:?} under {wit:?}"
26178            );
26179            assert_eq!(
26180                is_self_loop_via_const_fn(&self_edge),
26181                self_edge.is_self_loop()
26182            );
26183        }
26184        for (de, para, wit) in [
26185            ("cart", "catalog", "wasi:http/proxy"),
26186            ("checkout", "orders", "nats:pub-sub"),
26187            ("cart", "kv", "wasi:keyvalue/store"),
26188            ("audit", "sink", "wasi:logging"),
26189        ] {
26190            let inter_edge = mk(de, para, wit);
26191            assert!(
26192                !is_self_loop_via_const_fn(&inter_edge),
26193                "inter-edge {de:?}→{para:?} under {wit:?}",
26194            );
26195            assert_eq!(
26196                is_self_loop_via_const_fn(&inter_edge),
26197                inter_edge.is_self_loop()
26198            );
26199        }
26200        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
26201        // past the leading `a.len() != b.len()` shortcut so the const-fn
26202        // wrapper exercises every arm of the byte-slice equality loop.
26203        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
26204        assert!(
26205            !is_self_loop_via_const_fn(&same_len_pair),
26206            "same-length distinct-byte"
26207        );
26208        assert_eq!(
26209            is_self_loop_via_const_fn(&same_len_pair),
26210            same_len_pair.is_self_loop()
26211        );
26212    }
26213
26214    #[test]
26215    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
26216        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
26217        // pin: [`WitContract::endpoint`] must return the `:contratos
26218        // :endpoint` field byte-for-byte, borrowed from the typed slot's
26219        // own `Option<String>` storage. Peer of the sibling
26220        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
26221        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
26222        // mesh-slot `Option<String>` optional-scalar axes — same "the
26223        // substrate-primitive accessor must byte-equal the raw field
26224        // access verbatim across every author-declared value" discipline
26225        // extended to the per-`:contratos` HTTP-payload-carrier arm.
26226        // Pins against a future silent detour that re-canonicalized the
26227        // endpoint (an accidental percent-encoding pass that didn't
26228        // reach the peer field-access site at the dedup key, a per-CR
26229        // fully-qualified prefix rewrite the operator authors on one
26230        // consumer without the other, or an M4 typed-path-template
26231        // `Display` re-canonicalization that silently drifted the
26232        // printer output from the source `caixa.lisp`). Four values
26233        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
26234        // gate upstream admits (short root-path, dashed, param-shaped,
26235        // deep-hierarchy).
26236        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
26237            let c = WitContract {
26238                de: "cart".into(),
26239                para: "catalog".into(),
26240                wit: "wasi:http/proxy".into(),
26241                endpoint: Some(endpoint.into()),
26242                subject: None,
26243                slot: None,
26244            };
26245            assert_eq!(
26246                c.endpoint(),
26247                Some(endpoint),
26248                "WitContract::endpoint must return :contratos :endpoint \
26249                 verbatim (got {:?}, expected Some({endpoint:?}))",
26250                c.endpoint(),
26251            );
26252            assert_eq!(
26253                c.endpoint(),
26254                c.endpoint.as_deref(),
26255                "WitContract::endpoint must byte-equal the .endpoint \
26256                 field's `.as_deref()` projection",
26257            );
26258        }
26259    }
26260
26261    #[test]
26262    fn wit_contract_endpoint_none_when_field_is_none() {
26263        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
26264        // payload-carrier accessor pin: when the typed slot is absent —
26265        // the canonical shape under a non-HTTP `:wit` world per the
26266        // [`WitContract::target`]-enforced shape ↔ target partition
26267        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
26268        // carries `:slot`, [`WitTarget::Capability`] carries none) —
26269        // [`WitContract::endpoint`] must return `None`. Pins against a
26270        // future silent detour that projected the absent slot to a
26271        // `Some("")` empty-string default (the canonical `Option<String>`
26272        // → `String` collapse footgun the sibling M2
26273        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26274        // emptiness predicates already guard on the peer M2 typed-slot
26275        // surfaces), a `Some("None")` stringified-None round-trip, or a
26276        // `Some` arm whose contents were derived from a sibling slot (an
26277        // accidental fallback to the `:subject` / `:slot` payload that
26278        // read the pub-sub / store payload into the endpoint axis).
26279        // Three contracts sweep the accept-set every non-HTTP `:wit`
26280        // world lands on — pub-sub NATS, key/value, and payload-less
26281        // capability.
26282        for (wit, subject, slot) in [
26283            ("nats:pub-sub", Some("orders.paid"), None),
26284            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
26285            ("wasi:cli/environment", None, None),
26286        ] {
26287            let c = WitContract {
26288                de: "cart".into(),
26289                para: "downstream".into(),
26290                wit: wit.into(),
26291                endpoint: None,
26292                subject: subject.map(str::to_string),
26293                slot: slot.map(str::to_string),
26294            };
26295            assert!(
26296                c.endpoint().is_none(),
26297                "WitContract::endpoint must return None when the typed \
26298                 slot is absent under :wit {wit:?} (got {:?})",
26299                c.endpoint(),
26300            );
26301            assert_eq!(
26302                c.endpoint(),
26303                c.endpoint.as_deref(),
26304                "WitContract::endpoint must byte-equal the .endpoint \
26305                 field's `.as_deref()` projection in the absent arm",
26306            );
26307        }
26308    }
26309
26310    #[test]
26311    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
26312        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
26313        // an `Option<&str>` whose `Some` arm borrows from the typed
26314        // slot's own [`String`] storage — same-address invariant with
26315        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
26316        // detour that allocated a fresh `String`
26317        // (`self.endpoint.clone().map(...)` in the body would type-check
26318        // but silently drop the borrow, and every downstream consumer
26319        // that assumed the returned slice outlives `&self` would break
26320        // on a stale-reference use-after-free — the [`WitContract::target`]
26321        // Http-arm payload extraction rebinds the returned `Option<&str>`
26322        // through `.ok_or_else(...)` and threads the `&str` payload into
26323        // [`WitTarget::Http { endpoint: &'a str }`], the
26324        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
26325        // [`ContratoIdentity`] dedup key threads the returned
26326        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
26327        // from the WitContract's own storage and each would silently
26328        // misbehave if this accessor produced a detached copy). Peer of
26329        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
26330        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
26331        // shaped optional-scalar axes — first extension of the
26332        // `Option<&str>` borrow-not-copy discipline onto the
26333        // per-`:contratos` HTTP-shaped payload-carrier axis.
26334        let c = WitContract {
26335            de: "cart".into(),
26336            para: "catalog".into(),
26337            wit: "wasi:http/proxy".into(),
26338            endpoint: Some("/lookup".into()),
26339            subject: None,
26340            slot: None,
26341        };
26342        let ep = c.endpoint().expect("Some arm");
26343        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
26344        assert_eq!(
26345            ep.as_ptr(),
26346            storage_slice.as_ptr(),
26347            "WitContract::endpoint must borrow from the .endpoint \
26348             String's backing storage — a fresh allocation here means \
26349             the accessor no longer names the substrate-primitive typed \
26350             dispatch and every downstream consumer would silently \
26351             carry a detached copy",
26352        );
26353        assert_eq!(
26354            ep.len(),
26355            storage_slice.len(),
26356            "WitContract::endpoint and .endpoint.as_deref() must byte-\
26357             equal in length as well as in address",
26358        );
26359    }
26360
26361    #[test]
26362    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
26363        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
26364        // pin: [`WitContract::subject`] must return the `:contratos
26365        // :subject` field byte-for-byte, borrowed from the typed slot's
26366        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
26367        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
26368        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
26369        // optional-scalar axis — same "the substrate-primitive accessor
26370        // must byte-equal the raw field access verbatim across every
26371        // author-declared value" discipline extended to the pub-sub arm.
26372        // Pins against a future silent detour that re-canonicalized the
26373        // subject (an accidental `.to_lowercase()` normalization that
26374        // didn't reach the peer field-access site at the dedup key, a
26375        // per-CR fully-qualified prefix rewrite the operator authors on
26376        // one consumer without the other, or an M4 typed-subject-template
26377        // `Display` re-canonicalization that silently drifted the printer
26378        // output from the source `caixa.lisp`). Four values sweep the
26379        // NATS accept-set every pub-sub author-declared subject lands on
26380        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
26381        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
26382            let c = WitContract {
26383                de: "cart".into(),
26384                para: "notifier".into(),
26385                wit: "nats:pub-sub".into(),
26386                endpoint: None,
26387                subject: Some(subject.into()),
26388                slot: None,
26389            };
26390            assert_eq!(
26391                c.subject(),
26392                Some(subject),
26393                "WitContract::subject must return :contratos :subject \
26394                 verbatim (got {:?}, expected Some({subject:?}))",
26395                c.subject(),
26396            );
26397            assert_eq!(
26398                c.subject(),
26399                c.subject.as_deref(),
26400                "WitContract::subject must byte-equal the .subject \
26401                 field's `.as_deref()` projection",
26402            );
26403        }
26404    }
26405
26406    #[test]
26407    fn wit_contract_subject_none_when_field_is_none() {
26408        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
26409        // shaped payload-carrier accessor pin: when the typed slot is
26410        // absent — the canonical shape under a non-pub-sub `:wit` world
26411        // per the [`WitContract::target`]-enforced shape ↔ target
26412        // partition ([`WitTarget::Http`] carries `:endpoint`,
26413        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
26414        // carries none) — [`WitContract::subject`] must return `None`.
26415        // Pins against a future silent detour that projected the absent
26416        // slot to a `Some("")` empty-string default (the canonical
26417        // `Option<String>` → `String` collapse footgun the sibling M2
26418        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26419        // emptiness predicates already guard on the peer M2 typed-slot
26420        // surfaces), a `Some("None")` stringified-None round-trip, or a
26421        // `Some` arm whose contents were derived from a sibling slot (an
26422        // accidental fallback to the `:endpoint` / `:slot` payload that
26423        // read the HTTP / store payload into the subject axis). Three
26424        // contracts sweep the accept-set every non-pub-sub `:wit` world
26425        // lands on — HTTP proxy, key/value store, and payload-less
26426        // capability.
26427        for (wit, endpoint, slot) in [
26428            ("wasi:http/proxy", Some("/lookup"), None),
26429            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
26430            ("wasi:cli/environment", None, None),
26431        ] {
26432            let c = WitContract {
26433                de: "cart".into(),
26434                para: "downstream".into(),
26435                wit: wit.into(),
26436                endpoint: endpoint.map(str::to_string),
26437                subject: None,
26438                slot: slot.map(str::to_string),
26439            };
26440            assert!(
26441                c.subject().is_none(),
26442                "WitContract::subject must return None when the typed \
26443                 slot is absent under :wit {wit:?} (got {:?})",
26444                c.subject(),
26445            );
26446            assert_eq!(
26447                c.subject(),
26448                c.subject.as_deref(),
26449                "WitContract::subject must byte-equal the .subject \
26450                 field's `.as_deref()` projection in the absent arm",
26451            );
26452        }
26453    }
26454
26455    #[test]
26456    fn wit_contract_subject_borrows_from_subject_storage() {
26457        // The borrow-not-copy pin: [`WitContract::subject`] must return
26458        // an `Option<&str>` whose `Some` arm borrows from the typed
26459        // slot's own [`String`] storage — same-address invariant with
26460        // `c.subject.as_deref().unwrap()`. Pins against a future silent
26461        // detour that allocated a fresh `String`
26462        // (`self.subject.clone().map(...)` in the body would type-check
26463        // but silently drop the borrow, and every downstream consumer
26464        // that assumed the returned slice outlives `&self` would break
26465        // on a stale-reference use-after-free — the [`WitContract::target`]
26466        // PubSub-arm payload extraction rebinds the returned
26467        // `Option<&str>` through `.ok_or_else(...)` and threads the
26468        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
26469        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26470        // [`ContratoIdentity`] dedup key threads the returned
26471        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
26472        // from the WitContract's own storage and each would silently
26473        // misbehave if this accessor produced a detached copy). Peer of
26474        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
26475        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
26476        // shaped optional-scalar axis — second extension of the
26477        // `Option<&str>` borrow-not-copy discipline onto the
26478        // per-`:contratos` payload-carrier family, this time on the
26479        // pub-sub arm.
26480        let c = WitContract {
26481            de: "cart".into(),
26482            para: "notifier".into(),
26483            wit: "nats:pub-sub".into(),
26484            endpoint: None,
26485            subject: Some("orders.paid".into()),
26486            slot: None,
26487        };
26488        let sub = c.subject().expect("Some arm");
26489        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
26490        assert_eq!(
26491            sub.as_ptr(),
26492            storage_slice.as_ptr(),
26493            "WitContract::subject must borrow from the .subject \
26494             String's backing storage — a fresh allocation here means \
26495             the accessor no longer names the substrate-primitive typed \
26496             dispatch and every downstream consumer would silently \
26497             carry a detached copy",
26498        );
26499        assert_eq!(
26500            sub.len(),
26501            storage_slice.len(),
26502            "WitContract::subject and .subject.as_deref() must byte-\
26503             equal in length as well as in address",
26504        );
26505    }
26506
26507    #[test]
26508    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
26509        // The canonical per-`:contratos` key/value-store-shaped
26510        // `:slot`-scalar pin: [`WitContract::slot`] must return the
26511        // `:contratos :slot` field byte-for-byte, borrowed from the
26512        // typed slot's own `Option<String>` storage. Peer of the
26513        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
26514        // [`WitContract::subject`] (90de675) accessor pins on the M3
26515        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
26516        // optional-scalar axis — same "the substrate-primitive
26517        // accessor must byte-equal the raw field access verbatim
26518        // across every author-declared value" discipline extended to
26519        // the store arm. Pins against a future silent detour that
26520        // re-canonicalized the slot template (an accidental
26521        // `.to_lowercase()` bucket-prefix normalization that didn't
26522        // reach the peer field-access site at the dedup key, a per-CR
26523        // fully-qualified prefix rewrite the operator authors on one
26524        // consumer without the other, or an M4 typed-key-template
26525        // `Display` re-canonicalization that silently drifted the
26526        // printer output from the source `caixa.lisp`). Four values
26527        // sweep the wasi:keyvalue accept-set every store-shaped
26528        // author-declared slot lands on (flat bucket, single-param
26529        // template, multi-param template, nested-hierarchy template).
26530        for slot in [
26531            "sessions",
26532            "carts/{cart_id}",
26533            "orders/{tenant}/{order_id}",
26534            "cache/tenant-a/orders/{id}",
26535        ] {
26536            let c = WitContract {
26537                de: "cart".into(),
26538                para: "kv".into(),
26539                wit: "wasi:keyvalue/store".into(),
26540                endpoint: None,
26541                subject: None,
26542                slot: Some(slot.into()),
26543            };
26544            assert_eq!(
26545                c.slot(),
26546                Some(slot),
26547                "WitContract::slot must return :contratos :slot \
26548                 verbatim (got {:?}, expected Some({slot:?}))",
26549                c.slot(),
26550            );
26551            assert_eq!(
26552                c.slot(),
26553                c.slot.as_deref(),
26554                "WitContract::slot must byte-equal the .slot field's \
26555                 `.as_deref()` projection",
26556            );
26557        }
26558    }
26559
26560    #[test]
26561    fn wit_contract_slot_none_when_field_is_none() {
26562        // The absent-`:slot` arm of the per-`:contratos` store-shaped
26563        // payload-carrier accessor pin: when the typed slot is absent —
26564        // the canonical shape under a non-store `:wit` world per the
26565        // [`WitContract::target`]-enforced shape ↔ target partition
26566        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
26567        // carries `:subject`, [`WitTarget::Capability`] carries none) —
26568        // [`WitContract::slot`] must return `None`. Pins against a
26569        // future silent detour that projected the absent slot to a
26570        // `Some("")` empty-string default (the canonical
26571        // `Option<String>` → `String` collapse footgun the sibling M2
26572        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26573        // emptiness predicates already guard on the peer M2 typed-slot
26574        // surfaces), a `Some("None")` stringified-None round-trip, or
26575        // a `Some` arm whose contents were derived from a sibling
26576        // slot (an accidental fallback to the `:endpoint` / `:subject`
26577        // payload that read the HTTP / pub-sub payload into the store
26578        // axis). Three contracts sweep the accept-set every non-store
26579        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
26580        // payload-less capability.
26581        for (wit, endpoint, subject) in [
26582            ("wasi:http/proxy", Some("/lookup"), None),
26583            ("nats:pub-sub", None, Some("orders.paid")),
26584            ("wasi:cli/environment", None, None),
26585        ] {
26586            let c = WitContract {
26587                de: "cart".into(),
26588                para: "downstream".into(),
26589                wit: wit.into(),
26590                endpoint: endpoint.map(str::to_string),
26591                subject: subject.map(str::to_string),
26592                slot: None,
26593            };
26594            assert!(
26595                c.slot().is_none(),
26596                "WitContract::slot must return None when the typed \
26597                 slot is absent under :wit {wit:?} (got {:?})",
26598                c.slot(),
26599            );
26600            assert_eq!(
26601                c.slot(),
26602                c.slot.as_deref(),
26603                "WitContract::slot must byte-equal the .slot field's \
26604                 `.as_deref()` projection in the absent arm",
26605            );
26606        }
26607    }
26608
26609    #[test]
26610    fn wit_contract_slot_borrows_from_slot_storage() {
26611        // The borrow-not-copy pin: [`WitContract::slot`] must return
26612        // an `Option<&str>` whose `Some` arm borrows from the typed
26613        // slot's own [`String`] storage — same-address invariant with
26614        // `c.slot.as_deref().unwrap()`. Pins against a future silent
26615        // detour that allocated a fresh `String`
26616        // (`self.slot.clone().map(...)` in the body would type-check
26617        // but silently drop the borrow, and every downstream consumer
26618        // that assumed the returned slice outlives `&self` would
26619        // break on a stale-reference use-after-free — the
26620        // [`WitContract::target`] Store-arm payload extraction rebinds
26621        // the returned `Option<&str>` through `.ok_or_else(...)` and
26622        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
26623        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26624        // [`ContratoIdentity`] dedup key threads the returned
26625        // `Option<&str>` into the six-tuple's store arm — each borrow
26626        // from the WitContract's own storage and each would silently
26627        // misbehave if this accessor produced a detached copy). Peer
26628        // of the sibling per-`:contratos` [`WitContract::endpoint`]
26629        // (7020470) / [`WitContract::subject`] (90de675)
26630        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
26631        // shaped optional-scalar axis — third and final extension of
26632        // the `Option<&str>` borrow-not-copy discipline onto the
26633        // per-`:contratos` payload-carrier family, this time on the
26634        // store arm.
26635        let c = WitContract {
26636            de: "cart".into(),
26637            para: "kv".into(),
26638            wit: "wasi:keyvalue/store".into(),
26639            endpoint: None,
26640            subject: None,
26641            slot: Some("carts/{cart_id}".into()),
26642        };
26643        let slot = c.slot().expect("Some arm");
26644        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
26645        assert_eq!(
26646            slot.as_ptr(),
26647            storage_slice.as_ptr(),
26648            "WitContract::slot must borrow from the .slot String's \
26649             backing storage — a fresh allocation here means the \
26650             accessor no longer names the substrate-primitive typed \
26651             dispatch and every downstream consumer would silently \
26652             carry a detached copy",
26653        );
26654        assert_eq!(
26655            slot.len(),
26656            storage_slice.len(),
26657            "WitContract::slot and .slot.as_deref() must byte-equal \
26658             in length as well as in address",
26659        );
26660    }
26661
26662    #[test]
26663    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
26664        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
26665        // [`Membro::nome`] must return the `:membros :caixa` field
26666        // byte-for-byte, borrowed from the typed slot's own [`String`]
26667        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
26668        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26669        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
26670        // slot-atom scalar-value axes — same "the substrate-primitive
26671        // accessor must byte-equal the raw field access verbatim across
26672        // every author-declared value" discipline extended to the
26673        // per-`:membros` member-identity arm. Pins against a future
26674        // silent detour that re-normalized the member identity (an
26675        // accidental `.to_lowercase()` — every `:membros :caixa` is
26676        // validated as a DNS-1123 label upstream via
26677        // [`validate_membro_caixa`], so any re-normalization is
26678        // redundant + a drift surface between the validator and the
26679        // accessor), a namespace-prefix rewrite (an accidental
26680        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
26681        // rewrite that didn't land on the peer axes), or a per-cluster
26682        // alias stamp the operator authors on one consumer without the
26683        // other. Four values sweep the accept-set the DNS-1123 gate
26684        // upstream admits (short single-word / dashed / v-suffixed
26685        // member names).
26686        for name in ["cart", "checkout", "catalog", "orders-v2"] {
26687            let m = Membro {
26688                caixa: name.into(),
26689                versao: "^0.1".into(),
26690            };
26691            assert_eq!(
26692                m.nome(),
26693                name,
26694                "Membro::nome must return :membros :caixa verbatim \
26695                 (got {:?}, expected {name:?})",
26696                m.nome(),
26697            );
26698            assert_eq!(
26699                m.nome(),
26700                m.caixa.as_str(),
26701                "Membro::nome must byte-equal the .caixa field access",
26702            );
26703        }
26704    }
26705
26706    #[test]
26707    fn membro_nome_borrows_from_caixa_storage() {
26708        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
26709        // slice that borrows from the typed slot's own [`String`]
26710        // storage — same-address invariant with `m.caixa.as_str()`. Pins
26711        // against a future silent detour that allocated a fresh `String`
26712        // (`self.caixa.clone()` in the body would type-check but
26713        // silently drop the borrow, and every downstream consumer that
26714        // assumed the returned slice outlives `&self` would break on a
26715        // stale-reference use-after-free — the `HashSet<&str>` collector
26716        // at [`AplicacaoSpec::validate`]'s `names` seed, the
26717        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
26718        // [`AplicacaoSpec::detect_sync_cycles`], the
26719        // [`crate::render::insert_first_seen`] dedup key at
26720        // [`AplicacaoSpec::validate_membros`] — each borrow from the
26721        // Membro's own storage and each would silently misbehave if
26722        // this accessor produced a detached copy). Peer of the sibling
26723        // per-`:contratos` [`WitContract::source`] /
26724        // [`WitContract::destination`] and per-`:entrada`
26725        // [`Entrada::destination`] borrow-invariant pins on the mesh-
26726        // slot-atom scalar-value axes.
26727        let m = Membro {
26728            caixa: "checkout".into(),
26729            versao: "^0.1".into(),
26730        };
26731        let name = m.nome();
26732        let caixa_slice = m.caixa.as_str();
26733        assert_eq!(
26734            name.as_ptr(),
26735            caixa_slice.as_ptr(),
26736            "Membro::nome must borrow from the .caixa String's backing \
26737             storage — a fresh allocation here means the accessor no \
26738             longer names the substrate-primitive typed dispatch and \
26739             every downstream consumer would silently carry a detached \
26740             copy",
26741        );
26742        assert_eq!(
26743            name.len(),
26744            caixa_slice.len(),
26745            "Membro::nome and .caixa.as_str() must byte-equal in length \
26746             as well as in address",
26747        );
26748    }
26749
26750    #[test]
26751    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
26752        // The canonical per-`:membros` member-`:versao`-scalar pin:
26753        // [`Membro::versao_requirement`] must return the
26754        // `:membros :versao` field byte-for-byte, borrowed from the typed
26755        // slot's own [`String`] storage. Sibling of the peer
26756        // `membro_nome_returns_caixa_byte_equal_across_permutations`
26757        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
26758        // — same "the substrate-primitive accessor must byte-equal the
26759        // raw field access verbatim across every author-declared value"
26760        // discipline extended to the per-`:membros` member-`:versao`
26761        // requirement-string arm. Pins against a future silent detour
26762        // that re-canonicalized the requirement (an accidental
26763        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
26764        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
26765        // drifted the printer output away from the source `caixa.lisp`,
26766        // an accidental whitespace trim on `"^ 0.1"` that no consumer
26767        // ever produced from the field-access side, an accidental
26768        // per-cluster lacre-projected concrete-version rewrite that
26769        // didn't land on the peer field-access sites). Five values sweep
26770        // the accept-set the shared
26771        // [`crate::render::require_valid_versao_requirement`] gate
26772        // admits (caret / tilde / exact / wildcard / bare-major).
26773        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
26774            let m = Membro {
26775                caixa: "cart".into(),
26776                versao: req.into(),
26777            };
26778            assert_eq!(
26779                m.versao_requirement(),
26780                req,
26781                "Membro::versao_requirement must return :membros :versao \
26782                 verbatim (got {:?}, expected {req:?})",
26783                m.versao_requirement(),
26784            );
26785            assert_eq!(
26786                m.versao_requirement(),
26787                m.versao.as_str(),
26788                "Membro::versao_requirement must byte-equal the .versao \
26789                 field access",
26790            );
26791        }
26792    }
26793
26794    #[test]
26795    fn membro_versao_requirement_borrows_from_versao_storage() {
26796        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
26797        // return a `&str` slice that borrows from the typed slot's own
26798        // [`String`] storage — same-address invariant with
26799        // `m.versao.as_str()`. Pins against a future silent detour that
26800        // allocated a fresh `String` (`self.versao.clone()` in the body
26801        // would type-check but silently drop the borrow, and every
26802        // downstream consumer that assumed the returned slice outlives
26803        // `&self` would break on a stale-reference use-after-free). Peer
26804        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
26805        // per-`:contratos` [`WitContract::source`] /
26806        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
26807        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
26808        // the mesh-slot-atom scalar-value axes.
26809        let m = Membro {
26810            caixa: "checkout".into(),
26811            versao: "^0.1".into(),
26812        };
26813        let req = m.versao_requirement();
26814        let versao_slice = m.versao.as_str();
26815        assert_eq!(
26816            req.as_ptr(),
26817            versao_slice.as_ptr(),
26818            "Membro::versao_requirement must borrow from the .versao \
26819             String's backing storage — a fresh allocation here means \
26820             the accessor no longer names the substrate-primitive typed \
26821             dispatch and every downstream consumer would silently carry \
26822             a detached copy",
26823        );
26824        assert_eq!(
26825            req.len(),
26826            versao_slice.len(),
26827            "Membro::versao_requirement and .versao.as_str() must byte-\
26828             equal in length as well as in address",
26829        );
26830    }
26831
26832    #[test]
26833    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
26834        // Sibling-pair invariant pin composing both per-`:membros`
26835        // substrate-primitive typed dispatches — [`Membro::nome`]
26836        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
26837        // `(nome(), versao_requirement())` call shape every renderer
26838        // that fans on per-member identity + version pin keys off. The
26839        // invariant, evaluated per-member:
26840        //
26841        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
26842        //
26843        // Closes the last unlifted per-`:membros` scalar axis — every
26844        // downstream consumer that reads the pair now routes through
26845        // exactly two typed dispatches on the substrate primitive, not
26846        // one typed + one open-coded field access. A future refactor
26847        // that silently split either accessor's projection (an
26848        // accidental `nome()` namespace-prefix rewrite that didn't
26849        // reach the peer, an accidental `versao_requirement()` lacre-
26850        // projected concrete-version rewrite that didn't land on the
26851        // `nome()` peer) surfaces at caixa-core build time. Peer of the
26852        // sibling per-`:entrada` `(hostname(), destination())` and
26853        // per-`:contratos` `(source(), destination())` pair invariants
26854        // on the mesh-slot-atom scalar-value axes.
26855        for (caixa, versao) in [
26856            ("cart", "^0.1"),
26857            ("checkout", "~0.1.2"),
26858            ("catalog", "0.1.0"),
26859            ("orders-v2", "*"),
26860        ] {
26861            let m = Membro {
26862                caixa: caixa.into(),
26863                versao: versao.into(),
26864            };
26865            assert_eq!(
26866                (m.nome(), m.versao_requirement()),
26867                (m.caixa.as_str(), m.versao.as_str()),
26868                "(Membro::nome, Membro::versao_requirement) must project \
26869                 (.caixa, .versao) verbatim across every author-declared \
26870                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
26871                m.nome(),
26872                m.versao_requirement(),
26873            );
26874        }
26875    }
26876
26877    #[test]
26878    fn validate_membros_empty_gate_routes_through_nome_accessor() {
26879        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
26880        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
26881        // not the raw `.caixa` field access. Structurally: setting
26882        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
26883        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
26884        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
26885        // (i.e. the empty string) — so the emptiness predicate the
26886        // refusal arm reaches under is the accessor-projected value,
26887        // not a peer field that would silently drift under a future
26888        // accessor-side rewrite.
26889        //
26890        // Pins against a future silent detour that (a) re-derived the
26891        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
26892        // instead of `self.nome().is_empty()`, silently disagreeing with
26893        // every peer consumer (the `validate_membro_caixa(m.nome())`
26894        // per-slot helper — which now owns the emptiness arm outright —
26895        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
26896        // below, and the emit-side per-`programs[]` entry-`name:` at
26897        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
26898        // per-tenant alias arm the caller was unaware of, silently
26899        // rewriting an author-declared `:caixa "checkout"` to `""` —
26900        // the raw-field-access gate would fail-open while the
26901        // accessor-routed peer consumers would fail-closed, splitting
26902        // the diagnostic from the actual failure surface.
26903        //
26904        // Peer of the sibling
26905        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
26906        // (c0110f1) composition pin — same "the shape-gate predicate
26907        // must route through the substrate-primitive typed dispatch"
26908        // discipline extended onto the per-`:membros` empty-`:caixa`
26909        // refusal-arm axis. Closes the last unlifted `.caixa` production-
26910        // code read site on `Membro` — after this converge every
26911        // caixa-core `.caixa` field access outside the accessor's own
26912        // body is either a test-side field-setter (in-module tests
26913        // constructing invalid-shape inputs) or a doc-comment reference.
26914        let mut s = three_member_spec();
26915        s.membros[1].caixa = String::new();
26916        assert!(
26917            s.membros[1].nome().is_empty(),
26918            "Membro::nome must byte-equal the .caixa field access — an \
26919             accessor-side detour that no longer projects the raw field \
26920             would silently split this drift-detection test from the \
26921             validate() refusal arm",
26922        );
26923        assert_eq!(
26924            s.membros[1].nome(),
26925            s.membros[1].caixa.as_str(),
26926            "Membro::nome and .caixa.as_str() must byte-equal on an \
26927             empty-`:caixa` entry — the emptiness gate keys off the \
26928             accessor by construction",
26929        );
26930        assert_eq!(
26931            s.validate().unwrap_err(),
26932            AplicacaoError::MembroCaixaEmpty,
26933            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
26934             on an entry whose accessor-projected `nome()` is empty",
26935        );
26936    }
26937
26938    #[test]
26939    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
26940        // Convergence pin, paired with the deletion of the redundant
26941        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
26942        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
26943        // after the collapse, the `MembroCaixaEmpty` refusal on every
26944        // empty-`:caixa` per-member input is owned solely by the shared
26945        // [`validate_membro_caixa`] helper — the same per-slot substrate
26946        // primitive routing empty + shape arms uniformly onto
26947        // [`crate::render::require_valid_dns_1123_label`] that every
26948        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
26949        // on `:placement :clusters`, [`validate_entrada_para`] on
26950        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
26951        // :de`/`:para`) already funnels its own empty arm through.
26952        //
26953        // Two arms pin the collapse:
26954        //
26955        //   (1) The per-slot helper called with the empty string returns
26956        //       byte-equal to the previous inline arm's diagnostic — so
26957        //       a future rebrand of [`validate_membro_caixa`] that
26958        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
26959        //       empty input (an inadvertent switch to
26960        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
26961        //       `on_invalid` arm, an accidental re-routing to a shared
26962        //       `MembroError::Empty` under a future error-hierarchy
26963        //       flattening) would silently split the drift from the
26964        //       [`validate_membros`] caller and surface the wrong
26965        //       diagnostic on the author-facing empty-`:caixa` footgun.
26966        //
26967        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
26968        //       anywhere in the `:membros` fan-out still trips
26969        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
26970        //       no outer inline guard needed. Same shape as the
26971        //       whole-spec arm on [`validate_placement_cluster`] /
26972        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
26973        //       one substrate primitive per axis, folding empty + shape.
26974        //
26975        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
26976        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
26977        // MeshPolicy::validate) already extend across the M3 mesh-slot
26978        // family — closes the last per-slot gate on the family carrying
26979        // an inline empty guard duplicating its own helper.
26980        assert_eq!(
26981            validate_membro_caixa(""),
26982            Err(AplicacaoError::MembroCaixaEmpty),
26983            "validate_membro_caixa must own the empty arm outright — a \
26984             regression here would silently split MembroCaixaEmpty from \
26985             validate_membros' end-to-end refusal shape after the outer \
26986             inline `if m.nome().is_empty()` guard collapse",
26987        );
26988        let mut s = three_member_spec();
26989        s.membros[0].caixa = String::new();
26990        assert_eq!(
26991            s.validate().unwrap_err(),
26992            AplicacaoError::MembroCaixaEmpty,
26993            "an empty-`:caixa` :membros head entry must trip \
26994             MembroCaixaEmpty end-to-end via validate() with the outer \
26995             inline guard removed — the per-slot helper alone is now \
26996             load-bearing",
26997        );
26998        let mut s = three_member_spec();
26999        s.membros[2].caixa = String::new();
27000        assert_eq!(
27001            s.validate().unwrap_err(),
27002            AplicacaoError::MembroCaixaEmpty,
27003            "an empty-`:caixa` :membros tail entry must trip \
27004             MembroCaixaEmpty end-to-end via validate() with the outer \
27005             inline guard removed — the per-slot helper alone reaches \
27006             every fan-out position",
27007        );
27008    }
27009
27010    #[test]
27011    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
27012        // The canonical per-`:placement` Akka-cluster-sharding
27013        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
27014        // the `:placement :shard-key` field byte-for-byte, borrowed
27015        // from the typed slot's own `Option<String>` storage. Peer of
27016        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
27017        // per-`:contratos` [`WitContract::source`] /
27018        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
27019        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
27020        // slot-atom scalar-value axes — same "the substrate-primitive
27021        // accessor must byte-equal the raw field access verbatim across
27022        // every author-declared value" discipline extended to the
27023        // per-`:placement` Akka-cluster-sharding key extractor arm.
27024        // Pins against a future silent detour that re-normalized the
27025        // key (an accidental `.to_lowercase()` — every non-empty
27026        // `:shard-key` is validated as a printable-ASCII single-token
27027        // reference upstream via [`validate_placement_shard_key`], so
27028        // any re-normalization is redundant + a drift surface between
27029        // the validator and the accessor), a per-cluster alias rewrite
27030        // the operator authors on one consumer without the other, or an
27031        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
27032        // that didn't land on the peer field-access sites. Four values
27033        // sweep the accept-set the shape gate admits — bare identifier,
27034        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
27035        // the four canonical Akka-style entity-id extractor shapes the
27036        // future M4 cluster-sharding reconciler hashes.
27037        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
27038            let p = Placement {
27039                estrategia: PlacementStrategy::Sharded,
27040                clusters: vec!["rio".into()],
27041                affinity: None,
27042                shard_key: Some(key.into()),
27043            };
27044            assert_eq!(
27045                p.shard_key(),
27046                Some(key),
27047                "Placement::shard_key must return :placement :shard-key \
27048                 verbatim (got {:?}, expected Some({key:?}))",
27049                p.shard_key(),
27050            );
27051            assert_eq!(
27052                p.shard_key(),
27053                p.shard_key.as_deref(),
27054                "Placement::shard_key must byte-equal the .shard_key \
27055                 field's `.as_deref()` projection",
27056            );
27057        }
27058    }
27059
27060    #[test]
27061    fn placement_shard_key_none_when_field_is_none() {
27062        // The absent-`:shard-key` arm of the per-`:placement`
27063        // Akka-cluster-sharding accessor pin: when the typed slot is
27064        // absent — the canonical shape under `:estrategia Replicated` /
27065        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
27066        // enforced `shard_key.is_some() == matches!(estrategia,
27067        // Sharded)` partition — [`Placement::shard_key`] must return
27068        // `None`. Pins against a future silent detour that projected
27069        // the absent slot to a `Some("")` empty-string default (the
27070        // canonical `Option<String>` → `String` collapse footgun the
27071        // sibling M2 [`crate::LimitsSpec::is_empty`] /
27072        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
27073        // already guard on the peer M2 typed-slot surfaces), a
27074        // `Some("None")` stringified-None round-trip, or a `Some` arm
27075        // whose contents were derived from a sibling slot (an
27076        // accidental fallback to `estrategia.as_str()` that read the
27077        // strategy discriminator into the key axis). Two placements
27078        // sweep the accept-set every `validate`-passing non-`Sharded`
27079        // shape lands on — `Replicated` (Erlang/OTP distributed-app
27080        // takeover) and `SingleNode` (single-node hosting).
27081        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
27082            let p = Placement {
27083                estrategia,
27084                clusters: vec!["rio".into()],
27085                affinity: None,
27086                shard_key: None,
27087            };
27088            assert!(
27089                p.shard_key().is_none(),
27090                "Placement::shard_key must return None when the typed \
27091                 slot is absent under :estrategia {estrategia:?} (got {:?})",
27092                p.shard_key(),
27093            );
27094            assert_eq!(
27095                p.shard_key(),
27096                p.shard_key.as_deref(),
27097                "Placement::shard_key must byte-equal the .shard_key \
27098                 field's `.as_deref()` projection in the absent arm",
27099            );
27100        }
27101    }
27102
27103    #[test]
27104    fn placement_shard_key_borrows_from_shard_key_storage() {
27105        // The borrow-not-copy pin: [`Placement::shard_key`] must return
27106        // an `Option<&str>` whose `Some` arm borrows from the typed
27107        // slot's own [`String`] storage — same-address invariant with
27108        // `p.shard_key.as_deref().unwrap()`. Pins against a future
27109        // silent detour that allocated a fresh `String`
27110        // (`self.shard_key.clone().map(...)` in the body would type-
27111        // check but silently drop the borrow, and every downstream
27112        // consumer that assumed the returned slice outlives `&self`
27113        // would break on a stale-reference use-after-free — the
27114        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
27115        // gate's `Some(k)`-bound match arm reads `k: &str` under the
27116        // accessor's return type and would silently misbehave if this
27117        // accessor produced a detached copy). Peer of the sibling
27118        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
27119        // [`WitContract::source`] / [`WitContract::destination`]
27120        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
27121        // (6db982c) borrow-invariant pins on the mesh-slot-atom
27122        // scalar-value axes — first extension of the discipline onto
27123        // an `Option<String>`-shaped optional-scalar axis.
27124        let p = Placement {
27125            estrategia: PlacementStrategy::Sharded,
27126            clusters: vec!["rio".into()],
27127            affinity: None,
27128            shard_key: Some("tenantId".into()),
27129        };
27130        let key = p.shard_key().expect("Some arm");
27131        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
27132        assert_eq!(
27133            key.as_ptr(),
27134            storage_slice.as_ptr(),
27135            "Placement::shard_key must borrow from the .shard_key \
27136             String's backing storage — a fresh allocation here means \
27137             the accessor no longer names the substrate-primitive typed \
27138             dispatch and every downstream consumer would silently \
27139             carry a detached copy",
27140        );
27141        assert_eq!(
27142            key.len(),
27143            storage_slice.len(),
27144            "Placement::shard_key and .shard_key.as_deref() must byte-\
27145             equal in length as well as in address",
27146        );
27147    }
27148
27149    #[test]
27150    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
27151        // The canonical per-`:placement` M3-Adaptive-compression-hint
27152        // scalar pin: [`Placement::affinity`] must return the
27153        // `:placement :affinity` field byte-for-byte, borrowed from the
27154        // typed slot's own `Option<String>` storage. Peer of the sibling
27155        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
27156        // pin on the sibling `Option<&str>` optional-scalar axis — same
27157        // "the substrate-primitive accessor must byte-equal the raw
27158        // field access verbatim across every author-declared value"
27159        // discipline extended to the peer per-`:placement` M3-Adaptive-
27160        // compression-hint arm. Pins against a future silent detour
27161        // that re-normalized the hint (an accidental `.to_lowercase()`
27162        // — every `:affinity` is already validated as a DNS-1123 label
27163        // upstream via [`validate_placement_affinity`], so any re-
27164        // normalization is redundant + a drift surface between the
27165        // validator and the accessor), a per-cluster alias rewrite the
27166        // operator authors on one consumer without the other, or an
27167        // accidental hint-family collapse (`low-latency` → `latency`
27168        // that dropped the qualifier prefix). Four values sweep the
27169        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
27170        // canonical adaptive-compression-weight biases the future M4
27171        // placement engine reads.
27172        for hint in [
27173            "data-locality",
27174            "low-latency",
27175            "high-throughput",
27176            "cost-optimized",
27177        ] {
27178            let p = Placement {
27179                estrategia: PlacementStrategy::Replicated,
27180                clusters: vec!["rio".into()],
27181                affinity: Some(hint.into()),
27182                shard_key: None,
27183            };
27184            assert_eq!(
27185                p.affinity(),
27186                Some(hint),
27187                "Placement::affinity must return :placement :affinity \
27188                 verbatim (got {:?}, expected Some({hint:?}))",
27189                p.affinity(),
27190            );
27191            assert_eq!(
27192                p.affinity(),
27193                p.affinity.as_deref(),
27194                "Placement::affinity must byte-equal the .affinity \
27195                 field's `.as_deref()` projection",
27196            );
27197        }
27198    }
27199
27200    #[test]
27201    fn placement_affinity_none_when_field_is_none() {
27202        // The absent-`:affinity` arm of the per-`:placement`
27203        // M3-Adaptive-compression-hint accessor pin: when the typed
27204        // slot is absent — the canonical shape of an Aplicacao that
27205        // leaves the compression weighting up to the placement engine's
27206        // cluster-default arm — [`Placement::affinity`] must return
27207        // `None`. Pins against a future silent detour that projected
27208        // the absent slot to a `Some("")` empty-string default (the
27209        // canonical `Option<String>` → `String` collapse footgun the
27210        // sibling M2 [`crate::LimitsSpec::is_empty`] /
27211        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
27212        // already guard on the peer M2 typed-slot surfaces), a
27213        // `Some("None")` stringified-None round-trip, a `Some` arm
27214        // whose contents were derived from a sibling slot (an
27215        // accidental fallback to `estrategia.as_str()` that read the
27216        // strategy discriminator into the hint axis), or a
27217        // `Some("default")` implicit-default that would silently biases
27218        // the routing without the author having written one. Three
27219        // placements sweep the accept-set every `validate`-passing
27220        // `:affinity None` shape lands on — one per PlacementStrategy
27221        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
27222        // with a shard-key), since `:affinity` is orthogonal to
27223        // `:estrategia` in the typed grammar.
27224        for (estrategia, shard_key) in [
27225            (PlacementStrategy::SingleNode, None),
27226            (PlacementStrategy::Replicated, None),
27227            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
27228        ] {
27229            let p = Placement {
27230                estrategia,
27231                clusters: vec!["rio".into()],
27232                affinity: None,
27233                shard_key,
27234            };
27235            assert!(
27236                p.affinity().is_none(),
27237                "Placement::affinity must return None when the typed \
27238                 slot is absent under :estrategia {estrategia:?} (got {:?})",
27239                p.affinity(),
27240            );
27241            assert_eq!(
27242                p.affinity(),
27243                p.affinity.as_deref(),
27244                "Placement::affinity must byte-equal the .affinity \
27245                 field's `.as_deref()` projection in the absent arm",
27246            );
27247        }
27248    }
27249
27250    #[test]
27251    fn placement_affinity_borrows_from_affinity_storage() {
27252        // The borrow-not-copy pin: [`Placement::affinity`] must return
27253        // an `Option<&str>` whose `Some` arm borrows from the typed
27254        // slot's own [`String`] storage — same-address invariant with
27255        // `p.affinity.as_deref().unwrap()`. Pins against a future
27256        // silent detour that allocated a fresh `String`
27257        // (`self.affinity.clone().map(...)` in the body would type-
27258        // check but silently drop the borrow, and every downstream
27259        // consumer that assumed the returned slice outlives `&self`
27260        // would break on a stale-reference use-after-free — the
27261        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
27262        // gate reads the accessor's `&str` return through the
27263        // [`validate_placement_affinity`] `&str` parameter and would
27264        // silently misbehave if this accessor produced a detached
27265        // copy). Peer of the sibling per-`:placement`
27266        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
27267        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
27268        // extends the discipline onto the sibling per-`:placement`
27269        // M3-Adaptive-compression-hint arm.
27270        let p = Placement {
27271            estrategia: PlacementStrategy::Replicated,
27272            clusters: vec!["rio".into()],
27273            affinity: Some("data-locality".into()),
27274            shard_key: None,
27275        };
27276        let hint = p.affinity().expect("Some arm");
27277        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
27278        assert_eq!(
27279            hint.as_ptr(),
27280            storage_slice.as_ptr(),
27281            "Placement::affinity must borrow from the .affinity \
27282             String's backing storage — a fresh allocation here means \
27283             the accessor no longer names the substrate-primitive typed \
27284             dispatch and every downstream consumer would silently \
27285             carry a detached copy",
27286        );
27287        assert_eq!(
27288            hint.len(),
27289            storage_slice.len(),
27290            "Placement::affinity and .affinity.as_deref() must byte-\
27291             equal in length as well as in address",
27292        );
27293    }
27294
27295    #[test]
27296    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
27297        // The canonical per-`:placement` distribution-strategy-scalar
27298        // pin: [`Placement::estrategia`] must return the `:placement
27299        // :estrategia` field verbatim as a [`PlacementStrategy`],
27300        // `Copy`-projected from the typed slot's own `PlacementStrategy`
27301        // storage across every variant in the closed accept-set
27302        // (`SingleNode` — Erlang/OTP distributed-app takeover;
27303        // `Replicated` — active-active across every named cluster;
27304        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
27305        // against a future silent detour that re-derived the strategy
27306        // from a peer axis (an accidental fallback to
27307        // `if shard_key.is_some() { Sharded } else { Replicated }`
27308        // collapse that read the shard-key axis into the strategy
27309        // discriminator), a variant remap the operator authors on one
27310        // consumer without the other, or a stale-derive detour that
27311        // substituted [`PlacementStrategy::default`] when the field
27312        // held any explicit variant (which would silently collapse the
27313        // distinction between "author explicitly declared `:estrategia
27314        // Replicated`" and "author omitted the slot and inherited the
27315        // default" the future per-cluster override slot depends on).
27316        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
27317        // pin on the `Copy`-return `u16` scalar axis — same "the
27318        // substrate-primitive accessor must byte-equal the raw field
27319        // access verbatim across every author-declared value" discipline
27320        // extended onto the per-`:placement` distribution-strategy
27321        // `Copy`-composite-enum scalar axis.
27322        for estrategia in [
27323            PlacementStrategy::SingleNode,
27324            PlacementStrategy::Replicated,
27325            PlacementStrategy::Sharded,
27326        ] {
27327            // Route the paired `:shard-key` fixture-builder through the
27328            // typed cross-slot invariant predicate
27329            // [`PlacementStrategy::requires_shard_key`] rather than the
27330            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
27331            // arm-identity predicate — same discipline the sibling
27332            // `placement_strategy_variants_round_trip` fixture builder now
27333            // reads through.
27334            let shard_key = estrategia
27335                .requires_shard_key()
27336                .then(|| "tenantId".to_string());
27337            let p = Placement {
27338                estrategia,
27339                clusters: vec!["rio".into()],
27340                affinity: None,
27341                shard_key,
27342            };
27343            assert_eq!(
27344                p.estrategia(),
27345                estrategia,
27346                "Placement::estrategia must return :placement :estrategia \
27347                 verbatim (got {:?}, expected {estrategia:?})",
27348                p.estrategia(),
27349            );
27350            assert_eq!(
27351                p.estrategia(),
27352                p.estrategia,
27353                "Placement::estrategia accessor and .estrategia field \
27354                 access must byte-equal — the accessor is the substrate-\
27355                 primitive typed dispatch every downstream distribution-\
27356                 strategy consumer must route through",
27357            );
27358        }
27359    }
27360
27361    #[test]
27362    fn validate_placement_reads_through_lifted_estrategia_accessor() {
27363        // Three-consumer coherence pin: the
27364        // [`AplicacaoSpec::validate_placement`]
27365        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
27366        // `estrategia:` field (which reads through
27367        // [`Placement::estrategia`] to name the strategy the empty
27368        // `:clusters` list was declared against), the same method's
27369        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
27370        // reads through [`Placement::estrategia`] to fan across the
27371        // shape-gate cascades), and the non-`Sharded`-arm
27372        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
27373        // `estrategia:` field (which reads through
27374        // [`Placement::estrategia`] to name the strategy the declared-
27375        // but-inert `:shard-key` was authored under) must all key off
27376        // the lifted accessor, so any future rebrand on the typed
27377        // slot's reader shape lands at exactly one place. Pins the
27378        // three-site coherence by exercising each error surface end-
27379        // to-end and asserting the surfaced `estrategia:` field byte-
27380        // equals the accessor's return. Peer of the sibling per-
27381        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
27382        // pin on the M3 mesh-slot `Copy`-return scalar axis.
27383
27384        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
27385        // whose `estrategia:` field must byte-equal the accessor's return
27386        // for every variant in the closed accept-set.
27387        for estrategia in [
27388            PlacementStrategy::SingleNode,
27389            PlacementStrategy::Replicated,
27390            PlacementStrategy::Sharded,
27391        ] {
27392            let mut spec = three_member_spec();
27393            spec.placement.estrategia = estrategia;
27394            spec.placement.clusters = Vec::new();
27395            // Route the paired `:shard-key` spec-mutator through the typed
27396            // cross-slot invariant predicate
27397            // [`PlacementStrategy::requires_shard_key`] rather than the
27398            // [`gen_platform::IsVariant`]-derived
27399            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
27400            // same discipline the sibling
27401            // `placement_strategy_variants_round_trip` and
27402            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
27403            // fixture builders now read through.
27404            spec.placement.shard_key = estrategia
27405                .requires_shard_key()
27406                .then(|| "tenantId".to_string());
27407            let err = spec.validate().unwrap_err();
27408            match err {
27409                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
27410                    assert_eq!(
27411                        e,
27412                        spec.placement.estrategia(),
27413                        "PlacementWithoutClusters.estrategia must byte-equal \
27414                         Placement::estrategia() — the error carrier reads \
27415                         through the lifted accessor",
27416                    );
27417                }
27418                other => panic!(
27419                    "expected PlacementWithoutClusters, got {other:?} for \
27420                     estrategia={estrategia:?}"
27421                ),
27422            }
27423        }
27424
27425        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
27426        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
27427        // must byte-equal the accessor's return for both non-`Sharded`
27428        // strategies.
27429        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
27430            let mut spec = three_member_spec();
27431            spec.placement.estrategia = estrategia;
27432            spec.placement.shard_key = Some("tenantId".into());
27433            let err = spec.validate().unwrap_err();
27434            match err {
27435                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
27436                    assert_eq!(
27437                        e,
27438                        spec.placement.estrategia(),
27439                        "ShardKeyOnNonSharded.estrategia must byte-equal \
27440                         Placement::estrategia() — the non-Sharded-arm \
27441                         refusal reads through the lifted accessor",
27442                    );
27443                }
27444                other => panic!(
27445                    "expected ShardKeyOnNonSharded, got {other:?} for \
27446                     estrategia={estrategia:?}"
27447                ),
27448            }
27449        }
27450    }
27451
27452    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
27453    //
27454    // The [`Placement::clusters`] accessor lift is the second slice-return
27455    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
27456    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
27457    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
27458    // below cover (1) the accessor's byte-equal projection against the raw
27459    // field access across the empty / singleton / cohort fixtures the
27460    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
27461    // and the per-cluster validate loop fan between, and (2) the two-
27462    // consumer coherence of the paired pre-flight refusal probe and the
27463    // per-cluster validate loop routing through the accessor on both arms.
27464
27465    #[test]
27466    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
27467        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
27468        // [`Placement::clusters`] must return the `:placement :clusters`
27469        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
27470        // the same backing buffer the raw `self.clusters.as_slice()`
27471        // field access borrows from, byte-equal across every
27472        // representative fixture in the accept-set — the empty slice
27473        // (the pre-validation sentinel every
27474        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
27475        // the singleton slice (the minimal `SingleNode`-shape cohort),
27476        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
27477        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
27478        //
27479        // Pins against a future silent detour that returned
27480        // `&Vec<String>` (which would type-check but leak the storage-
27481        // side `Vec`'s grow/push/reserve surface no consumer of the
27482        // typed view reaches for), a fresh-allocated `Vec<String>` copy
27483        // (which would type-check via a coercion but silently break
27484        // every downstream caller that relied on the slice sharing the
27485        // backing buffer's identity), or an out-of-order or length-
27486        // drifted projection (which would silently split the paired
27487        // pre-flight `.is_empty()` refusal probe's input from the per-
27488        // cluster validate loop's traversal input).
27489        //
27490        // Peer of the sibling M2
27491        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27492        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27493        // `:supervisor` static-child-list axis, extended onto the M3
27494        // per-`:placement` distribution-target-list `Vec`-carry axis.
27495        let fixtures: Vec<Vec<String>> = vec![
27496            Vec::new(),
27497            vec!["rio".into()],
27498            vec!["rio".into(), "mar".into()],
27499            vec!["rio".into(), "mar".into(), "plo".into()],
27500        ];
27501        for clusters in fixtures {
27502            let p = Placement {
27503                clusters: clusters.clone(),
27504                ..Placement::default()
27505            };
27506            assert_eq!(
27507                p.clusters(),
27508                clusters.as_slice(),
27509                "Placement::clusters must return :placement :clusters \
27510                 verbatim (got {:?}, expected {:?})",
27511                p.clusters(),
27512                clusters.as_slice(),
27513            );
27514            assert_eq!(
27515                p.clusters(),
27516                p.clusters.as_slice(),
27517                "Placement::clusters accessor and .clusters.as_slice() \
27518                 field access must byte-equal — the accessor is the \
27519                 substrate-primitive typed dispatch every downstream \
27520                 cluster-pool consumer must route through",
27521            );
27522            assert_eq!(
27523                p.clusters().len(),
27524                p.clusters.len(),
27525                "Placement::clusters().len() must byte-equal \
27526                 self.clusters.len() — a length-drift would silently \
27527                 split the paired pre-flight `.is_empty()` refusal \
27528                 probe input from the per-cluster validate loop's \
27529                 traversal input",
27530            );
27531        }
27532    }
27533
27534    #[test]
27535    fn validate_placement_reads_through_lifted_clusters_accessor() {
27536        // Two-consumer coherence pin: the
27537        // [`AplicacaoSpec::validate_placement`] pre-flight
27538        // `self.placement.clusters().is_empty()` refusal probe (which
27539        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
27540        // the accessor projects the empty slice) and the per-cluster
27541        // validate loop's `for c in self.placement.clusters()`
27542        // traversal (which must reach every entry in the same order
27543        // the accessor projects, so both the per-entry value-shape
27544        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
27545        // and the duplicate-detection HashSet insert that trips
27546        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
27547        // accessor's projection) must both key off the lifted
27548        // accessor, so any future rebrand on the typed slot's reader
27549        // shape lands at exactly one place. Pins the two-site
27550        // coherence by exercising each production consumer end-to-end:
27551        // (1) the `PlacementWithoutClusters` refusal under the empty
27552        // slice, (2) the `PlacementClusterInvalid` refusal fires on
27553        // the second entry of a two-cluster cohort whose head is
27554        // valid but tail is not (which requires the loop to reach the
27555        // second entry through the accessor), and (3) the
27556        // `PlacementClusterDuplicate` refusal fires on the second
27557        // entry of a two-cluster cohort that shares a name (which
27558        // requires the loop to reach both entries — a first-entry-only
27559        // projection would silently pass since the dedup HashSet has
27560        // room for the first insert).
27561        //
27562        // Peer of the sibling M2
27563        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
27564        // (bc92bce) coherence pin on the per-`:supervisor` static-
27565        // child-list axis, extended onto the M3 per-`:placement`
27566        // distribution-target-list `Vec`-carry axis.
27567
27568        // (1) Pre-flight `.is_empty()` probe: the empty slice must
27569        // trip `PlacementWithoutClusters`.
27570        let mut spec = three_member_spec();
27571        spec.placement.clusters = Vec::new();
27572        match spec.validate().unwrap_err() {
27573            AplicacaoError::PlacementWithoutClusters { .. } => {}
27574            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
27575        }
27576        assert!(
27577            spec.placement.clusters().is_empty(),
27578            "the pre-flight refusal input must be the empty slice per \
27579             the accessor's projection",
27580        );
27581
27582        // (2) Per-cluster validate loop: a two-cluster cohort with an
27583        // invalid tail entry must trip `PlacementClusterInvalid` on
27584        // the tail — the loop must reach the second entry through
27585        // the accessor.
27586        let mut spec = three_member_spec();
27587        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
27588        match spec.validate().unwrap_err() {
27589            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
27590                assert_eq!(
27591                    cluster, "BAD_CLUSTER",
27592                    "PlacementClusterInvalid.cluster must carry the \
27593                     tail entry the loop reached through the accessor",
27594                );
27595            }
27596            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
27597        }
27598        assert_eq!(
27599            spec.placement.clusters().len(),
27600            2,
27601            "the per-cluster validate loop's traversal input must be \
27602             a two-element slice per the accessor's projection",
27603        );
27604
27605        // (3) Per-cluster validate loop: a two-cluster cohort that
27606        // shares a name must trip `PlacementClusterDuplicate` on the
27607        // second entry — the loop must reach both entries through the
27608        // accessor for the dedup HashSet's second insert to collide.
27609        let mut spec = three_member_spec();
27610        spec.placement.clusters = vec!["rio".into(), "rio".into()];
27611        match spec.validate().unwrap_err() {
27612            AplicacaoError::PlacementClusterDuplicate { cluster } => {
27613                assert_eq!(
27614                    cluster, "rio",
27615                    "PlacementClusterDuplicate.cluster must carry the \
27616                     shared cluster name verbatim",
27617                );
27618            }
27619            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
27620        }
27621        assert_eq!(
27622            spec.placement.clusters().len(),
27623            2,
27624            "the per-cluster validate loop's traversal input must be \
27625             a two-element slice per the accessor's projection",
27626        );
27627    }
27628
27629    #[test]
27630    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
27631        // The canonical per-`:membros` member-list-slice-shape pin:
27632        // [`AplicacaoSpec::membros`] must return the `:membros` typed
27633        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
27634        // same backing buffer the raw `self.membros.as_slice()` field
27635        // access borrows from, byte-equal across every representative
27636        // fixture in the accept-set — the empty slice (the pre-
27637        // validation sentinel every [`AplicacaoError::NoMembros`]
27638        // refusal keys off), the singleton slice (the minimal one-
27639        // Servico Aplicacao shape), and multi-entry cohorts (the peer
27640        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
27641        // load-bearing identity of the application graph).
27642        //
27643        // Pins against a future silent detour that returned
27644        // `&Vec<Membro>` (which would type-check but leak the storage-
27645        // side `Vec`'s grow/push/reserve surface no consumer of the
27646        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
27647        // (which would type-check via a coercion but silently break
27648        // every downstream caller that relied on the slice sharing the
27649        // backing buffer's identity), or an out-of-order or length-
27650        // drifted projection (which would silently split the paired
27651        // `HashSet<&str>` name-set seed's collect input from the
27652        // pre-flight `.is_empty()` refusal probe's input from the per-
27653        // member validate loop's traversal input from the
27654        // programs.yaml emitter's per-entry fan-out loop's input from
27655        // the `feira app graph` per-member print traversal's input).
27656        //
27657        // Peer of the sibling M2
27658        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27659        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27660        // `:supervisor` static-child-list axis and the sibling M3
27661        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
27662        // (a6e18d7) `&[String]` byte-equal pin on the per-
27663        // `:placement` distribution-target-list axis — extends the
27664        // slice-return-accessor byte-equal-projection discipline onto
27665        // the outermost M3 mesh-slot type's per-Aplicacao member-list
27666        // `Vec`-carry axis.
27667        let fixtures: Vec<Vec<Membro>> = vec![
27668            Vec::new(),
27669            vec![membro("catalog", "^0.1")],
27670            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
27671            vec![
27672                membro("catalog", "^0.1"),
27673                membro("cart", "^0.1"),
27674                membro("payment", "^0.2"),
27675            ],
27676        ];
27677        for membros in fixtures {
27678            let s = AplicacaoSpec {
27679                membros: membros.clone(),
27680                contratos: Vec::new(),
27681                politicas: MeshPolicy::default(),
27682                placement: Placement::default(),
27683                entrada: None,
27684            };
27685            assert_eq!(
27686                s.membros(),
27687                membros.as_slice(),
27688                "AplicacaoSpec::membros must return :membros verbatim \
27689                 (got {:?}, expected {:?})",
27690                s.membros(),
27691                membros.as_slice(),
27692            );
27693            assert_eq!(
27694                s.membros(),
27695                s.membros.as_slice(),
27696                "AplicacaoSpec::membros accessor and .membros.as_slice() \
27697                 field access must byte-equal — the accessor is the \
27698                 substrate-primitive typed dispatch every downstream \
27699                 member-list consumer must route through",
27700            );
27701            assert_eq!(
27702                s.membros().len(),
27703                s.membros.len(),
27704                "AplicacaoSpec::membros().len() must byte-equal \
27705                 self.membros.len() — a length-drift would silently \
27706                 split the paired `HashSet<&str>` name-set seed's \
27707                 collect input from the pre-flight `.is_empty()` \
27708                 refusal probe input from the per-member validate \
27709                 loop's traversal input",
27710            );
27711        }
27712    }
27713
27714    #[test]
27715    fn validate_reads_through_lifted_membros_accessor() {
27716        // Three-consumer coherence pin: the
27717        // [`AplicacaoSpec::validate_membros`] pre-flight
27718        // `self.membros().is_empty()` refusal probe (which must trip
27719        // [`AplicacaoError::NoMembros`] when the accessor projects the
27720        // empty slice), the same method's per-member validate loop's
27721        // `for m in self.membros()` traversal (which must reach every
27722        // entry in the same order the accessor projects, so both the
27723        // per-entry empty-`:caixa` gate that trips
27724        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
27725        // detection `insert_first_seen` that trips
27726        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
27727        // projection), and the peer [`AplicacaoSpec::validate`]'s
27728        // `HashSet<&str>` name-set seed's
27729        // `self.membros().iter().map(Membro::nome).collect()` collect
27730        // input (which every `:contratos` `:de` / `:para` membership
27731        // lookup rejects an unknown name against) must all three key
27732        // off the lifted accessor, so any future rebrand on the typed
27733        // slot's reader shape lands at exactly one place. Pins the
27734        // three-site coherence by exercising each production consumer
27735        // end-to-end: (1) the `NoMembros` refusal under the empty
27736        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
27737        // second entry of a two-member cohort whose head is valid but
27738        // tail has an empty `:caixa` (which requires the loop to
27739        // reach the second entry through the accessor), and (3) the
27740        // `MembroDuplicate` refusal fires on the second entry of a
27741        // two-member cohort that shares a `:caixa` name (which
27742        // requires the loop to reach both entries through the
27743        // accessor for the dedup HashSet's second insert to collide).
27744        //
27745        // Peer of the sibling M2
27746        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
27747        // (bc92bce) coherence pin on the per-`:supervisor` static-
27748        // child-list axis and the sibling M3
27749        // `validate_placement_reads_through_lifted_clusters_accessor`
27750        // (a6e18d7) coherence pin on the per-`:placement` distribution-
27751        // target-list axis — extends the slice-return-accessor
27752        // multi-consumer coherence discipline onto the outermost M3
27753        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
27754
27755        // (1) Pre-flight `.is_empty()` probe: the empty slice must
27756        // trip `NoMembros`.
27757        let mut spec = three_member_spec();
27758        spec.membros = Vec::new();
27759        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
27760        assert!(
27761            spec.membros().is_empty(),
27762            "the pre-flight refusal input must be the empty slice per \
27763             the accessor's projection",
27764        );
27765
27766        // (2) Per-member validate loop: a two-member cohort with an
27767        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
27768        // the tail — the loop must reach the second entry through
27769        // the accessor.
27770        let mut spec = three_member_spec();
27771        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
27772        assert_eq!(
27773            spec.validate().unwrap_err(),
27774            AplicacaoError::MembroCaixaEmpty,
27775        );
27776        assert_eq!(
27777            spec.membros().len(),
27778            2,
27779            "the per-member validate loop's traversal input must be \
27780             a two-element slice per the accessor's projection",
27781        );
27782
27783        // (3) Per-member validate loop: a two-member cohort that
27784        // shares a `:caixa` name must trip `MembroDuplicate` on the
27785        // second entry — the loop must reach both entries through the
27786        // accessor for the dedup HashSet's second insert to collide.
27787        let mut spec = three_member_spec();
27788        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
27789        match spec.validate().unwrap_err() {
27790            AplicacaoError::MembroDuplicate { caixa } => {
27791                assert_eq!(
27792                    caixa, "catalog",
27793                    "MembroDuplicate.caixa must carry the shared \
27794                     member name verbatim",
27795                );
27796            }
27797            other => panic!("expected MembroDuplicate, got {other:?}"),
27798        }
27799        assert_eq!(
27800            spec.membros().len(),
27801            2,
27802            "the per-member validate loop's traversal input must be \
27803             a two-element slice per the accessor's projection",
27804        );
27805    }
27806
27807    #[test]
27808    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
27809        // The canonical per-`:contratos` contract-list-slice-shape pin:
27810        // [`AplicacaoSpec::contratos`] must return the `:contratos`
27811        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
27812        // slice-view over the same backing buffer the raw
27813        // `self.contratos.as_slice()` field access borrows from, byte-
27814        // equal across every representative fixture in the accept-set —
27815        // the empty slice (the pre-validation "internal-only mesh" shape
27816        // an Aplicacao whose members exchange no typed edges renders
27817        // through), the singleton slice (the minimal one-edge Aplicacao
27818        // shape), and multi-entry cohorts (the peer multi-edge shapes
27819        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
27820        // of the application graph).
27821        //
27822        // Pins against a future silent detour that returned
27823        // `&Vec<WitContract>` (which would type-check but leak the
27824        // storage-side `Vec`'s grow/push/reserve surface no consumer of
27825        // the typed view reaches for), a fresh-allocated
27826        // `Vec<WitContract>` copy (which would type-check via a coercion
27827        // but silently break every downstream caller that relied on the
27828        // slice sharing the backing buffer's identity), or an out-of-
27829        // order or length-drifted projection (which would silently split
27830        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
27831        // seed's traversal input from the `detect_sync_cycles` per-edge
27832        // adjacency-list seed's traversal input from the
27833        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
27834        // BTreeMap grouping loop's traversal input from the
27835        // `feira app graph` per-contract print traversal's input).
27836        //
27837        // Peer of the immediately-adjacent sibling M3
27838        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
27839        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
27840        // node-list axis, the sibling M3
27841        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
27842        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
27843        // distribution-target-list axis, and the sibling M2
27844        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
27845        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
27846        // `:supervisor` static-child-list axis — extends the slice-
27847        // return-accessor byte-equal-projection discipline onto the
27848        // outermost M3 mesh-slot type's per-Aplicacao contract-list
27849        // `Vec`-carry axis, closing the last unlifted per-
27850        // `AplicacaoSpec` `Vec`-carry axis.
27851        let fixtures: Vec<Vec<WitContract>> = vec![
27852            Vec::new(),
27853            vec![contract_http("cart", "catalog", "/products/:id")],
27854            vec![
27855                contract_http("cart", "catalog", "/products/:id"),
27856                contract_http("cart", "payment", "/charge"),
27857            ],
27858            vec![
27859                contract_http("cart", "catalog", "/products/:id"),
27860                contract_http("cart", "payment", "/charge"),
27861                contract_http("payment", "catalog", "/audit"),
27862            ],
27863        ];
27864        for contratos in fixtures {
27865            let s = AplicacaoSpec {
27866                membros: vec![
27867                    membro("catalog", "^0.1"),
27868                    membro("cart", "^0.1"),
27869                    membro("payment", "^0.2"),
27870                ],
27871                contratos: contratos.clone(),
27872                politicas: MeshPolicy::default(),
27873                placement: Placement::default(),
27874                entrada: None,
27875            };
27876            assert_eq!(
27877                s.contratos(),
27878                contratos.as_slice(),
27879                "AplicacaoSpec::contratos must return :contratos verbatim \
27880                 (got {:?}, expected {:?})",
27881                s.contratos(),
27882                contratos.as_slice(),
27883            );
27884            assert_eq!(
27885                s.contratos(),
27886                s.contratos.as_slice(),
27887                "AplicacaoSpec::contratos accessor and \
27888                 .contratos.as_slice() field access must byte-equal — \
27889                 the accessor is the substrate-primitive typed dispatch \
27890                 every downstream contract-list consumer must route \
27891                 through",
27892            );
27893            assert_eq!(
27894                s.contratos().len(),
27895                s.contratos.len(),
27896                "AplicacaoSpec::contratos().len() must byte-equal \
27897                 self.contratos.len() — a length-drift would silently \
27898                 split the paired per-edge validate-loop's traversal \
27899                 input from the sync-cycle adjacency-list seed's \
27900                 traversal input from the cilium_network_policies \
27901                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
27902                 input from the `feira app graph` per-contract print \
27903                 traversal's input",
27904            );
27905        }
27906    }
27907
27908    #[test]
27909    fn validate_reads_through_lifted_contratos_accessor() {
27910        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
27911        // per-`:contratos` validate-loop's `for c in self.contratos()`
27912        // traversal (which must reach every entry in the same order the
27913        // accessor projects, so both the per-entry
27914        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
27915        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
27916        // dedup `HashSet` insert key off the accessor's projection),
27917        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
27918        // `for c in self.contratos()` adjacency-list seed (which drives
27919        // the sync-subgraph deadlock-detection gate via
27920        // [`AplicacaoError::SyncCycle`]), and the peer
27921        // [`caixa_mesh::cilium_network_policies`]'s
27922        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
27923        // grouping loop (which drives the per-CNP fan-out) must all
27924        // three key off the lifted accessor, so any future rebrand on
27925        // the typed slot's reader shape lands at exactly one place. Pins
27926        // the three-site coherence by exercising the two caixa-core
27927        // production consumers end-to-end: (1) the empty-`:contratos`
27928        // slice must validate without a per-edge diagnostic (the
27929        // per-edge loop is a no-op under the empty projection), (2) the
27930        // `ContratoMemberMissing` refusal fires on the second entry of a
27931        // two-edge cohort whose head references a valid member but tail
27932        // references a phantom name (which requires the loop to reach
27933        // the second entry through the accessor), and (3) the
27934        // `SyncCycle` refusal fires on a self-referential two-edge
27935        // cohort through the sync-cycle detector's peer projection
27936        // (which requires the detector to iterate the accessor's
27937        // projection to add the back-edge to its adjacency list).
27938        //
27939        // Peer of the sibling M3
27940        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
27941        // three-consumer coherence pin on the per-`:membros` node-list
27942        // axis and the sibling M3
27943        // `validate_placement_reads_through_lifted_clusters_accessor`
27944        // (a6e18d7) coherence pin on the per-`:placement` distribution-
27945        // target-list axis — extends the slice-return-accessor multi-
27946        // consumer coherence discipline onto the outermost M3 mesh-slot
27947        // type's per-Aplicacao contract-list `Vec`-carry axis.
27948
27949        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
27950        // and no per-edge diagnostic surfaces. Validate succeeds on
27951        // the well-formed `:membros` head.
27952        let mut spec = three_member_spec();
27953        spec.contratos = Vec::new();
27954        assert!(
27955            spec.validate().is_ok(),
27956            "empty :contratos must validate — the per-edge loop is a \
27957             no-op under the accessor's empty projection",
27958        );
27959        assert!(
27960            spec.contratos().is_empty(),
27961            "the per-edge validate loop's traversal input must be the \
27962             empty slice per the accessor's projection",
27963        );
27964
27965        // (2) Per-edge validate loop: a two-edge cohort whose tail
27966        // references a phantom `:para` member must trip
27967        // `ContratoMemberMissing` on the tail — the loop must reach
27968        // the second entry through the accessor for the membership
27969        // lookup to fail on the phantom name.
27970        let mut spec = three_member_spec();
27971        spec.contratos = vec![
27972            contract_http("cart", "catalog", "/products/:id"),
27973            contract_http("cart", "phantom", "/x"),
27974        ];
27975        let err = spec.validate().unwrap_err();
27976        assert!(
27977            matches!(
27978                err,
27979                AplicacaoError::ContratoMemberMissing { ref caixa }
27980                    if caixa == "phantom"
27981            ),
27982            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
27983        );
27984        assert_eq!(
27985            spec.contratos().len(),
27986            2,
27987            "the per-edge validate loop's traversal input must be \
27988             a two-element slice per the accessor's projection",
27989        );
27990
27991        // (3) Sync-cycle detector: a two-edge synchronous cohort
27992        // whose second edge closes the sync-subgraph back onto the
27993        // first must trip [`AplicacaoError::ContratoCycle`] — the
27994        // detector must iterate the accessor's projection to add
27995        // both edges to its adjacency list, so a length-drift on
27996        // the accessor's projection would silently disagree with
27997        // the sync-cycle detector on which edge closes the loop.
27998        // Peer projection to the `validate` per-edge loop above:
27999        // the sync-cycle detector routes through the same lifted
28000        // accessor, so a rebrand of the reader shape lands at one
28001        // place. Uses a two-edge cohort (cart → catalog → cart)
28002        // because the per-edge `ContratoSelfLoop` gate fires before
28003        // the sync-cycle detector on a single self-referential edge
28004        // (`cart → cart`) — the cycle-detector's input must be a
28005        // multi-edge cohort for its per-edge traversal input to be
28006        // observably wider than the per-edge validate loop's input.
28007        let mut spec = three_member_spec();
28008        spec.contratos = vec![
28009            contract_http("cart", "catalog", "/products/:id"),
28010            contract_http("catalog", "cart", "/callback"),
28011        ];
28012        let err = spec.validate().unwrap_err();
28013        assert!(
28014            matches!(err, AplicacaoError::ContratoCycle { .. }),
28015            "expected ContratoCycle from the sync-cycle detector on a \
28016             two-edge back-edge cohort, got {err:?}",
28017        );
28018        assert_eq!(
28019            spec.contratos().len(),
28020            2,
28021            "the sync-cycle detector's traversal input must be a \
28022             two-element slice per the accessor's projection",
28023        );
28024    }
28025
28026    #[test]
28027    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
28028        // The canonical per-`:politicas` outer-composite-reference-shape
28029        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
28030        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
28031        // the same backing storage the raw `&self.politicas` field
28032        // access borrows from, byte-equal across every representative
28033        // fixture in the accept-set — the default `MeshPolicy` (the
28034        // author-empty "no policy on any axis" shape whose
28035        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
28036        // shapes carrying one axis at a time
28037        // (`{mtls_required, timeout, retries, circuit_breaker,
28038        // rate_limit}` — the minimal five-axis fan-out over the
28039        // per-axis lifted accessor family every downstream mesh-artifact
28040        // emitter dispatches on), and the multi-axis composite (the
28041        // canonical `three_member_spec` fixture's `{timeout, retries,
28042        // mtls_required}` triple — the load-bearing shape every
28043        // Aplicacao-scoped fixture in this suite constructs).
28044        //
28045        // Pins against a future silent detour that returned a fresh-
28046        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
28047        // impl but silently break every downstream caller that relied
28048        // on the reference sharing the composite's backing identity), a
28049        // reference to an operator-resolved overlay (the future
28050        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
28051        // acknowledges — its resolution must land at exactly this
28052        // accessor body, not silently divert the raw slot away from a
28053        // second consumer), or an axis-shuffled projection (a future
28054        // detour that swapped `timeout` and `retries` through the
28055        // accessor would silently split the paired `validate_politicas`
28056        // per-axis bracket-dispatch's traversal input from the peer
28057        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
28058        // emitter's fan-out input from the peer
28059        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
28060        // overlay emitter's fan-out input).
28061        //
28062        // Peer of the sibling M3
28063        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
28064        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
28065        // node-list `Vec`-carry axis and the sibling M3
28066        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
28067        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
28068        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
28069        // accessor byte-equal-projection discipline onto the outermost
28070        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
28071        // reference axis, the first `&Composite`-return accessor on the
28072        // outer [`AplicacaoSpec`] type.
28073        let fixtures: Vec<MeshPolicy> = vec![
28074            MeshPolicy::default(),
28075            MeshPolicy {
28076                mtls_required: Some(true),
28077                ..MeshPolicy::default()
28078            },
28079            MeshPolicy {
28080                mtls_required: Some(false),
28081                ..MeshPolicy::default()
28082            },
28083            MeshPolicy {
28084                timeout: Some(Duration::from_secs(30)),
28085                ..MeshPolicy::default()
28086            },
28087            MeshPolicy {
28088                retries: Some(3),
28089                ..MeshPolicy::default()
28090            },
28091            MeshPolicy {
28092                circuit_breaker: Some(CircuitBreaker {
28093                    max_failures: 5,
28094                    window: Duration::from_secs(30),
28095                }),
28096                ..MeshPolicy::default()
28097            },
28098            MeshPolicy {
28099                rate_limit: Some(RateLimit {
28100                    rate: 100,
28101                    window: Duration::from_secs(1),
28102                }),
28103                ..MeshPolicy::default()
28104            },
28105            MeshPolicy {
28106                timeout: Some(Duration::from_secs(30)),
28107                retries: Some(3),
28108                mtls_required: Some(true),
28109                ..MeshPolicy::default()
28110            },
28111        ];
28112        for politicas in fixtures {
28113            let s = AplicacaoSpec {
28114                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28115                contratos: Vec::new(),
28116                politicas: politicas.clone(),
28117                placement: Placement::default(),
28118                entrada: None,
28119            };
28120            assert_eq!(
28121                *s.politicas(),
28122                politicas,
28123                "AplicacaoSpec::politicas must return :politicas verbatim \
28124                 (got {:?}, expected {:?})",
28125                s.politicas(),
28126                politicas,
28127            );
28128            assert!(
28129                std::ptr::eq(s.politicas(), &s.politicas),
28130                "AplicacaoSpec::politicas accessor and &self.politicas \
28131                 field access must borrow the same backing storage — \
28132                 the accessor is the substrate-primitive typed dispatch \
28133                 every downstream mesh-policy composite consumer must \
28134                 route through, and a reference-identity split would \
28135                 silently break every consumer that relied on the \
28136                 borrow sharing the composite's storage",
28137            );
28138            assert_eq!(
28139                s.politicas().is_empty(),
28140                s.politicas.is_empty(),
28141                "AplicacaoSpec::politicas().is_empty() must byte-equal \
28142                 self.politicas.is_empty() — an emptiness-drift would \
28143                 silently split the paired `validate_politicas` \
28144                 per-axis bracket-dispatch's seed from the peer \
28145                 caixa-mesh CNP mTLS-overlay emitter's key from the \
28146                 peer caixa-mesh HTTPRoute timeout+retry overlay \
28147                 emitter's key",
28148            );
28149        }
28150    }
28151
28152    #[test]
28153    fn validate_politicas_reads_through_lifted_politicas_accessor() {
28154        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
28155        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
28156        // followed by the per-axis fan-out `p.timeout()` /
28157        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
28158        // the lifted axis-level accessor family) must key off the
28159        // lifted outer accessor, so any future rebrand on the typed
28160        // slot's outer-composite reader shape lands at exactly one
28161        // place. Pins the multi-axis coherence by exercising each
28162        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
28163        // a `Some(Duration::ZERO)` timeout under the outer accessor's
28164        // reference projection, (2) `PolicyRetriesZero` fires on a
28165        // `Some(0)` retries under the same projection, and (3) an
28166        // empty [`MeshPolicy::default`] passes `validate_politicas` —
28167        // the outer accessor's reference-projection reaches every
28168        // per-axis branch without silently short-circuiting any.
28169        //
28170        // Peer of the sibling M3
28171        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28172        // three-consumer coherence pin on the per-`:membros` node-list
28173        // axis and the sibling M3
28174        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
28175        // three-consumer coherence pin on the per-`:contratos`
28176        // edge-list axis — extends the multi-consumer coherence
28177        // discipline onto the outermost M3 mesh-slot type's per-
28178        // Aplicacao mesh-policy composite-reference axis, the first
28179        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
28180        // type.
28181
28182        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
28183        // reference projection: a `Some(Duration::ZERO)` timeout must
28184        // trip the zero-floor gate. The bracket-dispatch's first arm
28185        // reads `p.timeout()` on the reference returned by the outer
28186        // accessor.
28187        let mut spec = three_member_spec();
28188        spec.politicas.timeout = Some(Duration::ZERO);
28189        spec.politicas.retries = None;
28190        spec.politicas.circuit_breaker = None;
28191        spec.politicas.rate_limit = None;
28192        assert_eq!(
28193            spec.validate().unwrap_err(),
28194            AplicacaoError::PolicyTimeoutZero,
28195        );
28196        assert!(
28197            std::ptr::eq(spec.politicas(), &spec.politicas),
28198            "the `validate_politicas` per-axis bracket-dispatch's \
28199             traversal input must be the same backing composite the \
28200             accessor's reference projection borrows from",
28201        );
28202
28203        // (2) `PolicyRetriesZero` refusal under the outer accessor's
28204        // reference projection: a `Some(0)` retries must trip the
28205        // zero-floor gate. The bracket-dispatch's second arm reads
28206        // `p.retries()` on the reference returned by the outer accessor.
28207        let mut spec = three_member_spec();
28208        spec.politicas.timeout = None;
28209        spec.politicas.retries = Some(0);
28210        spec.politicas.circuit_breaker = None;
28211        spec.politicas.rate_limit = None;
28212        assert_eq!(
28213            spec.validate().unwrap_err(),
28214            AplicacaoError::PolicyRetriesZero,
28215        );
28216
28217        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
28218        // — every per-axis arm short-circuits on `None`, so the outer
28219        // accessor's reference projection reaches the fall-through
28220        // `Ok(())` without any per-axis refusal firing.
28221        let mut spec = three_member_spec();
28222        spec.politicas = MeshPolicy::default();
28223        assert!(
28224            spec.validate().is_ok(),
28225            "an empty `MeshPolicy` must pass `validate_politicas` — \
28226             every per-axis arm short-circuits on `None` under the \
28227             outer accessor's reference projection",
28228        );
28229        assert!(
28230            spec.politicas().is_empty(),
28231            "the outer accessor's reference projection must be the \
28232             empty composite per the `MeshPolicy::default()` fixture",
28233        );
28234    }
28235
28236    #[test]
28237    #[allow(clippy::too_many_lines)]
28238    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
28239        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
28240        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
28241        // must both key off the lifted axis-level accessors
28242        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
28243        // the peer `:circuit-breaker` / `:rate-limit` arms already
28244        // routing through [`MeshPolicy::circuit_breaker`] /
28245        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
28246        // per axis on the substrate primitive" shape at the fan-out
28247        // (four axes, four accessors, no raw-field-access site
28248        // anywhere on the bracket-dispatch). Pins the per-axis
28249        // coherence at the accept-set boundaries the bracket carves:
28250        //   1. accessor byte-equal to raw field on every representative
28251        //      accept-set value (`None`, sub-cap, at-cap, past-cap
28252        //      sentinel) — a future accessor drift that no longer
28253        //      shipped the raw slot verbatim would surface here,
28254        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
28255        //      routed through the accessor's projection, proving the
28256        //      first arm reads through the accessor rather than a
28257        //      silent-detour peer-axis field access,
28258        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
28259        //      through the accessor's projection, proving the second
28260        //      arm reads through the accessor,
28261        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
28262        //      passes validate under the accessor projection (paired
28263        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
28264        //      sibling axis), pinning the upper-boundary accept-arm
28265        //      also routes through the accessor.
28266        //
28267        // Peer of the sibling M3
28268        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28269        // outer-composite-reference coherence pin (which asserts the
28270        // `let p = self.politicas()` seed); extends the discipline onto
28271        // the per-axis fan-out layer that consumes the seed's
28272        // reference. Same shape as
28273        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
28274        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28275        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
28276        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
28277
28278        // (1) Accessor byte-equal to raw field on the `:timeout` axis
28279        // across the accept-set boundaries the bracket dispatch's
28280        // three-arm gate carves out
28281        // ([`crate::render::require_positive_canonical_bounded_duration`]
28282        // — zero-floor + canonical-form + upper-cap).
28283        for timeout in [
28284            None,
28285            Some(Duration::ZERO),
28286            Some(Duration::from_millis(1)),
28287            Some(POLICY_TIMEOUT_MAX),
28288        ] {
28289            let p = MeshPolicy {
28290                timeout,
28291                ..MeshPolicy::default()
28292            };
28293            assert_eq!(
28294                p.timeout(),
28295                p.timeout,
28296                "MeshPolicy::timeout accessor must byte-equal the raw \
28297                 .timeout field across every accept-set boundary the \
28298                 validate_politicas :timeout arm carves out — a drift \
28299                 here would silently split the validate bracket's arm \
28300                 from the peer caixa-mesh HTTPRoute timeout-overlay \
28301                 emitter's read",
28302            );
28303        }
28304
28305        // (2) Accessor byte-equal to raw field on the `:retries` axis
28306        // across the accept-set boundaries the bracket dispatch's
28307        // two-arm gate carves out
28308        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
28309        // + upper-cap).
28310        for retries in [
28311            None,
28312            Some(0u32),
28313            Some(1u32),
28314            Some(POLICY_RETRIES_MAX),
28315            Some(POLICY_RETRIES_MAX + 1),
28316            Some(u32::MAX),
28317        ] {
28318            let p = MeshPolicy {
28319                retries,
28320                ..MeshPolicy::default()
28321            };
28322            assert_eq!(
28323                p.retries(),
28324                p.retries,
28325                "MeshPolicy::retries accessor must byte-equal the raw \
28326                 .retries field across every accept-set boundary the \
28327                 validate_politicas :retries arm carves out — a drift \
28328                 here would silently split the validate bracket's arm \
28329                 from the peer caixa-mesh HTTPRoute retry-overlay \
28330                 emitter's read",
28331            );
28332        }
28333
28334        // (3) `PolicyTimeoutZero` fires on the accessor-projected
28335        // zero-floor boundary. A silent detour that no longer read
28336        // through `p.timeout()` (a peer-axis field read, an accidental
28337        // Option::and-then chain that collapsed the None arm to Some,
28338        // an accessor rebrand that clamped the return through the
28339        // upper cap) would fail to refuse here.
28340        let mut spec = three_member_spec();
28341        spec.politicas.timeout = Some(Duration::ZERO);
28342        spec.politicas.retries = None;
28343        spec.politicas.circuit_breaker = None;
28344        spec.politicas.rate_limit = None;
28345        assert_eq!(
28346            spec.politicas().timeout(),
28347            Some(Duration::ZERO),
28348            "the accessor projection must reflect the fixture's \
28349             `Some(Duration::ZERO)` :timeout verbatim",
28350        );
28351        assert_eq!(
28352            spec.validate().unwrap_err(),
28353            AplicacaoError::PolicyTimeoutZero,
28354            "the validate_politicas :timeout zero-floor arm must fire \
28355             through the lifted accessor's projection — a silent \
28356             detour to a peer-axis field would fail to refuse",
28357        );
28358
28359        // (4) `PolicyRetriesZero` fires on the accessor-projected
28360        // zero-floor boundary on the sibling `:retries` axis.
28361        let mut spec = three_member_spec();
28362        spec.politicas.timeout = None;
28363        spec.politicas.retries = Some(0);
28364        spec.politicas.circuit_breaker = None;
28365        spec.politicas.rate_limit = None;
28366        assert_eq!(
28367            spec.politicas().retries(),
28368            Some(0),
28369            "the accessor projection must reflect the fixture's \
28370             `Some(0)` :retries verbatim",
28371        );
28372        assert_eq!(
28373            spec.validate().unwrap_err(),
28374            AplicacaoError::PolicyRetriesZero,
28375            "the validate_politicas :retries zero-floor arm must fire \
28376             through the lifted accessor's projection — a silent \
28377             detour to a peer-axis field would fail to refuse",
28378        );
28379
28380        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
28381        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
28382        // must pass validate under the accessor projection — pins the
28383        // upper-boundary accept-arm also routes through the lifted
28384        // accessor (a drift that clamped or short-circuited at the
28385        // upper boundary would fail the whole-spec validate here).
28386        let mut spec = three_member_spec();
28387        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
28388        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
28389        spec.politicas.circuit_breaker = None;
28390        spec.politicas.rate_limit = None;
28391        assert_eq!(
28392            spec.politicas().timeout(),
28393            Some(POLICY_TIMEOUT_MAX),
28394            "the accessor projection must reflect the fixture's \
28395             at-cap :timeout verbatim",
28396        );
28397        assert_eq!(
28398            spec.politicas().retries(),
28399            Some(POLICY_RETRIES_MAX),
28400            "the accessor projection must reflect the fixture's \
28401             at-cap :retries verbatim",
28402        );
28403        assert!(
28404            spec.validate().is_ok(),
28405            "at-cap :timeout + :retries must pass validate under the \
28406             accessor projection — the upper-boundary accept-arm on \
28407             both axes routes through the lifted accessor",
28408        );
28409    }
28410
28411    #[test]
28412    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
28413        // The canonical per-`:placement` outer-composite-reference-shape
28414        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
28415        // typed `Placement` verbatim as a `&Placement` reference over the
28416        // same backing storage the raw `&self.placement` field access
28417        // borrows from, byte-equal across every representative fixture in
28418        // the accept-set — the default `Placement` (the substrate seed
28419        // shape whose [`PlacementStrategy::default`] evaluates to
28420        // `SingleNode` with an empty `:clusters` pool and both
28421        // optional-scalar axes `None`), and every canonical strategy /
28422        // cluster-pool / optional-scalar combination the
28423        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
28424        // three [`PlacementStrategy`] variants — `SingleNode`,
28425        // `Replicated`, `Sharded` — cross-projected with a non-empty
28426        // `:clusters` pool and, on the `Sharded` arm, a non-empty
28427        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
28428        // canonical `three_member_spec` `Replicated` fixture's
28429        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
28430        //
28431        // Pins against a future silent detour that returned a fresh-
28432        // cloned `Placement` copy (which would type-check via a `Clone`
28433        // impl but silently break every downstream caller that relied on
28434        // the reference sharing the composite's backing identity), a
28435        // reference to an operator-resolved overlay (the future per-
28436        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
28437        // acknowledges — its resolution must land at exactly this
28438        // accessor body, not silently divert the raw slot away from a
28439        // second consumer), or an axis-shuffled projection (a future
28440        // detour that swapped `clusters` and `affinity` through the
28441        // accessor would silently split the paired `validate_placement`
28442        // per-axis bracket-dispatch's traversal input from the peer
28443        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
28444        // programs.yaml distribution-annotation emitter's fan-out input
28445        // from the peer `feira app graph` per-Aplicacao print line's
28446        // input).
28447        //
28448        // Peer of the sibling M3
28449        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
28450        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
28451        // outer mesh-policy composite-reference axis, and of the sibling
28452        // slice-return `aplicacao_spec_membros_returns_membros_slice_
28453        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
28454        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
28455        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
28456        // the outer-accessor byte-equal-projection discipline onto the
28457        // outermost M3 mesh-slot type's per-Aplicacao distribution
28458        // composite-reference axis, the second `&Composite`-return
28459        // accessor on the outer [`AplicacaoSpec`] type.
28460        let fixtures: Vec<Placement> = vec![
28461            Placement::default(),
28462            Placement {
28463                estrategia: PlacementStrategy::SingleNode,
28464                clusters: vec!["rio".into()],
28465                affinity: None,
28466                shard_key: None,
28467            },
28468            Placement {
28469                estrategia: PlacementStrategy::Replicated,
28470                clusters: vec!["rio".into(), "mar".into()],
28471                affinity: None,
28472                shard_key: None,
28473            },
28474            Placement {
28475                estrategia: PlacementStrategy::Replicated,
28476                clusters: vec!["rio".into(), "mar".into()],
28477                affinity: Some("data-locality".into()),
28478                shard_key: None,
28479            },
28480            Placement {
28481                estrategia: PlacementStrategy::Sharded,
28482                clusters: vec!["rio".into(), "mar".into()],
28483                affinity: None,
28484                shard_key: Some("tenantId".into()),
28485            },
28486            Placement {
28487                estrategia: PlacementStrategy::Sharded,
28488                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
28489                affinity: Some("low-latency".into()),
28490                shard_key: Some("metadata.tenantId".into()),
28491            },
28492        ];
28493        for placement in fixtures {
28494            let s = AplicacaoSpec {
28495                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28496                contratos: Vec::new(),
28497                politicas: MeshPolicy::default(),
28498                placement: placement.clone(),
28499                entrada: None,
28500            };
28501            assert_eq!(
28502                *s.placement(),
28503                placement,
28504                "AplicacaoSpec::placement must return :placement verbatim \
28505                 (got {:?}, expected {:?})",
28506                s.placement(),
28507                placement,
28508            );
28509            assert!(
28510                std::ptr::eq(s.placement(), &s.placement),
28511                "AplicacaoSpec::placement accessor and &self.placement \
28512                 field access must borrow the same backing storage — the \
28513                 accessor is the substrate-primitive typed dispatch every \
28514                 downstream distribution-composite consumer must route \
28515                 through, and a reference-identity split would silently \
28516                 break every consumer that relied on the borrow sharing \
28517                 the composite's storage",
28518            );
28519            assert_eq!(
28520                s.placement().estrategia(),
28521                s.placement.estrategia,
28522                "AplicacaoSpec::placement().estrategia() must byte-equal \
28523                 self.placement.estrategia — a strategy-drift would \
28524                 silently split the paired `validate_placement` \
28525                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
28526                 peer caixa-mesh programs.yaml `placement.estrategia` \
28527                 emitter's key from the peer `feira app graph` printer's \
28528                 strategy label",
28529            );
28530            assert_eq!(
28531                s.placement().clusters(),
28532                s.placement.clusters.as_slice(),
28533                "AplicacaoSpec::placement().clusters() must byte-equal \
28534                 self.placement.clusters — a cluster-pool drift would \
28535                 silently split the paired `validate_placement` \
28536                 pre-flight `.is_empty()` refusal probe's traversal from \
28537                 the peer caixa-mesh programs.yaml `placement.clusters` \
28538                 emitter's fan-out from the peer `feira app graph` \
28539                 printer's cluster list",
28540            );
28541        }
28542    }
28543
28544    #[test]
28545    fn validate_placement_reads_through_lifted_placement_accessor() {
28546        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
28547        // per-axis bracket-dispatch seed (`let p = self.placement();`,
28548        // followed by the per-axis fan-out `p.clusters()` /
28549        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
28550        // lifted axis-level accessor family) must key off the lifted
28551        // outer accessor, so any future rebrand on the typed slot's
28552        // outer-composite reader shape lands at exactly one place. Pins
28553        // the multi-axis coherence by exercising each per-axis refusal
28554        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
28555        // `:clusters` pool under the outer accessor's reference
28556        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
28557        // strategy with a `None` `:shard-key` under the same projection,
28558        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
28559        // with a `Some` `:shard-key` under the same projection, and
28560        // (4) the canonical `three_member_spec` `Replicated` fixture
28561        // passes `validate_placement` under the outer accessor's
28562        // reference projection — the accessor's reference-projection
28563        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
28564        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
28565        // without silently short-circuiting any.
28566        //
28567        // Peer of the sibling M3
28568        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28569        // (534dc21) multi-axis coherence pin on the per-`:politicas`
28570        // outer mesh-policy composite-reference axis — extends the
28571        // multi-consumer coherence discipline onto the outermost M3
28572        // mesh-slot type's per-Aplicacao distribution composite-
28573        // reference axis, the second `&Composite`-return accessor on
28574        // the outer [`AplicacaoSpec`] type.
28575
28576        // (1) `PlacementWithoutClusters` refusal under the outer
28577        // accessor's reference projection: an empty `:clusters` pool
28578        // must trip the pre-flight refusal probe. The bracket-dispatch's
28579        // first arm reads `p.clusters()` on the reference returned by
28580        // the outer accessor.
28581        let mut spec = three_member_spec();
28582        spec.placement.clusters = Vec::new();
28583        assert_eq!(
28584            spec.validate().unwrap_err(),
28585            AplicacaoError::PlacementWithoutClusters {
28586                estrategia: PlacementStrategy::Replicated,
28587            },
28588        );
28589        assert!(
28590            std::ptr::eq(spec.placement(), &spec.placement),
28591            "the `validate_placement` per-axis bracket-dispatch's \
28592             traversal input must be the same backing composite the \
28593             accessor's reference projection borrows from",
28594        );
28595
28596        // (2) `ShardedWithoutKey` refusal under the outer accessor's
28597        // reference projection: a `Sharded` strategy with a `None`
28598        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
28599        // The bracket-dispatch's third arm reads `p.estrategia()` for
28600        // the match scrutinee then `p.shard_key()` for the cascade
28601        // scrutinee, both on the reference returned by the outer
28602        // accessor.
28603        let mut spec = three_member_spec();
28604        spec.placement.estrategia = PlacementStrategy::Sharded;
28605        spec.placement.shard_key = None;
28606        assert_eq!(
28607            spec.validate().unwrap_err(),
28608            AplicacaoError::ShardedWithoutKey,
28609        );
28610
28611        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
28612        // reference projection: a non-`Sharded` strategy with a `Some`
28613        // `:shard-key` must trip the declared-but-inert refusal. The
28614        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
28615        // + `p.estrategia()` for the diagnostic on the reference
28616        // returned by the outer accessor.
28617        let mut spec = three_member_spec();
28618        spec.placement.estrategia = PlacementStrategy::Replicated;
28619        spec.placement.shard_key = Some("tenantId".into());
28620        assert_eq!(
28621            spec.validate().unwrap_err(),
28622            AplicacaoError::ShardKeyOnNonSharded {
28623                estrategia: PlacementStrategy::Replicated,
28624                shard_key: "tenantId".into(),
28625            },
28626        );
28627
28628        // (4) Canonical `three_member_spec` `Replicated` fixture passes
28629        // `validate_placement` — every per-axis arm reaches the fall-
28630        // through `Ok(())` without any per-axis refusal firing under the
28631        // outer accessor's reference projection.
28632        let spec = three_member_spec();
28633        assert!(
28634            spec.validate().is_ok(),
28635            "the canonical Replicated placement fixture must pass \
28636             `validate_placement` — every per-axis arm short-circuits on \
28637             valid input under the outer accessor's reference projection",
28638        );
28639        assert_eq!(
28640            spec.placement().estrategia(),
28641            PlacementStrategy::Replicated,
28642            "the outer accessor's reference projection must be the \
28643             canonical Replicated fixture's strategy",
28644        );
28645        assert_eq!(
28646            spec.placement().clusters(),
28647            &["rio", "mar"],
28648            "the outer accessor's reference projection must be the \
28649             canonical Replicated fixture's cluster pool",
28650        );
28651    }
28652
28653    #[test]
28654    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
28655        // The canonical per-`:entrada` outer-composite-optional-
28656        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
28657        // the `:entrada` typed `Option<Entrada>` verbatim as an
28658        // `Option<&Entrada>` reference over the same backing storage
28659        // the raw `self.entrada.as_ref()` field access borrows from,
28660        // byte-equal across every representative fixture in the
28661        // accept-set — the author-omitted `None` shape (the
28662        // "internal-only mesh" partition every downstream external-
28663        // gateway emitter treats as "emit nothing"), the minimal
28664        // singleton `:entrada` composite (host + destination + empty
28665        // paths + default port), the paths-carrying composite (the
28666        // canonical `three_member_spec` fixture's ["/api" "/health"]
28667        // path-list shape every HTTPRoute per-rule fan-out emitter
28668        // reads), and the non-default port composite (the canonical
28669        // custom-port shape the port-fallback resolver reads).
28670        //
28671        // Pins against a future silent detour that returned a fresh-
28672        // cloned `Entrada` copy (which would type-check via a `Clone`
28673        // impl but silently break every downstream caller that
28674        // relied on the reference sharing the composite's backing
28675        // identity), a reference to an operator-resolved overlay
28676        // (the future per-cluster `:entrada-overrides` slot the
28677        // MESH-COMPOSITION §V federation roadmap acknowledges — its
28678        // resolution must land at exactly this accessor body, not
28679        // silently divert the raw slot away from a second consumer),
28680        // a `None` → `Some(Entrada::default)` cluster-default
28681        // projection (which would collapse the load-bearing
28682        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
28683        // the peer `gateway_routes` early-return + `feira app graph`
28684        // internal-only-mesh partition both read), or an axis-
28685        // shuffled projection (a future detour that swapped
28686        // `host` and `para` through the accessor would silently
28687        // split the paired `validate` per-`:entrada` shape-and-
28688        // membership gate's traversal input from the peer
28689        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
28690        // fan-out input from the peer `feira app graph` external-
28691        // gateway summary line).
28692        //
28693        // Peer of the sibling M3
28694        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
28695        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
28696        // `:politicas` outer mesh-policy composite-reference axis
28697        // and of the sibling M3
28698        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
28699        // (9abb8f0) `&Placement` byte-equal pin on the per-
28700        // `:placement` outer distribution-composite composite-
28701        // reference axis — extends the outer-accessor byte-equal-
28702        // projection discipline onto the last unlifted outermost M3
28703        // mesh-slot type's per-Aplicacao external-gateway composite-
28704        // reference axis, the third and final `&Composite`-return
28705        // accessor on the outer [`AplicacaoSpec`] type.
28706        let fixtures: Vec<Option<Entrada>> = vec![
28707            None,
28708            Some(Entrada {
28709                host: "checkout.quero.cloud".into(),
28710                para: "cart".into(),
28711                paths: Vec::new(),
28712                port: DEFAULT_SERVICO_PORT,
28713            }),
28714            Some(Entrada {
28715                host: "checkout.quero.cloud".into(),
28716                para: "cart".into(),
28717                paths: vec!["/api".into(), "/health".into()],
28718                port: DEFAULT_SERVICO_PORT,
28719            }),
28720            Some(Entrada {
28721                host: "checkout.quero.cloud".into(),
28722                para: "cart".into(),
28723                paths: vec!["/api".into()],
28724                port: 9443,
28725            }),
28726        ];
28727        for entrada in fixtures {
28728            let s = AplicacaoSpec {
28729                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28730                contratos: Vec::new(),
28731                politicas: MeshPolicy::default(),
28732                placement: Placement::default(),
28733                entrada: entrada.clone(),
28734            };
28735            assert_eq!(
28736                s.entrada(),
28737                entrada.as_ref(),
28738                "AplicacaoSpec::entrada must return :entrada verbatim \
28739                 (got {:?}, expected {:?})",
28740                s.entrada(),
28741                entrada.as_ref(),
28742            );
28743            match (s.entrada(), s.entrada.as_ref()) {
28744                (Some(a), Some(b)) => assert!(
28745                    std::ptr::eq(a, b),
28746                    "AplicacaoSpec::entrada accessor and \
28747                     self.entrada.as_ref() field access must borrow \
28748                     the same backing storage — the accessor is the \
28749                     substrate-primitive typed dispatch every \
28750                     downstream external-gateway composite consumer \
28751                     must route through, and a reference-identity \
28752                     split would silently break every consumer that \
28753                     relied on the borrow sharing the composite's \
28754                     storage",
28755                ),
28756                (None, None) => {}
28757                _ => panic!(
28758                    "AplicacaoSpec::entrada presence bit must byte-\
28759                     equal self.entrada.is_some() — a presence-bit \
28760                     drift would silently split the paired `validate` \
28761                     per-`:entrada` shape-and-membership gate's \
28762                     traversal head from the peer \
28763                     caixa-mesh gateway_routes early-return partition \
28764                     from the peer `feira app graph` internal-only-\
28765                     mesh partition",
28766                ),
28767            }
28768            assert_eq!(
28769                s.entrada().is_some(),
28770                s.entrada.is_some(),
28771                "AplicacaoSpec::entrada().is_some() must byte-equal \
28772                 self.entrada.is_some() — a presence-bit drift would \
28773                 silently split every downstream `Option<&Entrada>` \
28774                 consumer's partition on the internal-only-mesh arm",
28775            );
28776        }
28777    }
28778
28779    #[test]
28780    fn validate_reads_through_lifted_entrada_accessor() {
28781        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
28782        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
28783        // self.entrada() { … }`, followed by the per-axis fan-out
28784        // `validate_entrada_para(&e.para)` /
28785        // `EntradaMemberMissing` membership lookup /
28786        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
28787        // per-`e.paths` `validate_entrada_path` traversal) must key
28788        // off the lifted outer accessor, so any future rebrand on
28789        // the typed slot's outer-composite reader shape lands at
28790        // exactly one place. Pins the multi-axis coherence by
28791        // exercising each per-axis refusal end-to-end: (1) the
28792        // author-omitted `None` shape short-circuits past every
28793        // per-`:entrada` refusal (the internal-only mesh partition
28794        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
28795        // fires on a well-shaped but phantom `:para` under the outer
28796        // accessor's reference projection, and (3) the canonical
28797        // `three_member_spec` `:entrada` fixture passes `validate`
28798        // under the outer accessor's reference projection.
28799        //
28800        // Peer of the sibling M3
28801        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28802        // (534dc21) multi-axis coherence pin on the per-`:politicas`
28803        // outer mesh-policy composite-reference axis and the sibling
28804        // M3
28805        // [`validate_placement_reads_through_lifted_placement_accessor`]
28806        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
28807        // outer distribution-composite composite-reference axis —
28808        // extends the multi-consumer coherence discipline onto the
28809        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
28810        // external-gateway composite-reference axis, the third and
28811        // final `&Composite`-return accessor on the outer
28812        // [`AplicacaoSpec`] type.
28813
28814        // (1) `None` :entrada — the internal-only-mesh partition
28815        // short-circuits past every per-`:entrada` refusal. The outer
28816        // accessor's reference projection reaches the fall-through
28817        // `Ok(())` on the `None` arm without any per-axis refusal
28818        // firing.
28819        let mut spec = three_member_spec();
28820        spec.entrada = None;
28821        assert!(
28822            spec.validate().is_ok(),
28823            "an author-omitted `:entrada` must pass `validate` — the \
28824             internal-only-mesh partition short-circuits past every \
28825             per-`:entrada` refusal under the outer accessor's \
28826             reference projection",
28827        );
28828        assert!(
28829            spec.entrada().is_none(),
28830            "the outer accessor's reference projection must name the \
28831             internal-only-mesh partition per the `None` fixture",
28832        );
28833
28834        // (2) `EntradaMemberMissing` refusal under the outer accessor's
28835        // reference projection: a well-shaped but phantom `:para` must
28836        // trip the membership-lookup refusal. The gate's second arm
28837        // reads `e.para` on the reference returned by the outer
28838        // accessor.
28839        let mut spec = three_member_spec();
28840        if let Some(e) = spec.entrada.as_mut() {
28841            e.para = "phantom".into();
28842        }
28843        assert_eq!(
28844            spec.validate().unwrap_err(),
28845            AplicacaoError::EntradaMemberMissing {
28846                para: "phantom".into(),
28847            },
28848        );
28849        match (spec.entrada(), spec.entrada.as_ref()) {
28850            (Some(a), Some(b)) => assert!(
28851                std::ptr::eq(a, b),
28852                "the `validate` per-`:entrada` gate's traversal head \
28853                 must be the same backing composite the accessor's \
28854                 reference projection borrows from",
28855            ),
28856            _ => panic!("fixture must carry Some(:entrada)"),
28857        }
28858
28859        // (3) Canonical `three_member_spec` `:entrada` fixture passes
28860        // `validate` — every per-axis arm reaches the fall-through
28861        // `Ok(())` without any per-axis refusal firing under the
28862        // outer accessor's reference projection.
28863        let spec = three_member_spec();
28864        assert!(
28865            spec.validate().is_ok(),
28866            "the canonical `:entrada` fixture must pass `validate` — \
28867             every per-axis arm short-circuits on valid input under \
28868             the outer accessor's reference projection",
28869        );
28870        assert!(
28871            spec.entrada().is_some(),
28872            "the outer accessor's reference projection must be the \
28873             canonical `:entrada` fixture's composite",
28874        );
28875    }
28876
28877    #[test]
28878    fn membro_names_matches_inline_membros_projection() {
28879        // Substrate-primitive ≡ inline-projection pin on
28880        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
28881        // must be byte-for-byte the set the pre-lift inline
28882        // `self.membros().iter().map(Membro::nome).collect()` builder
28883        // produced, on every membership shape the three
28884        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
28885        // :para`, `:entrada :para`) resolve against. Pins the
28886        // projection so a future rebrand of the node-identity axis
28887        // lands at the primitive rather than diverging between the
28888        // per-`:contratos` membership arms still inline at `validate`
28889        // and the lifted `validate_entrada` gate.
28890        for membros in [
28891            vec![],
28892            vec![membro("cart", "^0.1")],
28893            vec![
28894                membro("catalog", "^0.1"),
28895                membro("cart", "^0.1"),
28896                membro("payment", "^0.2"),
28897            ],
28898        ] {
28899            let mut spec = three_member_spec();
28900            spec.membros = membros;
28901            let inline: std::collections::HashSet<&str> =
28902                spec.membros().iter().map(Membro::nome).collect();
28903            assert_eq!(
28904                spec.membro_names(),
28905                inline,
28906                "the lifted membership oracle must discriminate the \
28907                 same node set as the pre-lift inline projection",
28908            );
28909        }
28910    }
28911
28912    #[test]
28913    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
28914        // Per-slot-gate ≡ validate equivalence pin on the lifted
28915        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
28916        // must discriminate the same set as [`AplicacaoSpec::validate`]
28917        // on every `:entrada`-covered input, so a future consumer that
28918        // re-validates the one slot (the M4 admission webhook
28919        // re-checking `:entrada` after a gateway-host patch) accepts
28920        // exactly what `feira build` accepts and surfaces the same
28921        // diagnostic on the same input. Covers each of the five gated
28922        // axes plus the two clean-pass shapes (`None` — the
28923        // internal-only-mesh partition — and the canonical fixture).
28924        //
28925        // Peer of the sibling per-slot equivalence pins
28926        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
28927        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
28928        // `:politicas` slot's compound entry gate, extended here onto
28929        // the `:entrada` slot's newly-named per-slot gate.
28930        /// One `:entrada` equivalence case: a label, the per-axis
28931        /// mutation applied to the canonical fixture's composite, and
28932        /// the diagnostic both the per-slot gate and `validate` must
28933        /// surface on it (`None` = clean pass).
28934        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
28935
28936        let cases: &[EntradaCase] = &[
28937            (
28938                ":para shape — empty",
28939                |e| e.para = String::new(),
28940                Some(AplicacaoError::EntradaParaEmpty),
28941            ),
28942            (
28943                ":para membership — well-shaped phantom",
28944                |e| e.para = "phantom".into(),
28945                Some(AplicacaoError::EntradaMemberMissing {
28946                    para: "phantom".into(),
28947                }),
28948            ),
28949            (
28950                ":host emptiness",
28951                |e| e.host = String::new(),
28952                Some(AplicacaoError::EmptyEntradaHost),
28953            ),
28954            (
28955                ":port structural floor",
28956                |e| e.port = 0,
28957                Some(AplicacaoError::EntradaPortZero),
28958            ),
28959            (
28960                ":paths per-entry emptiness",
28961                |e| e.paths = vec![String::new()],
28962                Some(AplicacaoError::EntradaPathEmpty),
28963            ),
28964            (
28965                ":paths leading-slash grammar",
28966                |e| e.paths = vec!["api/cart".into()],
28967                Some(AplicacaoError::EntradaPathNotAbsolute {
28968                    path: "api/cart".into(),
28969                }),
28970            ),
28971            (
28972                ":paths set-not-multiset",
28973                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
28974                Some(AplicacaoError::EntradaPathDuplicate {
28975                    path: "/api/cart".into(),
28976                }),
28977            ),
28978            ("clean pass — canonical fixture", |_| {}, None),
28979        ];
28980        for (label, mutate, expected) in cases {
28981            let mut spec = three_member_spec();
28982            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
28983            assert_eq!(
28984                spec.validate_entrada().err(),
28985                *expected,
28986                "per-slot gate disagreed with the expected diagnostic on {label}",
28987            );
28988            assert_eq!(
28989                spec.validate().err(),
28990                *expected,
28991                "`validate` disagreed with the per-slot gate on {label}",
28992            );
28993        }
28994
28995        // The `None` arm is the internal-only-mesh partition: a clean
28996        // pass through both the per-slot gate and `validate`, not a
28997        // refusal.
28998        let mut spec = three_member_spec();
28999        spec.entrada = None;
29000        assert_eq!(spec.validate_entrada().err(), None);
29001        assert_eq!(spec.validate().err(), None);
29002    }
29003
29004    #[test]
29005    fn validate_entrada_resolves_membership_through_own_oracle() {
29006        // Self-containment pin on the lifted per-slot gate:
29007        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
29008        // against the oracle *it* builds through
29009        // [`AplicacaoSpec::membro_names`], not one threaded down from
29010        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
29011        // longer contains the `:entrada :para` target must trip
29012        // `EntradaMemberMissing` when the per-slot gate is called
29013        // directly — the shape a future single-slot re-validator
29014        // (the M4 admission webhook) reaches the axis through, without
29015        // re-walking `:membros` / `:contratos` / the sync-cycle
29016        // detector first. Same self-contained posture
29017        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
29018        // the M4 per-edge policy resolver.
29019        let mut spec = three_member_spec();
29020        spec.membros.retain(|m| m.nome() != "cart");
29021        assert_eq!(
29022            spec.validate_entrada().unwrap_err(),
29023            AplicacaoError::EntradaMemberMissing {
29024                para: "cart".into(),
29025            },
29026            "the per-slot gate must resolve `:para` against the oracle \
29027             it builds itself, with no membership set threaded in",
29028        );
29029        assert!(
29030            !spec.membro_names().contains("cart"),
29031            "fixture must have dropped the `:entrada :para` target \
29032             from the graph's node set",
29033        );
29034    }
29035
29036    #[test]
29037    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
29038        // Per-slot-gate ≡ validate equivalence pin on the lifted
29039        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
29040        // gate must discriminate the same set as
29041        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
29042        // input, so a future consumer that re-validates the one slot
29043        // (the M4 admission webhook re-checking `:contratos` after a
29044        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
29045        // `:politicas` override MESH-COMPOSITION §III.2 #3
29046        // acknowledges — which resolves an effective per-edge
29047        // [`MeshPolicy`] and must re-check the edge's identity closure
29048        // before it can key a per-edge override off the endpoint
29049        // tuple) accepts exactly what `feira build` accepts and
29050        // surfaces the same diagnostic on the same input. Covers each
29051        // of the six gated axes (`:de`/`:para` per-arm shape,
29052        // per-arm graph-membership, structural self-loop, `:wit`
29053        // emptiness) plus the clean-pass canonical fixture; the
29054        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
29055        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
29056        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
29057        // `target:` carriers depend on library implementation
29058        // details are pinned separately below with a `matches!`
29059        // predicate on the arm identity plus the mirror equivalence
29060        // between the two entry points.
29061        //
29062        // Peer of the sibling per-slot equivalence pins
29063        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29064        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
29065        // `:politicas` slot's compound entry gate, and
29066        // `validate_entrada_matches_gate_on_every_per_axis_shape`
29067        // (20cd523) on the `:entrada` slot's per-slot gate — extended
29068        // here onto the `:contratos` slot's newly-named per-slot gate,
29069        // closing the last unlifted per-slot gate on the M3 mesh-slot
29070        // family.
29071        /// One `:contratos` equivalence case: a label, the per-axis
29072        /// mutation applied to the canonical fixture's spec, and the
29073        /// diagnostic both the per-slot gate and `validate` must
29074        /// surface on it (`None` = clean pass).
29075        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
29076
29077        let cases: &[ContratoCase] = &[
29078            (
29079                ":de shape — empty",
29080                |s| s.contratos[0].de = String::new(),
29081                Some(AplicacaoError::ContratoCaixaEmpty {
29082                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
29083                }),
29084            ),
29085            (
29086                ":para shape — empty",
29087                |s| s.contratos[0].para = String::new(),
29088                Some(AplicacaoError::ContratoCaixaEmpty {
29089                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
29090                }),
29091            ),
29092            (
29093                ":de membership — well-shaped phantom",
29094                |s| s.contratos[0].de = "phantom".into(),
29095                Some(AplicacaoError::ContratoMemberMissing {
29096                    caixa: "phantom".into(),
29097                }),
29098            ),
29099            (
29100                ":para membership — well-shaped phantom",
29101                |s| s.contratos[0].para = "phantom".into(),
29102                Some(AplicacaoError::ContratoMemberMissing {
29103                    caixa: "phantom".into(),
29104                }),
29105            ),
29106            (
29107                "structural self-loop",
29108                |s| s.contratos[0].para = "cart".into(),
29109                Some(AplicacaoError::ContratoSelfLoop {
29110                    caixa: "cart".into(),
29111                    wit: "wasi:http/proxy".into(),
29112                }),
29113            ),
29114            (
29115                ":wit emptiness",
29116                |s| s.contratos[0].wit = String::new(),
29117                Some(AplicacaoError::EmptyWit {
29118                    de: "cart".into(),
29119                    para: "catalog".into(),
29120                }),
29121            ),
29122            ("clean pass — canonical fixture", |_| {}, None),
29123        ];
29124        for (label, mutate, expected) in cases {
29125            let mut spec = three_member_spec();
29126            mutate(&mut spec);
29127            assert_eq!(
29128                spec.validate_contratos().err(),
29129                *expected,
29130                "per-slot gate disagreed with the expected diagnostic on {label}",
29131            );
29132            assert_eq!(
29133                spec.validate().err(),
29134                *expected,
29135                "`validate` disagreed with the per-slot gate on {label}",
29136            );
29137        }
29138    }
29139
29140    #[test]
29141    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
29142        // Companion pin to
29143        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
29144        // the per-slot gate ≡ `validate` equivalence on the three
29145        // `:contratos` refusal arms whose diagnostic carries a
29146        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
29147        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
29148        // `is_dns_1123_label` / `WitContract::target` shape helpers,
29149        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
29150        // library-formatted `target:` scalar). Value equality between
29151        // the per-slot gate and `validate` outputs pins the full
29152        // `Option<AplicacaoError>` (including reason-strings), and the
29153        // per-arm `matches!` predicate pins the arm-discriminator
29154        // identity on the specific `Contrato*` variant. Split from
29155        // the primary equivalence pin so each pin body stays under
29156        // [`clippy::too_many_lines`], the same shape the peer
29157        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29158        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
29159        // carries on the `:politicas` slot's compound entry gate.
29160        type ContratoReasonCase = (
29161            &'static str,
29162            fn(&mut AplicacaoSpec),
29163            fn(&AplicacaoError) -> bool,
29164        );
29165        let cases: &[ContratoReasonCase] = &[
29166            (
29167                ":de shape — DNS-1123 invalid",
29168                |s| s.contratos[0].de = "Cart".into(),
29169                |err| {
29170                    matches!(
29171                        err,
29172                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
29173                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
29174                    )
29175                },
29176            ),
29177            (
29178                ":wit target-shape mismatch — payload on capability arm",
29179                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
29180                |err| {
29181                    matches!(
29182                        err,
29183                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
29184                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
29185                    )
29186                },
29187            ),
29188            (
29189                "whole-edge dedup — six-axis identity collision",
29190                |s| {
29191                    let dup = s.contratos[0].clone();
29192                    s.contratos.push(dup);
29193                },
29194                |err| {
29195                    matches!(
29196                        err,
29197                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
29198                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
29199                    )
29200                },
29201            ),
29202        ];
29203        for (label, mutate, arm_matches) in cases {
29204            let mut spec = three_member_spec();
29205            mutate(&mut spec);
29206            let per_slot = spec.validate_contratos().err();
29207            let gate = spec.validate().err();
29208            assert_eq!(
29209                per_slot, gate,
29210                "per-slot gate and `validate` must return byte-equal \
29211                 `Option<AplicacaoError>` on {label} (including \
29212                 library-owned reason strings)",
29213            );
29214            let err = per_slot
29215                .as_ref()
29216                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
29217            assert!(
29218                arm_matches(err),
29219                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
29220            );
29221        }
29222    }
29223
29224    #[test]
29225    fn validate_contratos_resolves_membership_through_own_oracle() {
29226        // Self-containment pin on the lifted per-slot gate:
29227        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
29228        // `:de` / `:para` against the oracle *it* builds through
29229        // [`AplicacaoSpec::membro_names`], not one threaded down from
29230        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
29231        // longer contains a `:contratos` edge's endpoint must trip
29232        // `ContratoMemberMissing` when the per-slot gate is called
29233        // directly — the shape a future single-slot re-validator
29234        // (the M4 admission webhook re-checking `:contratos` after a
29235        // per-`(:de, :para)` edge patch, the M4 per-edge policy
29236        // resolver on the `:politicas` override axis) reaches the
29237        // axis through, without re-walking `:membros` / `:entrada` /
29238        // `:placement` / `:politicas` first. Same self-contained
29239        // posture the peer per-slot gates
29240        // [`AplicacaoSpec::detect_sync_cycles`] and
29241        // [`AplicacaoSpec::validate_entrada`] already carry for the
29242        // same M4 consumers.
29243        let mut spec = three_member_spec();
29244        spec.membros.retain(|m| m.nome() != "catalog");
29245        assert_eq!(
29246            spec.validate_contratos().unwrap_err(),
29247            AplicacaoError::ContratoMemberMissing {
29248                caixa: "catalog".into(),
29249            },
29250            "the per-slot gate must resolve `:de` / `:para` against \
29251             the oracle it builds itself, with no membership set \
29252             threaded in",
29253        );
29254        assert!(
29255            !spec.membro_names().contains("catalog"),
29256            "fixture must have dropped the `:contratos` edge's \
29257             `:para` target from the graph's node set",
29258        );
29259    }
29260
29261    #[test]
29262    fn validate_contratos_folds_cycle_axis_matches_gate() {
29263        // Fold-into-per-slot-gate equivalence pin on the
29264        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
29265        // surfaces byte-equal through both
29266        // [`AplicacaoSpec::validate_contratos`] and
29267        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
29268        // a synchronous-edge cycle in `:contratos`. Pins the fold that
29269        // moved the cross-edge cycle axis onto the per-slot gate — a
29270        // future silent regression that de-folded the axis back to the
29271        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
29272        // a peer per-slot gate lift that skipped the cross-axis half of
29273        // the [`MeshPolicy::validate`]-analogous discipline) would
29274        // surface here as `Some(ContratoCycle)` from `validate` and
29275        // `None` from `validate_contratos`.
29276        //
29277        // Cycle fixture is the same shape as the peer
29278        // [`rejects_three_node_synchronous_cycle`] test carries: a
29279        // clean 3-cycle over the HTTP subgraph (catalog → cart →
29280        // payment → catalog), so the per-entry cascade (shape +
29281        // membership + self-loop + `:wit` emptiness + WIT-target +
29282        // whole-edge dedup) passes cleanly and the sole surviving
29283        // refusal shape is the cross-edge cycle axis. The `cycle`
29284        // vector is normalized to a sorted body set for the equality
29285        // compare (the traversal path's starting node depends on
29286        // BTreeMap iteration order, which is deterministic but is not
29287        // the load-bearing property this pin covers).
29288        //
29289        // Peer of the sibling per-slot ≡ `validate` equivalence pins
29290        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
29291        // (per-entry axes) and
29292        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
29293        // (parser-owned reason arms) already carry on the six
29294        // per-entry axes — this extends the discipline onto the
29295        // cross-edge cycle axis newly folded into the per-slot gate,
29296        // matching the peer per-slot compound gate
29297        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
29298        // both per-axis and cross-axis surfaces on `:politicas`.
29299        let mut spec = three_member_spec();
29300        spec.contratos = vec![
29301            contract_http("catalog", "cart", "/x"),
29302            contract_http("cart", "payment", "/y"),
29303            contract_http("payment", "catalog", "/z"),
29304        ];
29305        let per_slot_err = spec.validate_contratos().unwrap_err();
29306        let gate_err = spec.validate().unwrap_err();
29307        assert_eq!(
29308            per_slot_err, gate_err,
29309            "the per-slot gate and `validate` must return byte-equal \
29310             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
29311             — the fold pins the cross-edge axis onto the per-slot \
29312             gate the same way the peer `validate_politicas` fold \
29313             pinned the `:politicas` cross-axis surface",
29314        );
29315        match per_slot_err {
29316            AplicacaoError::ContratoCycle { ref cycle } => {
29317                assert_eq!(
29318                    cycle.first(),
29319                    cycle.last(),
29320                    "cycle traversal must close on the back-edge \
29321                     target — the diagnostic shape the peer \
29322                     `rejects_three_node_synchronous_cycle` pins",
29323                );
29324                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
29325                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
29326                assert!(body.contains("cart"));
29327                assert!(body.contains("catalog"));
29328                assert!(body.contains("payment"));
29329            }
29330            other => panic!("expected ContratoCycle, got {other:?}"),
29331        }
29332    }
29333
29334    #[test]
29335    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
29336        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
29337        // carrying *both* a per-entry defect (a self-loop, the
29338        // structural-self-edge arm on the per-entry cascade — chosen
29339        // because it never masks or is masked by the cycle diagnostic
29340        // on the peer arms) *and* a would-be synchronous-edge cycle in
29341        // the remaining edges must surface the per-entry diagnostic
29342        // first through both [`AplicacaoSpec::validate_contratos`] and
29343        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
29344        // per-entry-before-cross-edge dispatch ordering, byte-equal to
29345        // the pre-fold `validate`-side sequence
29346        // (`validate_contratos()? → detect_sync_cycles()?`) the
29347        // dispatch encoded verbatim. A silent regression that reversed
29348        // the ordering inside the fold would surface here as a cycle
29349        // diagnostic on a fixture carrying an earlier per-entry defect
29350        // — masking the narrower "this edge is degenerate" arm behind
29351        // the coarser "this graph deadlocks" arm.
29352        //
29353        // Peer of the diagnostic-ordering property the pre-fold
29354        // dispatch encoded at the [`AplicacaoSpec::validate`]
29355        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
29356        // now enforced inside the per-slot gate's own body, so a future
29357        // consumer that reaches only the per-slot gate (the M4
29358        // admission webhook re-checking `:contratos` after a per-edge
29359        // patch) inherits the ordering property by construction.
29360        let mut spec = three_member_spec();
29361        // The three-member fixture already has cart → catalog and
29362        // cart → payment; adding catalog → cart closes a 2-cycle on
29363        // the HTTP subgraph.
29364        spec.contratos
29365            .push(contract_http("catalog", "cart", "/refresh"));
29366        // Add a self-loop on `payment` — the per-entry structural-
29367        // self-edge arm — which must surface first.
29368        spec.contratos
29369            .push(contract_http("payment", "payment", "/loop"));
29370        let per_slot_err = spec.validate_contratos().unwrap_err();
29371        let gate_err = spec.validate().unwrap_err();
29372        assert_eq!(
29373            per_slot_err, gate_err,
29374            "per-slot gate and `validate` must agree on the ordering \
29375             fixture's surfaced diagnostic — a divergence here means \
29376             the fold reshaped one dispatch's ordering without the \
29377             other",
29378        );
29379        assert!(
29380            matches!(
29381                per_slot_err,
29382                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
29383                    if caixa == "payment"
29384            ),
29385            "the per-entry structural-self-edge arm must fire before \
29386             the cross-edge cycle arm — pinning the fold's per-entry-\
29387             before-cross-edge dispatch ordering byte-equal to the \
29388             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
29389             sequence; got {per_slot_err:?}",
29390        );
29391    }
29392
29393    #[test]
29394    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
29395        // Self-containment pin on the folded cross-edge cycle axis:
29396        // [`AplicacaoSpec::validate_contratos`] surfaces
29397        // [`AplicacaoError::ContratoCycle`] directly against `&self`
29398        // without depending on the peer per-slot gates
29399        // ([`AplicacaoSpec::validate_membros`],
29400        // [`AplicacaoSpec::validate_entrada`],
29401        // [`AplicacaoSpec::validate_placement`],
29402        // [`AplicacaoSpec::validate_politicas`]) running first — the
29403        // shape a future single-slot re-validator (the M4 admission
29404        // webhook re-checking `:contratos` after a per-`(:de, :para)`
29405        // edge patch, the per-edge policy resolver MESH-COMPOSITION
29406        // §III.2 #3 acknowledges) reaches *both* structural axes on
29407        // the slot through one call. A spec with a per-`:politicas`
29408        // refusal shape (zero `:timeout`, the first per-axis arm the
29409        // peer [`MeshPolicy::validate`] gate covers) AND a
29410        // synchronous-edge cycle in `:contratos` must:
29411        //
29412        //   - surface [`AplicacaoError::ContratoCycle`] through the
29413        //     per-slot gate `validate_contratos` directly (proves the
29414        //     cycle axis reaches the per-slot altitude without the
29415        //     peer `:politicas` gate running first);
29416        //   - surface [`AplicacaoError::ContratoCycle`] through
29417        //     `validate` (which reaches `validate_contratos` before
29418        //     `validate_politicas` per the fixed dispatch order), so
29419        //     the fold's cross-slot ordering (`:membros` →
29420        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
29421        //     is byte-equal to the pre-fold dispatch's ordering.
29422        //
29423        // Same self-contained-on-`&self` posture the peer per-slot
29424        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
29425        // [`AplicacaoSpec::validate_contratos`] per-entry axis
29426        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
29427        // (f03a154) already carry — extended here onto the newly-
29428        // folded cross-edge cycle axis. Peer of the sibling per-slot
29429        // self-containment pins
29430        // `validate_entrada_resolves_membership_through_own_oracle`
29431        // and `validate_contratos_resolves_membership_through_own_oracle`
29432        // on the per-entry membership axis — extends the discipline
29433        // onto the cross-edge cycle axis of the same per-slot gate.
29434        let mut spec = three_member_spec();
29435        // Poison `:politicas` — zero-`:timeout` trips the first per-
29436        // axis arm the [`MeshPolicy::validate`] gate covers, so any
29437        // dispatch that reached `:politicas` would surface a
29438        // `:politicas` diagnostic instead of `ContratoCycle`.
29439        spec.politicas.timeout = Some(Duration::from_secs(0));
29440        // Close a synchronous-edge cycle on the HTTP subgraph.
29441        spec.contratos
29442            .push(contract_http("catalog", "cart", "/refresh"));
29443        let per_slot_err = spec.validate_contratos().unwrap_err();
29444        assert!(
29445            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
29446            "the per-slot gate must surface `ContratoCycle` directly \
29447             against `&self` — a peer per-slot gate's regression \
29448             would surface a non-`ContratoCycle` diagnostic here; \
29449             got {per_slot_err:?}",
29450        );
29451        let gate_err = spec.validate().unwrap_err();
29452        assert!(
29453            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
29454            "`validate`'s five-slot dispatch must reach the fold's \
29455             cross-edge cycle axis on `:contratos` before the peer \
29456             `:politicas` gate — a dispatch-order regression would \
29457             surface a `:politicas` diagnostic here; got {gate_err:?}",
29458        );
29459        // Sanity: the poisoned `:politicas` alone would trip
29460        // [`MeshPolicy::validate`] under the peer per-slot gate, so
29461        // the cycle-first surfacing above is a real ordering property,
29462        // not a case where the `:politicas` axis silently accepts the
29463        // fixture.
29464        let mut politicas_only = three_member_spec();
29465        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
29466        assert!(
29467            politicas_only.validate_politicas().is_err(),
29468            "the poisoned `:politicas` fixture must trip the peer \
29469             per-slot gate on its own — otherwise the self-contained \
29470             cycle-first surfacing above would not be an ordering \
29471             property",
29472        );
29473    }
29474
29475    #[test]
29476    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
29477        // Fail-before-pass-after equivalence pin on the lifted
29478        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
29479        // both arms (`:de` phantom and `:para` phantom) must fire the
29480        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
29481        // `caixa` carrier byte-equal to the offending accessor's
29482        // projection, and `:de` must fire before `:para` when both
29483        // arms would trip on the same call — preserving the canonical
29484        // edge-direction order the peer per-arm shape gate
29485        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
29486        // diagnostic, and every peer per-arm ordering in
29487        // [`AplicacaoSpec::validate_contratos`] already carry.
29488        //
29489        // Two-endpoint oracle covers exactly enough graph nodes to
29490        // exercise each arm in isolation: the `:de` arm fires when
29491        // the source is off-oracle and the destination is on-oracle,
29492        // the `:para` arm fires when the source is on-oracle and the
29493        // destination is off-oracle, and the `:de`-before-`:para`
29494        // ordering falls out from a probe where *both* endpoints are
29495        // off-oracle — the diagnostic's `caixa` field must byte-equal
29496        // the source, not the destination, pinning the primitive's
29497        // arm ordering as `:de` first.
29498        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
29499        names.insert("cart");
29500        names.insert("catalog");
29501
29502        // `:de` phantom, `:para` on-oracle
29503        let de_phantom = contract_http("phantom-de", "catalog", "/x");
29504        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
29505        assert_eq!(
29506            err,
29507            AplicacaoError::ContratoMemberMissing {
29508                caixa: de_phantom.source().to_string(),
29509            },
29510            "the `:de` phantom arm must fire ContratoMemberMissing \
29511             with `caixa` byte-equal to `WitContract::source` — a \
29512             bypass here (a raw `.de.clone()` regression, a divergent \
29513             accessor on a per-CR alias table) would silently split \
29514             the primitive's diagnostic from the substrate-primitive \
29515             scalar accessor every downstream consumer routes through",
29516        );
29517
29518        // `:de` on-oracle, `:para` phantom
29519        let para_phantom = contract_http("cart", "phantom-para", "/x");
29520        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
29521        assert_eq!(
29522            err,
29523            AplicacaoError::ContratoMemberMissing {
29524                caixa: para_phantom.destination().to_string(),
29525            },
29526            "the `:para` phantom arm must fire ContratoMemberMissing \
29527             with `caixa` byte-equal to `WitContract::destination` — \
29528             symmetric callee-side pin to the `:de` arm above",
29529        );
29530
29531        // Both endpoints off-oracle: the `:de` arm must fire first,
29532        // pinning the primitive's canonical edge-direction order.
29533        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
29534        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
29535        assert_eq!(
29536            err,
29537            AplicacaoError::ContratoMemberMissing {
29538                caixa: both_phantom.source().to_string(),
29539            },
29540            "when both endpoints are off-oracle, the `:de` arm must \
29541             fire before the `:para` arm — preserving byte-equal \
29542             ordering with the pre-lift inline cascade in \
29543             `validate_contratos` and with every peer per-arm \
29544             ordering the sibling per-edge substrate primitives \
29545             already carry",
29546        );
29547
29548        // Both endpoints on-oracle: clean pass.
29549        let clean = contract_http("cart", "catalog", "/x");
29550        clean.require_endpoints_in(&names).unwrap();
29551    }
29552
29553    #[test]
29554    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
29555        // Convergence pin: the whole-spec end-to-end route through
29556        // [`AplicacaoSpec::validate_contratos`] must reach the
29557        // per-edge substrate primitive
29558        // [`WitContract::require_endpoints_in`] on every membership
29559        // arm — the diagnostic fired at the per-slot altitude must
29560        // byte-equal the diagnostic the primitive fires when called
29561        // directly on the same edge and the same oracle. Pins the
29562        // primitive as the sole load-bearing gate on the membership
29563        // axis, so any future silent detour that re-inlined the twin
29564        // `if !names.contains(...)` cascade back into the per-slot
29565        // gate (a rebase-artifact regression, an M4 admission-webhook
29566        // consumer that bypassed the primitive) would surface here as
29567        // a byte-equal miss between the two dispatches.
29568        //
29569        // Same equivalence-pin discipline the peer
29570        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
29571        // pin already carries on the per-slot gate ≡ `validate` axis,
29572        // extended here onto the per-slot gate ≡ per-edge primitive
29573        // axis at one altitude deeper.
29574        for phantom_edge in [
29575            contract_http("phantom-de", "catalog", "/x"),
29576            contract_http("cart", "phantom-para", "/x"),
29577        ] {
29578            let mut spec = three_member_spec();
29579            spec.contratos.push(phantom_edge.clone());
29580            let per_slot_err = spec.validate_contratos().unwrap_err();
29581            let primitive_err = phantom_edge
29582                .require_endpoints_in(&spec.membro_names())
29583                .unwrap_err();
29584            assert_eq!(
29585                per_slot_err, primitive_err,
29586                "the per-slot gate must reach the per-edge substrate \
29587                 primitive on every membership arm — a bypass here \
29588                 would silently split the two dispatches on the \
29589                 same edge + same oracle input",
29590            );
29591            // And the diagnostic's `caixa` carrier must byte-equal
29592            // the offending accessor's projection at both altitudes,
29593            // pinning the accessor routing across the whole-spec
29594            // path.
29595            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
29596                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
29597            };
29598            let expected = if spec.membro_names().contains(phantom_edge.source()) {
29599                phantom_edge.destination()
29600            } else {
29601                phantom_edge.source()
29602            };
29603            assert_eq!(
29604                caixa, expected,
29605                "the whole-spec ContratoMemberMissing.caixa carrier \
29606                 must byte-equal the offending edge's accessor \
29607                 projection — a bypass here would silently split \
29608                 the wrap envelope's `caixa` field from the \
29609                 substrate-primitive scalar accessor every \
29610                 downstream consumer routes through",
29611            );
29612        }
29613    }
29614
29615    #[test]
29616    fn port_for_destination_reads_through_lifted_entrada_accessor() {
29617        // Peer coherence pin: the
29618        // [`AplicacaoSpec::port_for_destination`] per-destination
29619        // L4-port fallback resolver's composite-projection seed
29620        // (`self.entrada().filter(…).map_or(…)`) must key off the
29621        // lifted outer accessor. Pins the coherence by exercising
29622        // the resolver end-to-end: (1) the `None` `:entrada` shape
29623        // falls through to `DEFAULT_SERVICO_PORT` under the outer
29624        // accessor's reference projection, (2) a non-matching
29625        // destination falls through to `DEFAULT_SERVICO_PORT` under
29626        // the outer accessor's reference projection, and (3) the
29627        // matching destination resolves to the `:entrada :port`
29628        // value under the outer accessor's reference projection.
29629        //
29630        // Peer of the sibling
29631        // [`validate_reads_through_lifted_entrada_accessor`] multi-
29632        // consumer coherence pin on the same per-`:entrada` outer-
29633        // composite axis — extends the multi-consumer coherence
29634        // discipline onto the second per-`:entrada` production
29635        // consumer, the L4-port fallback resolver.
29636
29637        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
29638        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
29639        // arm under the outer accessor's reference projection.
29640        let mut spec = three_member_spec();
29641        spec.entrada = None;
29642        assert_eq!(
29643            spec.port_for_destination("cart"),
29644            DEFAULT_SERVICO_PORT,
29645            "the port-fallback resolver must fall through to \
29646             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
29647             under the outer accessor's reference projection",
29648        );
29649
29650        // (2) Non-matching destination — the resolver's `filter(…)`
29651        // arm rejects a mismatched destination and falls through
29652        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
29653        // reference projection.
29654        let mut spec = three_member_spec();
29655        if let Some(e) = spec.entrada.as_mut() {
29656            e.para = "cart".into();
29657            e.port = 9443;
29658        }
29659        assert_eq!(
29660            spec.port_for_destination("catalog"),
29661            DEFAULT_SERVICO_PORT,
29662            "the port-fallback resolver must fall through to \
29663             DEFAULT_SERVICO_PORT on a non-matching destination \
29664             under the outer accessor's reference projection",
29665        );
29666
29667        // (3) Matching destination — the resolver's `map_or(…)` arm
29668        // returns the `:entrada :port` value under the outer
29669        // accessor's reference projection.
29670        let mut spec = three_member_spec();
29671        if let Some(e) = spec.entrada.as_mut() {
29672            e.para = "cart".into();
29673            e.port = 9443;
29674        }
29675        assert_eq!(
29676            spec.port_for_destination("cart"),
29677            9443,
29678            "the port-fallback resolver must return the \
29679             `:entrada :port` value on a matching destination \
29680             under the outer accessor's reference projection",
29681        );
29682    }
29683
29684    #[test]
29685    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
29686        // The canonical per-`:politicas` `:mtls-required` mTLS-
29687        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
29688        // must return the `:politicas :mtls-required` typed bool
29689        // verbatim as an `Option<bool>`, byte-equal to the raw field
29690        // access across every value in the three-way accept-set —
29691        // `None` (cluster default applies), `Some(true)` (mTLS
29692        // handshake enforced — the sandboxing-by-default arm the
29693        // MeshPolicy's docstring names), `Some(false)` (handshake
29694        // skipped — the explicit debug-edge opt-out).
29695        //
29696        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
29697        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
29698        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
29699        // shape — first `Option<Copy-T>`-return accessor on the M3
29700        // mesh-slot family. Pins against a future silent detour that
29701        // re-derived the toggle from a peer axis (an accidental
29702        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
29703        // whenever a breaker is set), a `None` → `Some(false)` cluster-
29704        // default projection (the canonical `Option<bool>` → `bool`
29705        // collapse footgun the surrounding `is_empty()` predicate
29706        // guards on the peer emptiness axis), or a `Some(true)` /
29707        // `Some(false)` variant swap that landed on one consumer
29708        // without the other.
29709        for required in [None, Some(true), Some(false)] {
29710            let p = MeshPolicy {
29711                mtls_required: required,
29712                ..MeshPolicy::default()
29713            };
29714            assert_eq!(
29715                p.mtls_required(),
29716                required,
29717                "MeshPolicy::mtls_required must return :politicas \
29718                 :mtls-required verbatim (got {:?}, expected {required:?})",
29719                p.mtls_required(),
29720            );
29721            assert_eq!(
29722                p.mtls_required(),
29723                p.mtls_required,
29724                "MeshPolicy::mtls_required must byte-equal the raw \
29725                 .mtls_required field access across every value in the \
29726                 three-way accept-set",
29727            );
29728        }
29729    }
29730
29731    #[test]
29732    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
29733        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
29734        // arm must key off [`MeshPolicy::mtls_required`], not the raw
29735        // `.mtls_required` field access. Structurally: toggling ONLY
29736        // the `mtls_required` slot on an otherwise-default MeshPolicy
29737        // must flip `is_empty()` from `true` (all-`None`) to `false`
29738        // (one axis carries a value); the flip must be observed for
29739        // both `Some(true)` and `Some(false)` since the emptiness
29740        // semantic reads "any axis carries a value" — not "any axis
29741        // carries a truthy value" — the same non-collapsing shape the
29742        // sibling M2 [`crate::LimitsSpec::is_empty`] /
29743        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
29744        // peer `Option<T>`-typed slot surfaces.
29745        //
29746        // Pins against a future silent detour that re-derived the
29747        // emptiness predicate off a peer axis (an accidental
29748        // `.rate_limit.is_none()`-only chain that dropped the
29749        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
29750        // collapse to a truthy-only check (which would silently
29751        // classify `Some(false)` as empty), or an accessor-side
29752        // detour that no longer names the substrate-primitive typed
29753        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
29754        // == false` fallback in the accessor that would silently
29755        // classify both `None` and `Some(false)` as the same value).
29756        //
29757        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
29758        // (7cd2a28) accessor-composition pin on the sibling optional-
29759        // scalar axis — same "the emptiness / shape-gate predicate
29760        // must route through the substrate-primitive typed dispatch"
29761        // discipline extended onto the peer per-`:politicas` emptiness
29762        // predicate.
29763        let empty = MeshPolicy::default();
29764        assert!(
29765            empty.is_empty(),
29766            "MeshPolicy::default() must be is_empty() — every axis \
29767             defaults to None",
29768        );
29769        for required in [Some(true), Some(false)] {
29770            let p = MeshPolicy {
29771                mtls_required: required,
29772                ..MeshPolicy::default()
29773            };
29774            assert!(
29775                !p.is_empty(),
29776                "MeshPolicy::is_empty must return false when \
29777                 :mtls-required is {required:?} — the emptiness \
29778                 predicate reads \"any axis carries a value\", not \
29779                 \"any axis carries a truthy value\"",
29780            );
29781            assert_eq!(
29782                p.mtls_required().is_none(),
29783                p.is_empty(),
29784                "when :mtls-required is the only set axis, \
29785                 is_empty() must equal mtls_required().is_none() — \
29786                 the accessor and the emptiness predicate must \
29787                 route through the same substrate-primitive typed \
29788                 dispatch on the :mtls-required arm",
29789            );
29790        }
29791    }
29792
29793    #[test]
29794    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
29795        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
29796        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
29797        // accessor must return by value, not by reference. Peer of the
29798        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
29799        // borrow-invariant pin on the sibling `Option<String>` slot,
29800        // but extended onto the peer `Option<bool>` copy-invariant
29801        // shape — the accessor's returned `Option<bool>` must outlive
29802        // `&self` (multiple calls must return equal values from a
29803        // dropped-`&self` copy, since the returned Option carries no
29804        // borrow), and calling the accessor twice on the same
29805        // MeshPolicy must yield the same `Option<bool>` verbatim
29806        // (idempotent, no side effects on `&self`).
29807        //
29808        // Pins against a future silent detour that returned
29809        // `Option<&bool>` (which would type-check but silently break
29810        // every downstream caller — [`single_field_overlay`]'s first
29811        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
29812        // detached copy at the call site), an accidental
29813        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
29814        // would also type-check but return `Option<&bool>`), or a
29815        // one-arm-only accessor that reads `Some(*b)` in the Some arm
29816        // but reads a fresh Default::default() in the None arm.
29817        for required in [None, Some(true), Some(false)] {
29818            let p = MeshPolicy {
29819                mtls_required: required,
29820                ..MeshPolicy::default()
29821            };
29822            let first = p.mtls_required();
29823            let second = p.mtls_required();
29824            assert_eq!(
29825                first, second,
29826                "MeshPolicy::mtls_required must be idempotent — two \
29827                 successive calls on the same &self must return the \
29828                 same Option<bool>",
29829            );
29830            assert_eq!(
29831                first, required,
29832                "MeshPolicy::mtls_required must return :politicas \
29833                 :mtls-required verbatim by copy — got {first:?}, \
29834                 expected {required:?}",
29835            );
29836        }
29837    }
29838
29839    #[test]
29840    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
29841        // The canonical per-`:politicas` `:retries` transient-failure-
29842        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
29843        // the `:politicas :retries` typed `u32` verbatim as an
29844        // `Option<u32>`, byte-equal to the raw field access across every
29845        // representative value in the accept-set — `None` (cluster
29846        // default applies — typically "no retries beyond a single
29847        // dispatch attempt" the caixa-mesh `retry_overlay` builder
29848        // documents), `Some(1)` (the lower boundary of the
29849        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
29850        // `AplicacaoSpec::validate_politicas` gate carves out on the
29851        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
29852        // (the upper boundary the same gate carves out on the sibling
29853        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
29854        // past-the-guard sentinel that pins the accessor doesn't perform
29855        // a silent bounds-collapse at the return path).
29856        //
29857        // Sibling of the peer per-`:politicas`
29858        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
29859        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
29860        // peer per-`:politicas` `Option<u32>` shape — second
29861        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
29862        // Pins against a future silent detour that re-derived the retry
29863        // cap from a peer axis (an accidental `.circuit_breaker
29864        // .as_ref().map(|b| b.max_failures)` collapse that read the
29865        // breaker's max-failure count as a retry budget), a
29866        // `None → Some(0)` cluster-default projection (which would
29867        // silently re-introduce the `PolicyRetriesZero` refusal case at
29868        // the emit boundary), or a bounds-collapsing accessor that
29869        // clamped the return through `POLICY_RETRIES_MAX` (the
29870        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
29871        // must ship the raw slot verbatim so a validate-time gate
29872        // regression surfaces at the emit boundary rather than being
29873        // silently absorbed).
29874        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
29875            let p = MeshPolicy {
29876                retries,
29877                ..MeshPolicy::default()
29878            };
29879            assert_eq!(
29880                p.retries(),
29881                retries,
29882                "MeshPolicy::retries must return :politicas :retries \
29883                 verbatim (got {:?}, expected {retries:?})",
29884                p.retries(),
29885            );
29886            assert_eq!(
29887                p.retries(),
29888                p.retries,
29889                "MeshPolicy::retries must byte-equal the raw .retries \
29890                 field access across every value in the accept-set",
29891            );
29892        }
29893    }
29894
29895    #[test]
29896    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
29897        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
29898        // must key off [`MeshPolicy::retries`], not the raw `.retries`
29899        // field access. Structurally: toggling ONLY the `retries` slot
29900        // on an otherwise-default MeshPolicy must flip `is_empty()`
29901        // from `true` (all-`None`) to `false` (one axis carries a
29902        // value); the flip must be observed for every value in the
29903        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
29904        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
29905        // the emptiness semantic reads "any axis carries a value" —
29906        // not "any axis carries a value the validate gate accepts" —
29907        // the same non-collapsing shape the peer M2
29908        // [`crate::LimitsSpec::is_empty`] /
29909        // [`crate::BehaviorSpec::is_empty`] predicates carry.
29910        //
29911        // Pins against a future silent detour that re-derived the
29912        // emptiness predicate off a peer axis (an accidental
29913        // `.rate_limit.is_none()`-only chain that dropped the
29914        // `retries` arm entirely), a `retries == Some(_)` collapse
29915        // that key-off a validate-gate-clamped bounds check (which
29916        // would silently classify a past-the-guard `Some(u32::MAX)`
29917        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
29918        // check), or an accessor-side detour that no longer names the
29919        // substrate-primitive typed dispatch.
29920        //
29921        // Sibling of the peer per-`:politicas`
29922        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
29923        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
29924        // same "the emptiness predicate must route through the
29925        // substrate-primitive typed dispatch" discipline extended onto
29926        // the peer per-`:politicas` `Option<u32>` axis.
29927        let empty = MeshPolicy::default();
29928        assert!(
29929            empty.is_empty(),
29930            "MeshPolicy::default() must be is_empty() — every axis \
29931             defaults to None",
29932        );
29933        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
29934            let p = MeshPolicy {
29935                retries,
29936                ..MeshPolicy::default()
29937            };
29938            assert!(
29939                !p.is_empty(),
29940                "MeshPolicy::is_empty must return false when \
29941                 :retries is {retries:?} — the emptiness \
29942                 predicate reads \"any axis carries a value\", not \
29943                 \"any axis carries a value the validate gate \
29944                 accepts\"",
29945            );
29946            assert_eq!(
29947                p.retries().is_none(),
29948                p.is_empty(),
29949                "when :retries is the only set axis, is_empty() \
29950                 must equal retries().is_none() — the accessor and \
29951                 the emptiness predicate must route through the same \
29952                 substrate-primitive typed dispatch on the :retries \
29953                 arm",
29954            );
29955        }
29956    }
29957
29958    #[test]
29959    fn mesh_policy_retries_projects_option_u32_by_copy() {
29960        // The by-copy pin: [`MeshPolicy::retries`] returns
29961        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
29962        // accessor must return by value, not by reference. Sibling of
29963        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
29964        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
29965        // extended onto the sibling `Option<u32>` copy-invariant
29966        // shape — the accessor's returned `Option<u32>` must outlive
29967        // `&self` (multiple calls must return equal values from a
29968        // dropped-`&self` copy, since the returned Option carries no
29969        // borrow), and calling the accessor twice on the same
29970        // MeshPolicy must yield the same `Option<u32>` verbatim
29971        // (idempotent, no side effects on `&self`).
29972        //
29973        // Pins against a future silent detour that returned
29974        // `Option<&u32>` (which would type-check but silently break
29975        // every downstream caller — [`crate::render::single_field_overlay`]'s
29976        // first parameter is `Option<T: Clone>`, and `&u32` would
29977        // fold to a detached copy at the call site), an accidental
29978        // `Option::as_ref()` projection (`self.retries.as_ref()` would
29979        // also type-check but return `Option<&u32>`), or a one-arm-
29980        // only accessor that reads `Some(*n)` in the Some arm but
29981        // reads a fresh `Default::default()` (`0_u32`) in the None
29982        // arm.
29983        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
29984            let p = MeshPolicy {
29985                retries,
29986                ..MeshPolicy::default()
29987            };
29988            let first = p.retries();
29989            let second = p.retries();
29990            assert_eq!(
29991                first, second,
29992                "MeshPolicy::retries must be idempotent — two \
29993                 successive calls on the same &self must return the \
29994                 same Option<u32>",
29995            );
29996            assert_eq!(
29997                first, retries,
29998                "MeshPolicy::retries must return :politicas :retries \
29999                 verbatim by copy — got {first:?}, expected {retries:?}",
30000            );
30001        }
30002    }
30003
30004    #[test]
30005    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
30006        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
30007        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
30008        // return the `:politicas :timeout` typed [`Duration`] verbatim
30009        // as an `Option<Duration>`, byte-equal to the raw field access
30010        // across every representative value in the accept-set — `None`
30011        // (cluster default applies — typically the gateway class's
30012        // implementation-side per-request wall-clock cap the caixa-mesh
30013        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
30014        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
30015        // set the surrounding `AplicacaoSpec::validate_politicas` gate
30016        // carves out on the sibling `PolicyTimeoutZero` /
30017        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
30018        // (the upper boundary the same gate carves out on the sibling
30019        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
30020        // (a past-the-guard sentinel that pins the accessor doesn't
30021        // perform a silent bounds-collapse into `None` on the zero-
30022        // Duration arm — validate rejects zero but the accessor must
30023        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
30024        // past-the-guard sentinel that pins the accessor doesn't
30025        // perform a silent bounds-collapse at the return path).
30026        //
30027        // Sibling of the peer per-`:politicas`
30028        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
30029        // `Option<u32>` optional-scalar axis and the peer per-
30030        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
30031        // pin on the sibling `Option<bool>` optional-scalar axis,
30032        // extended onto the peer per-`:politicas` `Option<Duration>`
30033        // shape — third `Option<Copy-T>`-return accessor on the M3
30034        // mesh-slot family. Pins against a future silent detour that
30035        // re-derived the per-call cap from a peer axis (an accidental
30036        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
30037        // read the breaker's rolling-window duration as a per-call
30038        // deadline), a `None → Some(Duration::MAX)` cluster-default
30039        // projection (which would silently re-introduce the
30040        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
30041        // blocking" arm at the emit boundary), or a bounds-collapsing
30042        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
30043        // (the `AplicacaoSpec::validate` gate owns the bounds; the
30044        // accessor must ship the raw slot verbatim so a validate-time
30045        // gate regression surfaces at the emit boundary rather than
30046        // being silently absorbed).
30047        for timeout in [
30048            None,
30049            Some(Duration::from_millis(1)),
30050            Some(POLICY_TIMEOUT_MAX),
30051            Some(Duration::ZERO),
30052            Some(Duration::MAX),
30053        ] {
30054            let p = MeshPolicy {
30055                timeout,
30056                ..MeshPolicy::default()
30057            };
30058            assert_eq!(
30059                p.timeout(),
30060                timeout,
30061                "MeshPolicy::timeout must return :politicas :timeout \
30062                 verbatim (got {:?}, expected {timeout:?})",
30063                p.timeout(),
30064            );
30065            assert_eq!(
30066                p.timeout(),
30067                p.timeout,
30068                "MeshPolicy::timeout must byte-equal the raw .timeout \
30069                 field access across every value in the accept-set",
30070            );
30071        }
30072    }
30073
30074    #[test]
30075    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
30076        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
30077        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
30078        // field access. Structurally: toggling ONLY the `timeout` slot
30079        // on an otherwise-default MeshPolicy must flip `is_empty()`
30080        // from `true` (all-`None`) to `false` (one axis carries a
30081        // value); the flip must be observed for every value in the
30082        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
30083        // gate accepts (`Some(Duration::from_millis(1))`,
30084        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
30085        // reads "any axis carries a value" — not "any axis carries a
30086        // value the validate gate accepts" — the same non-collapsing
30087        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
30088        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30089        //
30090        // Pins against a future silent detour that re-derived the
30091        // emptiness predicate off a peer axis (an accidental
30092        // `.rate_limit.is_none()`-only chain that dropped the
30093        // `timeout` arm entirely), a `timeout == Some(_)` collapse
30094        // that key-off a validate-gate-clamped bounds check (which
30095        // would silently classify a past-the-guard `Some(Duration::MAX)`
30096        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
30097        // check), or an accessor-side detour that no longer names the
30098        // substrate-primitive typed dispatch.
30099        //
30100        // Sibling of the peer per-`:politicas`
30101        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
30102        // the sibling `Option<u32>` optional-scalar axis and the peer
30103        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
30104        // accessor-composition pin on the sibling `Option<bool>`
30105        // optional-scalar axis — same "the emptiness predicate must
30106        // route through the substrate-primitive typed dispatch"
30107        // discipline extended onto the peer per-`:politicas`
30108        // `Option<Duration>` axis.
30109        let empty = MeshPolicy::default();
30110        assert!(
30111            empty.is_empty(),
30112            "MeshPolicy::default() must be is_empty() — every axis \
30113             defaults to None",
30114        );
30115        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
30116            let p = MeshPolicy {
30117                timeout,
30118                ..MeshPolicy::default()
30119            };
30120            assert!(
30121                !p.is_empty(),
30122                "MeshPolicy::is_empty must return false when \
30123                 :timeout is {timeout:?} — the emptiness \
30124                 predicate reads \"any axis carries a value\", not \
30125                 \"any axis carries a value the validate gate \
30126                 accepts\"",
30127            );
30128            assert_eq!(
30129                p.timeout().is_none(),
30130                p.is_empty(),
30131                "when :timeout is the only set axis, is_empty() \
30132                 must equal timeout().is_none() — the accessor and \
30133                 the emptiness predicate must route through the same \
30134                 substrate-primitive typed dispatch on the :timeout \
30135                 arm",
30136            );
30137        }
30138    }
30139
30140    #[test]
30141    fn mesh_policy_timeout_projects_option_duration_by_copy() {
30142        // The by-copy pin: [`MeshPolicy::timeout`] returns
30143        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
30144        // and the accessor must return by value, not by reference.
30145        // Sibling of the peer per-`:politicas`
30146        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
30147        // sibling `Option<u32>` optional-scalar axis and the peer
30148        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
30149        // by-copy pin on the sibling `Option<bool>` optional-scalar
30150        // axis, extended onto the peer per-`:politicas`
30151        // `Option<Duration>` copy-invariant shape — the accessor's
30152        // returned `Option<Duration>` must outlive `&self` (multiple
30153        // calls must return equal values from a dropped-`&self`
30154        // copy, since the returned Option carries no borrow), and
30155        // calling the accessor twice on the same MeshPolicy must
30156        // yield the same `Option<Duration>` verbatim (idempotent, no
30157        // side effects on `&self`).
30158        //
30159        // Pins against a future silent detour that returned
30160        // `Option<&Duration>` (which would type-check but silently
30161        // break every downstream caller — [`crate::render::single_field_overlay`]'s
30162        // first parameter is `Option<T: Clone>`, and `&Duration`
30163        // would fold to a detached copy at the call site), an
30164        // accidental `Option::as_ref()` projection
30165        // (`self.timeout.as_ref()` would also type-check but return
30166        // `Option<&Duration>`), or a one-arm-only accessor that
30167        // reads `Some(*d)` in the Some arm but reads a fresh
30168        // `Default::default()` (`Duration::ZERO`) in the None arm
30169        // (which would silently re-classify every unset `:timeout`
30170        // as the `PolicyTimeoutZero`-refused zero-Duration value at
30171        // the accessor boundary).
30172        for timeout in [
30173            None,
30174            Some(Duration::from_millis(1)),
30175            Some(POLICY_TIMEOUT_MAX),
30176            Some(Duration::ZERO),
30177            Some(Duration::MAX),
30178        ] {
30179            let p = MeshPolicy {
30180                timeout,
30181                ..MeshPolicy::default()
30182            };
30183            let first = p.timeout();
30184            let second = p.timeout();
30185            assert_eq!(
30186                first, second,
30187                "MeshPolicy::timeout must be idempotent — two \
30188                 successive calls on the same &self must return the \
30189                 same Option<Duration>",
30190            );
30191            assert_eq!(
30192                first, timeout,
30193                "MeshPolicy::timeout must return :politicas :timeout \
30194                 verbatim by copy — got {first:?}, expected {timeout:?}",
30195            );
30196        }
30197    }
30198
30199    #[test]
30200    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
30201        // The canonical per-`:politicas` `:rate-limit` Envoy-
30202        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
30203        // [`MeshPolicy::rate_limit`] must return the `:politicas
30204        // :rate-limit` typed [`RateLimit`] verbatim as an
30205        // `Option<RateLimit>`, byte-equal to the raw field access
30206        // across every representative value in the accept-set — `None`
30207        // (cluster default applies — no per-Aplicacao rate declaration,
30208        // the gateway-class per-listener default arm the future caixa-
30209        // mesh `local_rate_limit_overlay` emitter documents),
30210        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
30211        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
30212        // accept-set the surrounding
30213        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
30214        // sibling `PolicyRateLimitZero` refusal, paired with the
30215        // canonical-window "1 second" arm of the three-unit
30216        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
30217        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
30218        // (the upper boundary the same gate carves out on the sibling
30219        // `PolicyRateLimitExceedsCap` refusal, paired with the
30220        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
30221        // (a past-the-guard sentinel that pins the accessor doesn't
30222        // perform a silent bounds-collapse into `None` on the
30223        // zero-rate/zero-window arm — validate rejects zero but the
30224        // accessor must ship the raw slot verbatim so a validate-time
30225        // gate regression surfaces at the emit boundary rather than
30226        // being silently absorbed), and
30227        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
30228        // (a past-the-guard sentinel that pins the accessor doesn't
30229        // perform a silent bounds-collapse at the return path).
30230        //
30231        // First `Option<Copy-composite-T>`-return accessor pin on the
30232        // M3 mesh-slot family (peer of the sibling per-`:politicas`
30233        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
30234        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
30235        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
30236        // Copy accessor pins, extended onto the peer per-`:politicas`
30237        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
30238        // and the accessor returns by value). Pins against a future
30239        // silent detour that re-derived the rate declaration from a
30240        // peer axis (an accidental
30241        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
30242        // collapse that read the breaker's trip threshold + rolling
30243        // window as a rate declaration), a `None → Some(default())`
30244        // cluster-default projection (which would silently re-
30245        // introduce a "cluster default is 0/s" arm the emit boundary
30246        // would take as "declared but inert" — the canonical
30247        // declared-but-inert footgun the sibling
30248        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
30249        // amplification-shape axis), a bounds-collapsing accessor
30250        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
30251        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
30252        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
30253        // accessor must ship the raw slot verbatim), or a
30254        // by-reference detour (`Option<&RateLimit>`) that broke every
30255        // downstream consumer keying off `Option<RateLimit>` by-copy.
30256        for rl in [
30257            None,
30258            Some(RateLimit {
30259                rate: 1,
30260                window: Duration::from_secs(1),
30261            }),
30262            Some(RateLimit {
30263                rate: POLICY_RATE_LIMIT_MAX,
30264                window: Duration::from_secs(3600),
30265            }),
30266            Some(RateLimit {
30267                rate: 0,
30268                window: Duration::ZERO,
30269            }),
30270            Some(RateLimit {
30271                rate: u32::MAX,
30272                window: Duration::MAX,
30273            }),
30274        ] {
30275            let p = MeshPolicy {
30276                rate_limit: rl,
30277                ..MeshPolicy::default()
30278            };
30279            assert_eq!(
30280                p.rate_limit(),
30281                rl,
30282                "MeshPolicy::rate_limit must return :politicas :rate-limit \
30283                 verbatim (got {:?}, expected {rl:?})",
30284                p.rate_limit(),
30285            );
30286            assert_eq!(
30287                p.rate_limit(),
30288                p.rate_limit,
30289                "MeshPolicy::rate_limit must byte-equal the raw \
30290                 .rate_limit field access across every value in the \
30291                 accept-set",
30292            );
30293        }
30294    }
30295
30296    #[test]
30297    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
30298        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
30299        // must key off [`MeshPolicy::rate_limit`], not the raw
30300        // `.rate_limit` field access. Structurally: toggling ONLY the
30301        // `rate_limit` slot on an otherwise-default MeshPolicy must
30302        // flip `is_empty()` from `true` (all-`None`) to `false` (one
30303        // axis carries a value); the flip must be observed for every
30304        // representative value in the accept-set the surrounding
30305        // [`AplicacaoSpec::validate_politicas`] gate accepts
30306        // (`Some(RateLimit { rate: 1, window: 1s })`,
30307        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
30308        // since the emptiness semantic reads "any axis carries a
30309        // value" — not "any axis carries a value the validate gate
30310        // accepts" — the same non-collapsing shape the peer M2
30311        // [`crate::LimitsSpec::is_empty`] /
30312        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30313        //
30314        // Pins against a future silent detour that re-derived the
30315        // emptiness predicate off a peer axis (an accidental
30316        // `.timeout.is_none()`-only chain that dropped the
30317        // `rate_limit` arm entirely — the last unlifted inline field
30318        // access on `is_empty` before this lift), a `rate_limit ==
30319        // Some(_)` collapse that key-off a validate-gate-clamped
30320        // bounds check (which would silently classify a past-the-
30321        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
30322        // because it fails the value-shape gate), or an accessor-
30323        // side detour that no longer names the substrate-primitive
30324        // typed dispatch.
30325        //
30326        // Fourth "the emptiness predicate must route through the
30327        // substrate-primitive typed dispatch" composition pin on the
30328        // M3 mesh-slot family — closes the last unlifted composition
30329        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
30330        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
30331        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
30332        // 7073d0f is_empty-composition pins on the sibling primitive-
30333        // Copy axes, extended onto the peer per-`:politicas`
30334        // composite-Copy `Option<RateLimit>` axis).
30335        let empty = MeshPolicy::default();
30336        assert!(
30337            empty.is_empty(),
30338            "MeshPolicy::default() must be is_empty() — every axis \
30339             defaults to None",
30340        );
30341        for rl in [
30342            RateLimit {
30343                rate: 1,
30344                window: Duration::from_secs(1),
30345            },
30346            RateLimit {
30347                rate: POLICY_RATE_LIMIT_MAX,
30348                window: Duration::from_secs(3600),
30349            },
30350        ] {
30351            let p = MeshPolicy {
30352                rate_limit: Some(rl),
30353                ..MeshPolicy::default()
30354            };
30355            assert!(
30356                !p.is_empty(),
30357                "MeshPolicy::is_empty must return false when \
30358                 :rate-limit is {rl:?} — the emptiness predicate \
30359                 reads \"any axis carries a value\", not \"any axis \
30360                 carries a value the validate gate accepts\"",
30361            );
30362            assert_eq!(
30363                p.rate_limit().is_none(),
30364                p.is_empty(),
30365                "when :rate-limit is the only set axis, is_empty() \
30366                 must equal rate_limit().is_none() — the accessor \
30367                 and the emptiness predicate must route through the \
30368                 same substrate-primitive typed dispatch on the \
30369                 :rate-limit arm",
30370            );
30371        }
30372    }
30373
30374    #[test]
30375    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
30376        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30377        // `:rate-limit` value-shape gate must key off
30378        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
30379        // field bind. Structurally: a `MeshPolicy` whose only set
30380        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
30381        // the `PolicyRateLimitZero` refusal exactly, and the same
30382        // MeshPolicy with the rate at the canonical lower boundary
30383        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
30384        // The pair jointly pins the accessor + validate-gate
30385        // composition: any future silent detour that had the accessor
30386        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
30387        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
30388        // silently absorb the `PolicyRateLimitZero` refusal at the
30389        // accessor boundary — the composition pin catches that at
30390        // caixa-core build time.
30391        //
30392        // Sibling of the peer [`validate_politicas`]
30393        // `:mtls-required` / `:retries` / `:timeout` composition pins
30394        // on the sibling primitive-Copy optional-scalar axes — same
30395        // "the validate / shape-gate predicate must route through the
30396        // substrate-primitive typed dispatch" discipline extended
30397        // onto the peer per-`:politicas` composite-Copy
30398        // `Option<RateLimit>` axis. Second composition-with-accessor
30399        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
30400        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
30401        let mut spec = three_member_spec();
30402        spec.politicas = MeshPolicy {
30403            rate_limit: Some(RateLimit {
30404                rate: 0,
30405                window: Duration::from_secs(1),
30406            }),
30407            ..MeshPolicy::default()
30408        };
30409        assert!(
30410            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
30411            "validate_politicas must reject rate == 0 with \
30412             PolicyRateLimitZero — the accessor and the validate gate \
30413             must route through the same substrate-primitive typed \
30414             dispatch on the :rate-limit zero-floor arm",
30415        );
30416        spec.politicas = MeshPolicy {
30417            rate_limit: Some(RateLimit {
30418                rate: 1,
30419                window: Duration::from_secs(1),
30420            }),
30421            ..MeshPolicy::default()
30422        };
30423        assert!(
30424            spec.validate().is_ok(),
30425            "validate_politicas must accept rate == 1 (the canonical \
30426             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
30427             set) with a canonical 1s window",
30428        );
30429    }
30430
30431    #[test]
30432    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
30433        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
30434        // `outlier_detection`-mesh consecutive-failure-ejection scalar
30435        // pin: [`MeshPolicy::circuit_breaker`] must return the
30436        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
30437        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
30438        // raw field access across every representative value in the
30439        // accept-set — `None` (cluster default applies — no
30440        // per-Aplicacao breaker declaration, the gateway-class per-
30441        // listener default arm the future caixa-mesh
30442        // `outlier_detection_overlay` emitter documents),
30443        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
30444        // (the lower boundary of the accept-set the surrounding
30445        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
30446        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
30447        // refusals),
30448        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
30449        // (the upper boundary the same gate carves out on the sibling
30450        // `PolicyBreakerMaxFailuresExceedsCap` /
30451        // `PolicyBreakerWindowExceedsCap` refusals),
30452        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
30453        // (a past-the-guard sentinel that pins the accessor doesn't
30454        // perform a silent bounds-collapse into `None` on the
30455        // zero-failures/zero-window arm — validate rejects zero but
30456        // the accessor must ship the raw slot verbatim so a validate-
30457        // time gate regression surfaces at the emit boundary rather
30458        // than being silently absorbed), and
30459        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
30460        // (a past-the-guard sentinel that pins the accessor doesn't
30461        // perform a silent bounds-collapse at the return path).
30462        //
30463        // Second `Option<Copy-composite-T>`-return accessor pin on the
30464        // M3 mesh-slot family (peer of the sibling per-`:politicas`
30465        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
30466        // composite-Copy accessor pin, and of the sibling per-
30467        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
30468        // [`MeshPolicy::retries`] bdfb399 /
30469        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
30470        // accessor pins). Pins against a future silent detour that
30471        // re-derived the breaker declaration from a peer axis (an
30472        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
30473        // collapse that read the rate-limit's bucket capacity + refill
30474        // period as a breaker declaration), a `None → Some(default())`
30475        // cluster-default projection (which would silently re-
30476        // introduce the `PolicyBreakerZeroFailures` /
30477        // `PolicyBreakerZeroWindow` refusal cases at the emit
30478        // boundary), a bounds-collapsing accessor that clamped
30479        // `cb.max_failures` through
30480        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
30481        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
30482        // [`AplicacaoSpec::validate`] gate owns the bounds; the
30483        // accessor must ship the raw slot verbatim), or a
30484        // by-reference detour (`Option<&CircuitBreaker>`) that broke
30485        // every downstream consumer keying off `Option<CircuitBreaker>`
30486        // by-copy.
30487        for cb in [
30488            None,
30489            Some(CircuitBreaker {
30490                max_failures: 1,
30491                window: Duration::from_millis(1),
30492            }),
30493            Some(CircuitBreaker {
30494                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
30495                window: POLICY_BREAKER_WINDOW_MAX,
30496            }),
30497            Some(CircuitBreaker {
30498                max_failures: 0,
30499                window: Duration::ZERO,
30500            }),
30501            Some(CircuitBreaker {
30502                max_failures: u32::MAX,
30503                window: Duration::MAX,
30504            }),
30505        ] {
30506            let p = MeshPolicy {
30507                circuit_breaker: cb,
30508                ..MeshPolicy::default()
30509            };
30510            assert_eq!(
30511                p.circuit_breaker(),
30512                cb,
30513                "MeshPolicy::circuit_breaker must return :politicas \
30514                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
30515                p.circuit_breaker(),
30516            );
30517            assert_eq!(
30518                p.circuit_breaker(),
30519                p.circuit_breaker,
30520                "MeshPolicy::circuit_breaker must byte-equal the raw \
30521                 .circuit_breaker field access across every value in \
30522                 the accept-set",
30523            );
30524        }
30525    }
30526
30527    #[test]
30528    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
30529        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
30530        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
30531        // `.circuit_breaker` field access. Structurally: toggling ONLY
30532        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
30533        // must flip `is_empty()` from `true` (all-`None`) to `false`
30534        // (one axis carries a value); the flip must be observed for
30535        // every representative value in the accept-set the surrounding
30536        // [`AplicacaoSpec::validate_politicas`] gate accepts
30537        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
30538        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
30539        // since the emptiness semantic reads "any axis carries a
30540        // value" — not "any axis carries a value the validate gate
30541        // accepts" — the same non-collapsing shape the peer M2
30542        // [`crate::LimitsSpec::is_empty`] /
30543        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30544        //
30545        // Pins against a future silent detour that re-derived the
30546        // emptiness predicate off a peer axis (an accidental
30547        // `.rate_limit.is_none()`-only chain that dropped the
30548        // `circuit_breaker` arm entirely — the last unlifted inline
30549        // field access on `is_empty` before this lift), a
30550        // `circuit_breaker == Some(_)` collapse that key-off a
30551        // validate-gate-clamped bounds check (which would silently
30552        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
30553        // 0, window: 0s })` as empty because it fails the value-shape
30554        // gate), or an accessor-side detour that no longer names the
30555        // substrate-primitive typed dispatch.
30556        //
30557        // Fifth "the emptiness predicate must route through the
30558        // substrate-primitive typed dispatch" composition pin on the
30559        // M3 mesh-slot family — closes the last unlifted composition
30560        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
30561        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
30562        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
30563        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
30564        // composition pins on the sibling primitive-Copy + composite-
30565        // Copy axes, extended onto the peer per-`:politicas`
30566        // composite-Copy `Option<CircuitBreaker>` axis).
30567        let empty = MeshPolicy::default();
30568        assert!(
30569            empty.is_empty(),
30570            "MeshPolicy::default() must be is_empty() — every axis \
30571             defaults to None",
30572        );
30573        for cb in [
30574            CircuitBreaker {
30575                max_failures: 1,
30576                window: Duration::from_millis(1),
30577            },
30578            CircuitBreaker {
30579                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
30580                window: POLICY_BREAKER_WINDOW_MAX,
30581            },
30582        ] {
30583            let p = MeshPolicy {
30584                circuit_breaker: Some(cb),
30585                ..MeshPolicy::default()
30586            };
30587            assert!(
30588                !p.is_empty(),
30589                "MeshPolicy::is_empty must return false when \
30590                 :circuit-breaker is {cb:?} — the emptiness predicate \
30591                 reads \"any axis carries a value\", not \"any axis \
30592                 carries a value the validate gate accepts\"",
30593            );
30594            assert_eq!(
30595                p.circuit_breaker().is_none(),
30596                p.is_empty(),
30597                "when :circuit-breaker is the only set axis, \
30598                 is_empty() must equal circuit_breaker().is_none() — \
30599                 the accessor and the emptiness predicate must route \
30600                 through the same substrate-primitive typed dispatch \
30601                 on the :circuit-breaker arm",
30602            );
30603        }
30604    }
30605
30606    #[test]
30607    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
30608        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30609        // `:circuit-breaker` value-shape gate must key off
30610        // [`MeshPolicy::circuit_breaker`], not the raw
30611        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
30612        // whose only set axis is a `Some(CircuitBreaker { max_failures:
30613        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
30614        // refusal exactly, and the same MeshPolicy with the breaker at
30615        // the canonical lower boundary
30616        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
30617        // pass validate. The pair jointly pins the accessor +
30618        // validate-gate composition: any future silent detour that had
30619        // the accessor omit the `Some(CircuitBreaker { max_failures:
30620        // 0, .. })` arm (a
30621        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
30622        // collapse) would silently absorb the
30623        // `PolicyBreakerZeroFailures` refusal at the accessor
30624        // boundary — the composition pin catches that at caixa-core
30625        // build time.
30626        //
30627        // Sibling of the peer [`validate_politicas`]
30628        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
30629        // composition pins on the sibling primitive-Copy + composite-
30630        // Copy optional-scalar axes — same "the validate / shape-gate
30631        // predicate must route through the substrate-primitive typed
30632        // dispatch" discipline extended onto the peer per-`:politicas`
30633        // composite-Copy `Option<CircuitBreaker>` axis. Second
30634        // composition-with-accessor pin on the M3 mesh-slot
30635        // `Option<CircuitBreaker>` arm alongside the
30636        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
30637        let mut spec = three_member_spec();
30638        spec.politicas = MeshPolicy {
30639            circuit_breaker: Some(CircuitBreaker {
30640                max_failures: 0,
30641                window: Duration::from_millis(1),
30642            }),
30643            ..MeshPolicy::default()
30644        };
30645        assert!(
30646            matches!(
30647                spec.validate(),
30648                Err(AplicacaoError::PolicyBreakerZeroFailures)
30649            ),
30650            "validate_politicas must reject max_failures == 0 with \
30651             PolicyBreakerZeroFailures — the accessor and the validate \
30652             gate must route through the same substrate-primitive \
30653             typed dispatch on the :circuit-breaker zero-floor arm",
30654        );
30655        spec.politicas = MeshPolicy {
30656            circuit_breaker: Some(CircuitBreaker {
30657                max_failures: 1,
30658                window: Duration::from_millis(1),
30659            }),
30660            ..MeshPolicy::default()
30661        };
30662        assert!(
30663            spec.validate().is_ok(),
30664            "validate_politicas must accept a CircuitBreaker at the \
30665             canonical lower boundary (max_failures = 1, window = \
30666             1ms) — the accessor and the validate gate must route \
30667             through the same substrate-primitive typed dispatch on \
30668             the :circuit-breaker arm",
30669        );
30670    }
30671
30672    #[test]
30673    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
30674        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
30675        // Envoy-outlier-detection trip-threshold scalar pin:
30676        // [`CircuitBreaker::max_failures`] must return the
30677        // `:politicas :circuit-breaker :max-failures` typed `u32`
30678        // verbatim, byte-equal to the raw field access across every
30679        // representative value in the accept-set — `1` (the lower
30680        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
30681        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
30682        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
30683        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
30684        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
30685        // refusal), `0` (a past-the-guard sentinel that pins the accessor
30686        // doesn't perform a silent bounds-collapse into `1` on the zero
30687        // arm — validate rejects zero but the accessor must ship the
30688        // raw slot verbatim so a validate-time gate regression surfaces
30689        // at the emit boundary rather than being silently absorbed),
30690        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
30691        // doesn't perform a silent bounds-collapse through
30692        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
30693        //
30694        // First sub-struct required-scalar accessor pin on the M3
30695        // mesh-slot family — sibling in shape to the peer per-`:membros`
30696        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
30697        // (a40b0e3) required-`String`-carry accessor pins and the peer
30698        // per-`:contratos` [`WitContract::source`] /
30699        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
30700        // accessor pins, extended onto the peer per-`CircuitBreaker`
30701        // required-`u32` scalar-value axis. Pins against a future silent
30702        // detour that re-derived the trip threshold from a peer axis (an
30703        // accidental `self.window.as_secs() as u32` collapse that read
30704        // the breaker's rolling-window duration as a failure count), a
30705        // `0 → 1` cluster-default projection (which would silently absorb
30706        // the `PolicyBreakerZeroFailures` refusal case at the accessor
30707        // boundary), or a bounds-collapsing accessor that clamped the
30708        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
30709        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30710        // must ship the raw slot verbatim).
30711        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
30712            let cb = CircuitBreaker {
30713                max_failures,
30714                window: Duration::from_secs(60),
30715            };
30716            assert_eq!(
30717                cb.max_failures(),
30718                max_failures,
30719                "CircuitBreaker::max_failures must return :politicas \
30720                 :circuit-breaker :max-failures verbatim (got {}, \
30721                 expected {max_failures})",
30722                cb.max_failures(),
30723            );
30724            assert_eq!(
30725                cb.max_failures(),
30726                cb.max_failures,
30727                "CircuitBreaker::max_failures must byte-equal the raw \
30728                 .max_failures field access across every value in the \
30729                 u32 accept-set",
30730            );
30731        }
30732    }
30733
30734    #[test]
30735    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
30736        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30737        // `:circuit-breaker :max-failures` zero-floor arm must key off
30738        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
30739        // field access. Structurally: a `CircuitBreaker { max_failures:
30740        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
30741        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
30742        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
30743        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
30744        // pass validate. The pair jointly pins the accessor +
30745        // validate-gate composition: any future silent detour that had
30746        // the accessor return a fresh `1` on the zero arm (a
30747        // `.max_failures().max(1)` collapse) would silently absorb the
30748        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
30749        // and the validate gate would accept a struct-literal
30750        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
30751        // catches that at caixa-core build time.
30752        //
30753        // Peer of the sibling per-`:politicas`
30754        // [`MeshPolicy::mtls_required`] (c0110f1) /
30755        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
30756        // (7073d0f) accessor-composition pins on the sibling optional-
30757        // scalar axes — same "the validate / shape-gate predicate must
30758        // route through the substrate-primitive typed dispatch"
30759        // discipline extended onto the peer per-`CircuitBreaker`
30760        // required-scalar composition axis.
30761        let mut spec = three_member_spec();
30762        spec.politicas = MeshPolicy {
30763            circuit_breaker: Some(CircuitBreaker {
30764                max_failures: 0,
30765                window: Duration::from_secs(60),
30766            }),
30767            ..MeshPolicy::default()
30768        };
30769        assert!(
30770            matches!(
30771                spec.validate(),
30772                Err(AplicacaoError::PolicyBreakerZeroFailures)
30773            ),
30774            "validate_politicas must reject max_failures == 0 with \
30775             PolicyBreakerZeroFailures — the accessor and the validate \
30776             gate must route through the same substrate-primitive typed \
30777             dispatch on the :max-failures zero-floor arm",
30778        );
30779        spec.politicas = MeshPolicy {
30780            circuit_breaker: Some(CircuitBreaker {
30781                max_failures: 1,
30782                window: Duration::from_secs(60),
30783            }),
30784            ..MeshPolicy::default()
30785        };
30786        assert!(
30787            spec.validate().is_ok(),
30788            "validate_politicas must accept max_failures == 1 (the \
30789             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
30790             accept-set)",
30791        );
30792    }
30793
30794    #[test]
30795    fn circuit_breaker_max_failures_projects_u32_by_copy() {
30796        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
30797        // `u32` by copy — `u32` is `Copy` and the accessor must return
30798        // by value, not by reference. Peer of the sibling
30799        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
30800        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
30801        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
30802        // optional-scalar axes, extended onto the peer
30803        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
30804        // the accessor's returned `u32` must outlive `&self` (multiple
30805        // calls must return equal values from a dropped-`&self` copy,
30806        // since the returned scalar carries no borrow), and calling
30807        // the accessor twice on the same CircuitBreaker must yield the
30808        // same `u32` verbatim (idempotent, no side effects on `&self`).
30809        //
30810        // Pins against a future silent detour that returned `&u32`
30811        // (which would type-check but silently break every downstream
30812        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
30813        // first parameter is `u32`, and `&u32` would fold to a detached
30814        // copy at the call site with a `*` deref the sibling accessors
30815        // don't need), an accidental `.max_failures.wrapping_add(0)`
30816        // detour that returned a fresh copy through an arithmetic
30817        // no-op (breaking a future `const fn` regression), or a
30818        // one-arm-only accessor that returned a saturating value on
30819        // some sentinel input (breaking the pass-through invariant the
30820        // sibling required-scalar accessors carry).
30821        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
30822            let cb = CircuitBreaker {
30823                max_failures,
30824                window: Duration::from_secs(60),
30825            };
30826            let first = cb.max_failures();
30827            let second = cb.max_failures();
30828            assert_eq!(
30829                first, second,
30830                "CircuitBreaker::max_failures must be idempotent — two \
30831                 successive calls on the same &self must return the \
30832                 same u32",
30833            );
30834            assert_eq!(
30835                first, max_failures,
30836                "CircuitBreaker::max_failures must return :politicas \
30837                 :circuit-breaker :max-failures verbatim by copy — \
30838                 got {first}, expected {max_failures}",
30839            );
30840        }
30841    }
30842
30843    #[test]
30844    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
30845        // The canonical per-`:politicas :circuit-breaker` `:window`
30846        // Envoy-outlier-detection rolling-observation-interval scalar
30847        // pin: [`CircuitBreaker::window`] must return the
30848        // `:politicas :circuit-breaker :window` typed `Duration`
30849        // verbatim, byte-equal to the raw field access across every
30850        // representative value in the accept-set — `Duration::from_millis(1)`
30851        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
30852        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
30853        // gate carves out on the sibling `PolicyBreakerZeroWindow`
30854        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
30855        // same gate carves out on the sibling
30856        // `PolicyBreakerWindowExceedsCap` refusal),
30857        // `Duration::ZERO` (a past-the-guard sentinel that pins the
30858        // accessor doesn't perform a silent bounds-collapse into
30859        // `Duration::from_millis(1)` on the zero arm — validate rejects
30860        // zero but the accessor must ship the raw slot verbatim so a
30861        // validate-time gate regression surfaces at the emit boundary
30862        // rather than being silently absorbed),
30863        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
30864        // far above the 1h cap — that pins the accessor doesn't perform
30865        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
30866        // at the return path).
30867        //
30868        // Second sub-struct required-scalar accessor pin on the M3
30869        // mesh-slot family — sibling in shape to the just-landed
30870        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
30871        // (3a74062) required-`u32` accessor pin on the peer
30872        // per-`CircuitBreaker` required-axis, extended onto the
30873        // per-sub-struct required-`Duration` axis. Pins against a
30874        // future silent detour that re-derived the observation window
30875        // from a peer axis (an accidental
30876        // `Duration::from_secs(self.max_failures as u64)` collapse that
30877        // read the breaker's trip count as an observation-interval
30878        // duration), a `Duration::ZERO → Duration::from_millis(1)`
30879        // cluster-default projection (which would silently absorb the
30880        // `PolicyBreakerZeroWindow` refusal case at the accessor
30881        // boundary), or a bounds-collapsing accessor that clamped the
30882        // return through `POLICY_BREAKER_WINDOW_MAX` (the
30883        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30884        // must ship the raw slot verbatim).
30885        for window in [
30886            Duration::from_millis(1),
30887            POLICY_BREAKER_WINDOW_MAX,
30888            Duration::ZERO,
30889            Duration::from_secs(86_400),
30890        ] {
30891            let cb = CircuitBreaker {
30892                max_failures: 5,
30893                window,
30894            };
30895            assert_eq!(
30896                cb.window(),
30897                window,
30898                "CircuitBreaker::window must return :politicas \
30899                 :circuit-breaker :window verbatim (got {:?}, \
30900                 expected {window:?})",
30901                cb.window(),
30902            );
30903            assert_eq!(
30904                cb.window(),
30905                cb.window,
30906                "CircuitBreaker::window must byte-equal the raw \
30907                 .window field access across every value in the \
30908                 Duration accept-set",
30909            );
30910        }
30911    }
30912
30913    #[test]
30914    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
30915        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30916        // `:circuit-breaker :window` zero-floor arm must key off
30917        // [`CircuitBreaker::window`], not the raw `.window` field
30918        // access. Structurally: a `CircuitBreaker { window:
30919        // Duration::ZERO, .. }` embedded in a
30920        // `:politicas :circuit-breaker` slot must surface the
30921        // `PolicyBreakerZeroWindow` refusal exactly, and a
30922        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
30923        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
30924        // accept-set) must pass validate. The pair jointly pins the
30925        // accessor + validate-gate composition: any future silent
30926        // detour that had the accessor return a fresh
30927        // `Duration::from_millis(1)` on the zero arm (a
30928        // `.window().max(Duration::from_millis(1))` collapse) would
30929        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
30930        // accessor boundary and the validate gate would accept a
30931        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
30932        // — the composition pin catches that at caixa-core build time.
30933        //
30934        // Peer of the sibling per-`CircuitBreaker`
30935        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
30936        // pin on the peer required-scalar `:max-failures` axis — same
30937        // "the validate / shape-gate predicate must route through the
30938        // substrate-primitive typed dispatch" discipline extended onto
30939        // the peer per-`CircuitBreaker` required-`Duration` composition
30940        // axis.
30941        let mut spec = three_member_spec();
30942        spec.politicas = MeshPolicy {
30943            circuit_breaker: Some(CircuitBreaker {
30944                max_failures: 5,
30945                window: Duration::ZERO,
30946            }),
30947            ..MeshPolicy::default()
30948        };
30949        assert!(
30950            matches!(
30951                spec.validate(),
30952                Err(AplicacaoError::PolicyBreakerZeroWindow)
30953            ),
30954            "validate_politicas must reject window == Duration::ZERO \
30955             with PolicyBreakerZeroWindow — the accessor and the \
30956             validate gate must route through the same substrate-\
30957             primitive typed dispatch on the :window zero-floor arm",
30958        );
30959        spec.politicas = MeshPolicy {
30960            circuit_breaker: Some(CircuitBreaker {
30961                max_failures: 5,
30962                window: Duration::from_millis(1),
30963            }),
30964            ..MeshPolicy::default()
30965        };
30966        assert!(
30967            spec.validate().is_ok(),
30968            "validate_politicas must accept window == \
30969             Duration::from_millis(1) (the lower boundary of the \
30970             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
30971        );
30972    }
30973
30974    #[test]
30975    fn circuit_breaker_window_projects_duration_by_copy() {
30976        // The by-copy pin: [`CircuitBreaker::window`] returns
30977        // `Duration` by copy — `Duration` is `Copy` and the accessor
30978        // must return by value, not by reference. Peer of the sibling
30979        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
30980        // (3a74062) by-copy pin on the peer required-scalar
30981        // `:max-failures` axis, extended onto the peer
30982        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
30983        // — the accessor's returned `Duration` must outlive `&self`
30984        // (multiple calls must return equal values from a
30985        // dropped-`&self` copy, since the returned scalar carries no
30986        // borrow), and calling the accessor twice on the same
30987        // CircuitBreaker must yield the same `Duration` verbatim
30988        // (idempotent, no side effects on `&self`).
30989        //
30990        // Pins against a future silent detour that returned
30991        // `&Duration` (which would type-check but silently break every
30992        // downstream `Duration`-by-value consumer —
30993        // [`crate::render::require_positive_canonical_bounded_duration`]'s
30994        // first parameter is `Duration`, and `&Duration` would fold to
30995        // a detached copy at the call site with a `*` deref the sibling
30996        // accessors don't need), an accidental `.window + Duration::ZERO`
30997        // detour that returned a fresh copy through an arithmetic
30998        // no-op (breaking a future `const fn` regression), or a
30999        // one-arm-only accessor that returned a saturating value on
31000        // some sentinel input (breaking the pass-through invariant the
31001        // sibling required-scalar accessors carry).
31002        for window in [
31003            Duration::from_millis(1),
31004            POLICY_BREAKER_WINDOW_MAX,
31005            Duration::ZERO,
31006            Duration::from_secs(86_400),
31007        ] {
31008            let cb = CircuitBreaker {
31009                max_failures: 5,
31010                window,
31011            };
31012            let first = cb.window();
31013            let second = cb.window();
31014            assert_eq!(
31015                first, second,
31016                "CircuitBreaker::window must be idempotent — two \
31017                 successive calls on the same &self must return the \
31018                 same Duration",
31019            );
31020            assert_eq!(
31021                first, window,
31022                "CircuitBreaker::window must return :politicas \
31023                 :circuit-breaker :window verbatim by copy — \
31024                 got {first:?}, expected {window:?}",
31025            );
31026        }
31027    }
31028
31029    #[test]
31030    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
31031        // Apex-identity pair-invariant pin composing both substrate-
31032        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
31033        // and [`WitContract::destination`] — at the emit-side call shape
31034        // every per-`(:de, :para)` CNP L4 port reader now takes. The
31035        // invariant, evaluated per-edge:
31036        //
31037        //   spec.port_for_destination(c.destination()) == expected_port
31038        //
31039        // where `expected_port` is `entrada.port` when
31040        // `c.destination() == entrada.destination()` and
31041        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
31042        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
31043        // pin on the per-`:entrada` axis — that pin encodes the apex
31044        // ingress L4 identity via `entrada.destination()`; this pin
31045        // encodes the per-edge L4 identity via `c.destination()`, and
31046        // both compose on the same substrate-primitive resolver so a
31047        // future refactor that silently split either accessor's apex
31048        // behavior surfaces at caixa-core build time.
31049        let mut spec = three_member_spec();
31050        if let Some(e) = spec.entrada.as_mut() {
31051            e.para = "cart".into();
31052            e.port = 8443;
31053        }
31054        let apex_contract = WitContract {
31055            de: "checkout".into(),
31056            para: "cart".into(),
31057            wit: "wasi:http/proxy".into(),
31058            endpoint: Some("/hello".into()),
31059            subject: None,
31060            slot: None,
31061        };
31062        assert_eq!(
31063            spec.port_for_destination(apex_contract.destination()),
31064            8443,
31065            "`spec.port_for_destination(c.destination())` must equal \
31066             `entrada.port` when the contract callee names the ingress \
31067             apex — the CNP per-edge L4 port and the HTTPRoute apex \
31068             backendRef port share this substrate-primitive resolver.",
31069        );
31070        let non_apex_contract = WitContract {
31071            de: "cart".into(),
31072            para: "payment".into(),
31073            wit: "wasi:http/proxy".into(),
31074            endpoint: Some("/charge".into()),
31075            subject: None,
31076            slot: None,
31077        };
31078        assert_eq!(
31079            spec.port_for_destination(non_apex_contract.destination()),
31080            DEFAULT_SERVICO_PORT,
31081            "`spec.port_for_destination(c.destination())` must fall back \
31082             to the substrate-canonical port floor when the contract \
31083             callee is not the ingress apex — the resolver's non-apex \
31084             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
31085        );
31086    }
31087
31088    #[test]
31089    fn membro_key_consts_are_lower_camel_case_shape() {
31090        // Shape-pin: every `MEMBRO_KEY_*` const must be a
31091        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31092        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31093        // leading capital, no whitespace / dots) — the canonical shape
31094        // the `#[serde(rename_all = "camelCase")]` derive produces on
31095        // [`Membro`]. A future flip to a non-camelCase attribute at
31096        // the derive surfaces both here (this test fails on the
31097        // stale-constant shape) and at
31098        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
31099        // fails on the mismatch between const and derive). Peer with
31100        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
31101        // on the sibling `SupervisorSpec` top-level axis.
31102        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
31103            assert!(
31104                !key.is_empty(),
31105                "MEMBRO_KEY_* must be non-empty (got {key:?})"
31106            );
31107            let first = key.chars().next().unwrap();
31108            assert!(
31109                first.is_ascii_lowercase(),
31110                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
31111                 (got {key:?}, leads with {first:?})",
31112            );
31113            assert!(
31114                key.chars().all(|c| c.is_ascii_alphanumeric()),
31115                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
31116                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31117            );
31118        }
31119    }
31120
31121    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
31122
31123    #[test]
31124    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
31125        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
31126        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
31127        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
31128        // keys the `#[serde(rename_all = "camelCase")]` attribute on
31129        // [`WitContract`] emits for the required-triad. The three
31130        // sibling payload-arm keys already pin under
31131        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
31132        // `STORE_FIELD_NAME` — pin all six alongside so a future
31133        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31134        // verbatim-field-name flip at the derive attribute (any of which
31135        // would silently break every downstream JSON consumer that
31136        // reaches for one of the six via `Value::get(...)`) surfaces
31137        // here as a build-time test failure at `aplicacao.rs`, not as an
31138        // apply-time `.get(<stale-canonical-const>)` returning `None`
31139        // far from the derive-attr drift's commit. Peer with the sibling
31140        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31141        // pin on the M3 `:membros` per-entry axis — same discipline the
31142        // `Membro` per-entry lift established, extended here to the
31143        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
31144        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
31145        // axis on the Aplicacao surface without a lifted serde-key peer.
31146        let c = WitContract {
31147            de: "cart".into(),
31148            para: "catalog".into(),
31149            wit: "wasi:http/proxy".into(),
31150            endpoint: Some("/lookup".into()),
31151            subject: None,
31152            slot: None,
31153        };
31154        let json = serde_json::to_string(&c).unwrap();
31155        for key in [
31156            crate::CONTRATO_KEY_DE,
31157            crate::CONTRATO_KEY_PARA,
31158            crate::CONTRATO_KEY_WIT,
31159            WitTarget::HTTP_FIELD_NAME,
31160        ] {
31161            let quoted = format!("\"{key}\"");
31162            assert!(
31163                json.contains(&quoted),
31164                "serialized WitContract must carry the lifted \
31165                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
31166                 {quoted} verbatim in the JSON emission (got: {json})",
31167            );
31168        }
31169
31170        // Pin the two remaining payload-arm keys by round-tripping a
31171        // `WitContract` under each payload-shape (pub-sub, store) — the
31172        // required-triad appears on every emission but the payload arms
31173        // only surface when their `Option<String>` field is `Some`.
31174        let pubsub = WitContract {
31175            de: "cart".into(),
31176            para: "events".into(),
31177            wit: "nats:pub-sub".into(),
31178            endpoint: None,
31179            subject: Some("orders.placed".into()),
31180            slot: None,
31181        };
31182        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
31183        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
31184        assert!(
31185            pubsub_json.contains(&pubsub_quoted),
31186            "serialized pub-sub WitContract must carry the lifted \
31187             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
31188             verbatim in the JSON emission (got: {pubsub_json})",
31189        );
31190        let store = WitContract {
31191            de: "cart".into(),
31192            para: "sessions".into(),
31193            wit: "wasi:keyvalue/store".into(),
31194            endpoint: None,
31195            subject: None,
31196            slot: Some("cart/$id".into()),
31197        };
31198        let store_json = serde_json::to_string(&store).unwrap();
31199        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
31200        assert!(
31201            store_json.contains(&store_quoted),
31202            "serialized store WitContract must carry the lifted \
31203             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
31204             verbatim in the JSON emission (got: {store_json})",
31205        );
31206    }
31207
31208    #[test]
31209    fn contrato_key_consts_are_pairwise_distinct() {
31210        // Cross-axis drift-detection pin: a future collapse of the six
31211        // canonical [`WitContract`] per-entry byte-strings onto the same
31212        // value (e.g. an accidental copy-paste flip of
31213        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
31214        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
31215        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
31216        // every downstream probe on one axis onto the sibling axis's
31217        // overlay entry and pass every propagation-probe test that
31218        // expected only the stale axis's value. Peer of the sibling
31219        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
31220        // widened here to the six-way axis the `WitContract`
31221        // required-triad + `WitTarget` payload-triad jointly cover.
31222        let all = [
31223            crate::CONTRATO_KEY_DE,
31224            crate::CONTRATO_KEY_PARA,
31225            crate::CONTRATO_KEY_WIT,
31226            WitTarget::HTTP_FIELD_NAME,
31227            WitTarget::PUBSUB_FIELD_NAME,
31228            WitTarget::STORE_FIELD_NAME,
31229        ];
31230        for (i, a) in all.iter().enumerate() {
31231            for b in all.iter().skip(i + 1) {
31232                assert_ne!(
31233                    a, b,
31234                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
31235                     must be pairwise-distinct canonical byte-sequences \
31236                     — got `{a}` == `{b}`",
31237                );
31238            }
31239        }
31240    }
31241
31242    #[test]
31243    fn contrato_key_consts_are_lower_camel_case_shape() {
31244        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
31245        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
31246        // byte-sequence (no `snake_case` underscores, no `kebab-case`
31247        // hyphens, no leading colon, no `PascalCase` leading capital, no
31248        // whitespace / dots) — the canonical shape the
31249        // `#[serde(rename_all = "camelCase")]` derive produces on
31250        // [`WitContract`]. A future flip to a non-camelCase attribute at
31251        // the derive surfaces both here (this test fails on the
31252        // stale-constant shape) and at
31253        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31254        // (that test fails on the mismatch between const and derive).
31255        // Peer with `membro_key_consts_are_lower_camel_case_shape`
31256        // (ce80ca0) on the sibling `Membro` per-entry axis.
31257        for key in [
31258            crate::CONTRATO_KEY_DE,
31259            crate::CONTRATO_KEY_PARA,
31260            crate::CONTRATO_KEY_WIT,
31261            WitTarget::HTTP_FIELD_NAME,
31262            WitTarget::PUBSUB_FIELD_NAME,
31263            WitTarget::STORE_FIELD_NAME,
31264        ] {
31265            assert!(
31266                !key.is_empty(),
31267                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
31268                 non-empty (got {key:?})"
31269            );
31270            let first = key.chars().next().unwrap();
31271            assert!(
31272                first.is_ascii_lowercase(),
31273                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
31274                 with an ASCII-lowercase byte (got {key:?}, leads with \
31275                 {first:?})",
31276            );
31277            assert!(
31278                key.chars().all(|c| c.is_ascii_alphanumeric()),
31279                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
31280                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
31281                 whitespace (got {key:?})",
31282            );
31283        }
31284    }
31285
31286    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
31287
31288    #[test]
31289    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
31290        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
31291        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
31292        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
31293        // name the exact camelCase JSON keys the
31294        // `#[serde(rename_all = "camelCase")]` attribute on
31295        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
31296        // pin that each canonical byte-sequence appears verbatim in the
31297        // JSON — a future accidental `rename_all = "snake_case"` /
31298        // `"kebab-case"` / verbatim-field-name flip at the derive
31299        // attribute (any of which would silently break every downstream
31300        // JSON consumer that reaches for one of the four consts via
31301        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
31302        // emitter's per-Aplicacao hostname/paths/port projection, the
31303        // future `app-operator` reconciler's per-Aplicacao ingress
31304        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
31305        // materializer's admission-time cross-check) surfaces here as
31306        // a build-time test failure at `aplicacao.rs`, not as an
31307        // apply-time `.get(<stale-canonical-const>)` returning `None`
31308        // far from the derive-attr drift's commit. Peer with the
31309        // sibling
31310        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31311        // (ca463a4) and
31312        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31313        // pins on the M3 collection-slot atom axes — same discipline
31314        // both collection-slot lifts established, extended here to the
31315        // singleton `:entrada` mesh-slot atom axis, the last M3
31316        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
31317        // axis on the Aplicacao surface without a lifted serde-key
31318        // peer.
31319        let e = Entrada {
31320            host: "checkout.quero.cloud".into(),
31321            para: "cart".into(),
31322            paths: vec!["/cart".into()],
31323            port: 8080,
31324        };
31325        let json = serde_json::to_string(&e).unwrap();
31326        for key in [
31327            crate::ENTRADA_KEY_HOST,
31328            crate::ENTRADA_KEY_PARA,
31329            crate::ENTRADA_KEY_PATHS,
31330            crate::ENTRADA_KEY_PORT,
31331        ] {
31332            let quoted = format!("\"{key}\"");
31333            assert!(
31334                json.contains(&quoted),
31335                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
31336                 byte-sequence {quoted} verbatim in the JSON emission \
31337                 (got: {json})",
31338            );
31339        }
31340    }
31341
31342    #[test]
31343    fn entrada_key_consts_are_pairwise_distinct() {
31344        // Cross-axis drift-detection pin: a future collapse of the four
31345        // canonical [`Entrada`] singleton byte-strings onto the same
31346        // value (e.g. an accidental copy-paste flip of
31347        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
31348        // silently reroute every downstream probe on one axis onto the
31349        // sibling axis's overlay entry and pass every propagation-probe
31350        // test that expected only the stale axis's value — the
31351        // Gateway/HTTPRoute emitter would read the hostname string
31352        // where the destination-Servico name was expected (or vice
31353        // versa), the admission-webhook cross-check would compare the
31354        // wrong pair of values, and the resulting Gateway resource
31355        // would either be admitted with garbage or rejected at the
31356        // controller far from the rebrand commit's source. Peer of the
31357        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
31358        // tetrad (40cc4e5), the two-way distinct pin on the
31359        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
31360        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
31361        // triad (ca463a4).
31362        let all = [
31363            crate::ENTRADA_KEY_HOST,
31364            crate::ENTRADA_KEY_PARA,
31365            crate::ENTRADA_KEY_PATHS,
31366            crate::ENTRADA_KEY_PORT,
31367        ];
31368        for (i, a) in all.iter().enumerate() {
31369            for b in all.iter().skip(i + 1) {
31370                assert_ne!(
31371                    a, b,
31372                    "ENTRADA_KEY_* consts must be pairwise-distinct \
31373                     canonical byte-sequences — got `{a}` == `{b}`",
31374                );
31375            }
31376        }
31377    }
31378
31379    #[test]
31380    fn entrada_key_consts_are_lower_camel_case_shape() {
31381        // Shape-pin: every `ENTRADA_KEY_*` const must be a
31382        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31383        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31384        // leading capital, no whitespace / dots) — the canonical shape
31385        // the `#[serde(rename_all = "camelCase")]` derive produces on
31386        // [`Entrada`]. A future flip to a non-camelCase attribute at
31387        // the derive surfaces both here (this test fails on the
31388        // stale-constant shape) and at
31389        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
31390        // test fails on the mismatch between const and derive). Peer
31391        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
31392        // and `contrato_key_consts_are_lower_camel_case_shape`
31393        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
31394        // entry axes.
31395        for key in [
31396            crate::ENTRADA_KEY_HOST,
31397            crate::ENTRADA_KEY_PARA,
31398            crate::ENTRADA_KEY_PATHS,
31399            crate::ENTRADA_KEY_PORT,
31400        ] {
31401            assert!(
31402                !key.is_empty(),
31403                "ENTRADA_KEY_* must be non-empty (got {key:?})"
31404            );
31405            let first = key.chars().next().unwrap();
31406            assert!(
31407                first.is_ascii_lowercase(),
31408                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
31409                 (got {key:?}, leads with {first:?})",
31410            );
31411            assert!(
31412                key.chars().all(|c| c.is_ascii_alphanumeric()),
31413                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
31414                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31415            );
31416        }
31417    }
31418
31419    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
31420
31421    #[test]
31422    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
31423        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
31424        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
31425        // [`crate::POLITICAS_KEY_RETRIES`] /
31426        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
31427        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
31428        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
31429        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
31430        // on [`MeshPolicy`] emits. Three of the five axes
31431        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
31432        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
31433        // camelCase transforms — the derive-attribute is load-bearing
31434        // on those, unlike the sibling `Entrada` / `Membro` /
31435        // `WitContract` structs whose fields are all lowercase-single-
31436        // word and where the derive is a no-op on every axis.
31437        // Serialize a fully-populated [`MeshPolicy`] (every axis
31438        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
31439        // on none of the five slots) and pin that each canonical
31440        // byte-sequence appears verbatim in the JSON — a future
31441        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31442        // verbatim-field-name flip at the derive attribute (any of
31443        // which would silently break every downstream JSON consumer
31444        // that reaches for one of the five consts via
31445        // `Value::get(...)` — the future M4 per-edge `:politicas`
31446        // overlay projection onto Cilium `L7Rules` and Gateway API
31447        // `HTTPRoute` backend timeouts, the future
31448        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31449        // admission-time mesh-policy cross-check, the future
31450        // `feira lint` per-`:politicas` bound-check gate) surfaces here
31451        // as a build-time test failure at `aplicacao.rs`, not as an
31452        // apply-time `.get(<stale-canonical-const>)` returning `None`
31453        // far from the derive-attr drift's commit. Peer with the
31454        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
31455        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31456        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
31457        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
31458        // atom axes — same discipline every M3 sibling lift
31459        // established, extended here to the singleton `:politicas`
31460        // mesh-slot atom axis, closing the last M3 typed-struct
31461        // top-level `#[serde(rename_all = "camelCase")]` axis on the
31462        // Aplicacao surface without a lifted serde-key peer.
31463        let p = MeshPolicy {
31464            timeout: Some(Duration::from_secs(30)),
31465            retries: Some(3),
31466            circuit_breaker: Some(CircuitBreaker {
31467                max_failures: 5,
31468                window: Duration::from_secs(60),
31469            }),
31470            mtls_required: Some(true),
31471            rate_limit: Some(RateLimit {
31472                rate: 100,
31473                window: Duration::from_secs(1),
31474            }),
31475        };
31476        let json = serde_json::to_string(&p).unwrap();
31477        for key in [
31478            crate::POLITICAS_KEY_TIMEOUT,
31479            crate::POLITICAS_KEY_RETRIES,
31480            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31481            crate::POLITICAS_KEY_MTLS_REQUIRED,
31482            crate::POLITICAS_KEY_RATE_LIMIT,
31483        ] {
31484            let quoted = format!("\"{key}\"");
31485            assert!(
31486                json.contains(&quoted),
31487                "serialized MeshPolicy must carry the lifted \
31488                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
31489                 JSON emission (got: {json})",
31490            );
31491        }
31492    }
31493
31494    #[test]
31495    fn politicas_key_consts_are_pairwise_distinct() {
31496        // Cross-axis drift-detection pin: a future collapse of the five
31497        // canonical [`MeshPolicy`] singleton byte-strings onto the same
31498        // value (e.g. an accidental copy-paste flip of
31499        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
31500        // would silently reroute every downstream probe on one axis
31501        // onto the sibling axis's overlay entry and pass every
31502        // propagation-probe test that expected only the stale axis's
31503        // value — the M4 per-edge `:politicas` overlay projection would
31504        // read the retry-count string where the timeout duration was
31505        // expected (or vice versa), the CR materializer's admission
31506        // cross-check would compare the wrong pair of values, and the
31507        // resulting mesh reconciler would either bind the wrong axis
31508        // or reject the resource at reconcile far from the rebrand
31509        // commit's source. Peer of the sibling four-way distinct pin
31510        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
31511        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
31512        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
31513        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
31514        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31515        let all = [
31516            crate::POLITICAS_KEY_TIMEOUT,
31517            crate::POLITICAS_KEY_RETRIES,
31518            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31519            crate::POLITICAS_KEY_MTLS_REQUIRED,
31520            crate::POLITICAS_KEY_RATE_LIMIT,
31521        ];
31522        for (i, a) in all.iter().enumerate() {
31523            for b in all.iter().skip(i + 1) {
31524                assert_ne!(
31525                    a, b,
31526                    "POLITICAS_KEY_* consts must be pairwise-distinct \
31527                     canonical byte-sequences — got `{a}` == `{b}`",
31528                );
31529            }
31530        }
31531    }
31532
31533    #[test]
31534    fn politicas_key_consts_are_lower_camel_case_shape() {
31535        // Shape-pin: every `POLITICAS_KEY_*` const must be a
31536        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31537        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31538        // leading capital, no whitespace / dots) — the canonical shape
31539        // the `#[serde(rename_all = "camelCase")]` derive produces on
31540        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
31541        // at the derive surfaces both here (this test fails on the
31542        // stale-constant shape) and at
31543        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31544        // (that test fails on the mismatch between const and derive).
31545        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
31546        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31547        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31548        // (ca463a4) on the sibling M3 typed-struct axes.
31549        for key in [
31550            crate::POLITICAS_KEY_TIMEOUT,
31551            crate::POLITICAS_KEY_RETRIES,
31552            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
31553            crate::POLITICAS_KEY_MTLS_REQUIRED,
31554            crate::POLITICAS_KEY_RATE_LIMIT,
31555        ] {
31556            assert!(
31557                !key.is_empty(),
31558                "POLITICAS_KEY_* must be non-empty (got {key:?})"
31559            );
31560            let first = key.chars().next().unwrap();
31561            assert!(
31562                first.is_ascii_lowercase(),
31563                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
31564                 byte (got {key:?}, leads with {first:?})",
31565            );
31566            assert!(
31567                key.chars().all(|c| c.is_ascii_alphanumeric()),
31568                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
31569                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31570            );
31571        }
31572    }
31573
31574    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
31575
31576    #[test]
31577    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
31578        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
31579        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
31580        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
31581        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
31582        // [`CircuitBreaker`] emits inside the
31583        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
31584        // two axes (`max_failures` → `maxFailures`) is a non-trivial
31585        // camelCase transform — the derive-attribute is load-bearing on
31586        // that axis, unlike the sibling `window` field where the derive
31587        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
31588        // pin that each canonical byte-sequence appears verbatim in the
31589        // JSON — a future accidental `rename_all = "snake_case"` /
31590        // `"kebab-case"` / verbatim-field-name flip at the derive
31591        // attribute (any of which would silently break every downstream
31592        // JSON consumer that reaches for one of the two consts via
31593        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
31594        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
31595        // per-edge `:politicas` overlay projection onto the mesh's
31596        // per-backend consecutive-failure-counter tripping threshold, the
31597        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31598        // admission-time breaker cross-check, the future `feira lint`
31599        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
31600        // here as a build-time test failure at `aplicacao.rs`, not as an
31601        // apply-time `.get(<stale-canonical-const>)` returning `None`
31602        // far from the derive-attr drift's commit. Peer with the sibling
31603        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31604        // (b55cca7) parent-axis pin — that test pins the outer
31605        // sub-block key the derive on [`MeshPolicy`] emits, this test
31606        // pins the inner keys the derive on the payload type emits, so
31607        // the two together lock the whole [`MeshPolicy`] breaker-tuning
31608        // shape end-to-end at build time.
31609        let cb = CircuitBreaker {
31610            max_failures: 5,
31611            window: Duration::from_secs(60),
31612        };
31613        let json = serde_json::to_string(&cb).unwrap();
31614        for key in [
31615            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31616            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31617        ] {
31618            let quoted = format!("\"{key}\"");
31619            assert!(
31620                json.contains(&quoted),
31621                "serialized CircuitBreaker must carry the lifted \
31622                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
31623                 in the JSON emission (got: {json})",
31624            );
31625        }
31626    }
31627
31628    #[test]
31629    fn circuit_breaker_key_consts_are_pairwise_distinct() {
31630        // Cross-axis drift-detection pin: a future collapse of the two
31631        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
31632        // same value (e.g. an accidental copy-paste flip of
31633        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
31634        // `"maxFailures"`) would silently reroute every downstream
31635        // probe on one axis onto the sibling axis's overlay entry and
31636        // pass every propagation-probe test that expected only the
31637        // stale axis's value — the M4 per-edge `:politicas` overlay
31638        // projection would read the failure-count where the window
31639        // duration was expected (or vice versa), the CR materializer's
31640        // admission cross-check would compare the wrong pair of values,
31641        // and the resulting mesh reconciler would either bind the wrong
31642        // axis or reject the resource at reconcile far from the rebrand
31643        // commit's source. Peer of the sibling five-way distinct pin on
31644        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
31645        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
31646        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
31647        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
31648        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31649        let all = [
31650            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31651            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31652        ];
31653        for (i, a) in all.iter().enumerate() {
31654            for b in all.iter().skip(i + 1) {
31655                assert_ne!(
31656                    a, b,
31657                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
31658                     canonical byte-sequences — got `{a}` == `{b}`",
31659                );
31660            }
31661        }
31662    }
31663
31664    #[test]
31665    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
31666        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
31667        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31668        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31669        // leading capital, no whitespace / dots) — the canonical shape
31670        // the `#[serde(rename_all = "camelCase")]` derive produces on
31671        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
31672        // at the derive surfaces both here (this test fails on the
31673        // stale-constant shape) and at
31674        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
31675        // (that test fails on the mismatch between const and derive).
31676        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
31677        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
31678        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31679        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31680        // (ca463a4) on the sibling M3 typed-struct axes.
31681        for key in [
31682            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
31683            crate::CIRCUIT_BREAKER_KEY_WINDOW,
31684        ] {
31685            assert!(
31686                !key.is_empty(),
31687                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
31688            );
31689            let first = key.chars().next().unwrap();
31690            assert!(
31691                first.is_ascii_lowercase(),
31692                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
31693                 byte (got {key:?}, leads with {first:?})",
31694            );
31695            assert!(
31696                key.chars().all(|c| c.is_ascii_alphanumeric()),
31697                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
31698                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31699            );
31700        }
31701    }
31702
31703    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
31704
31705    #[test]
31706    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
31707        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
31708        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
31709        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
31710        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
31711        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
31712        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
31713        // [`Placement`] emits. One of the four axes (`shard_key` →
31714        // `shardKey`) is a non-trivial camelCase transform — the
31715        // derive-attribute is load-bearing on that axis, unlike the
31716        // sibling `estrategia` / `clusters` / `affinity` axes whose
31717        // source-side field names carry no `_` and where the derive is a
31718        // no-op. Serialize a fully-populated [`Placement`] (both
31719        // `Option`-carrying axes `Some(_)` so
31720        // `skip_serializing_if = "Option::is_none"` fires on neither of
31721        // the two optional slots) and pin that each canonical
31722        // byte-sequence appears verbatim in the JSON — a future
31723        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31724        // verbatim-field-name flip at the derive attribute (any of which
31725        // would silently break every downstream consumer that reaches
31726        // for one of the four consts via
31727        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
31728        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
31729        // aggregator's per-cluster fanout filter keying off
31730        // `placement.clusters`, the M3 shard-pool dispatch materializer
31731        // keying off `placement.shardKey`, the M3 Adaptive compression
31732        // pass weighting off `placement.affinity`, every downstream
31733        // dispatcher branching on `placement.estrategia`, the future
31734        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31735        // admission-time placement cross-check, the future `feira lint`
31736        // per-`:placement` bound-check gate) surfaces here as a
31737        // build-time test failure at `aplicacao.rs`, not as an
31738        // apply-time `.get(<stale-canonical-const>)` returning `None`
31739        // far from the derive-attr drift's commit. Peer with the sibling
31740        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
31741        // (b55cca7),
31742        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
31743        // (468e959),
31744        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
31745        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31746        // (ca463a4), and
31747        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31748        // pins on the M3 collection-slot / singleton-slot atom axes —
31749        // closes the last M3 typed-struct top-level
31750        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
31751        // surface without a drift-detection pin.
31752        let p = Placement {
31753            estrategia: PlacementStrategy::Sharded,
31754            clusters: vec!["rio".into(), "mar".into()],
31755            affinity: Some("data-locality".into()),
31756            shard_key: Some("$tenantId".into()),
31757        };
31758        let json = serde_json::to_string(&p).unwrap();
31759        for key in [
31760            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31761            crate::M3_PLACEMENT_KEY_CLUSTERS,
31762            crate::M3_PLACEMENT_KEY_AFFINITY,
31763            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31764        ] {
31765            let quoted = format!("\"{key}\"");
31766            assert!(
31767                json.contains(&quoted),
31768                "serialized Placement must carry the lifted \
31769                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
31770                 the JSON emission (got: {json})",
31771            );
31772        }
31773    }
31774
31775    #[test]
31776    fn m3_placement_key_consts_are_pairwise_distinct() {
31777        // Cross-axis drift-detection pin: a future collapse of the four
31778        // canonical [`Placement`] sub-block byte-strings onto the same
31779        // value (e.g. an accidental copy-paste flip of
31780        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
31781        // `"affinity"`) would silently reroute every downstream probe on
31782        // one axis onto the sibling axis's overlay entry and pass every
31783        // propagation-probe test that expected only the stale axis's
31784        // value — the M3 shard-pool dispatch materializer would read the
31785        // affinity placement-hint where the shard-selection template was
31786        // expected (or vice versa), the M3 Adaptive compression pass's
31787        // cross-check would compare the wrong pair of values, and the
31788        // resulting placement engine would either bind the wrong axis or
31789        // reject the resource at reconcile far from the rebrand commit's
31790        // source. Peer of the sibling two-way distinct pin on the
31791        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
31792        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
31793        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
31794        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
31795        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
31796        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
31797        let all = [
31798            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31799            crate::M3_PLACEMENT_KEY_CLUSTERS,
31800            crate::M3_PLACEMENT_KEY_AFFINITY,
31801            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31802        ];
31803        for (i, a) in all.iter().enumerate() {
31804            for b in all.iter().skip(i + 1) {
31805                assert_ne!(
31806                    a, b,
31807                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
31808                     canonical byte-sequences — got `{a}` == `{b}`",
31809                );
31810            }
31811        }
31812    }
31813
31814    #[test]
31815    fn m3_placement_key_consts_are_lower_camel_case_shape() {
31816        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
31817        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31818        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31819        // leading capital, no whitespace / dots) — the canonical shape
31820        // the `#[serde(rename_all = "camelCase")]` derive produces on
31821        // [`Placement`]. A future flip to a non-camelCase attribute at
31822        // the derive surfaces both here (this test fails on the stale-
31823        // constant shape) and at
31824        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
31825        // (that test fails on the mismatch between const and derive).
31826        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
31827        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
31828        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
31829        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
31830        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
31831        // (ca463a4) on the sibling M3 typed-struct axes.
31832        for key in [
31833            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
31834            crate::M3_PLACEMENT_KEY_CLUSTERS,
31835            crate::M3_PLACEMENT_KEY_AFFINITY,
31836            crate::M3_PLACEMENT_KEY_SHARD_KEY,
31837        ] {
31838            assert!(
31839                !key.is_empty(),
31840                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
31841            );
31842            let first = key.chars().next().unwrap();
31843            assert!(
31844                first.is_ascii_lowercase(),
31845                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
31846                 byte (got {key:?}, leads with {first:?})",
31847            );
31848            assert!(
31849                key.chars().all(|c| c.is_ascii_alphanumeric()),
31850                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
31851                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31852            );
31853        }
31854    }
31855
31856    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
31857    //    destination-facing L4 port resolver every per-Aplicacao renderer
31858    //    reaching for a per-destination Servico TCP port axis routes
31859    //    through. The four pin tests below fix the four-way accept-set
31860    //    the resolver must always honor: (:entrada-para-matches,
31861    //    :entrada-para-mismatches, :entrada-none-so-fallback,
31862    //    :entrada-port-non-default-honored) — drift on any arm surfaces
31863    //    at caixa-core build time rather than at cluster-apply time.
31864
31865    #[test]
31866    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
31867        // The typed `:entrada` block's `:para "cart"` matches the
31868        // queried destination, so the resolver returns the author-
31869        // declared `:port` scalar verbatim — the canonical "the
31870        // destination Servico IS the ingress apex, honor the typed
31871        // listener port" arm of the port-resolution dispatch.
31872        let mut spec = three_member_spec();
31873        if let Some(e) = spec.entrada.as_mut() {
31874            e.para = "cart".into();
31875            e.port = 9090;
31876        }
31877        assert_eq!(
31878            spec.port_for_destination("cart"),
31879            9090,
31880            "port_for_destination(entrada.para) must return entrada.port \
31881             verbatim, not the DEFAULT_SERVICO_PORT fallback"
31882        );
31883    }
31884
31885    #[test]
31886    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
31887        // The typed `:entrada` block names `:para "cart"`, but the
31888        // queried destination is `"payment"` — a Servico that
31889        // participates in the mesh graph but is not the ingress apex.
31890        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
31891        // canonical port floor, closing the "non-apex destination reads
31892        // the substrate default" arm. Same fixture the peer
31893        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
31894        // pin at caixa-mesh exercises through the CNP emit-side path;
31895        // this pin exercises the shared underlying resolver directly.
31896        let spec = three_member_spec();
31897        assert_eq!(
31898            spec.port_for_destination("payment"),
31899            DEFAULT_SERVICO_PORT,
31900            "port_for_destination(non-apex-destination) must route \
31901             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
31902        );
31903    }
31904
31905    #[test]
31906    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
31907        // Internal-only Aplicacao — no `:entrada` block declared. Every
31908        // per-destination port query falls back to the lifted
31909        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
31910        // the Aplicacao surface admits `:entrada None` (internal mesh
31911        // with no external gateway); every downstream renderer's per-
31912        // destination port axis must still resolve to a well-defined
31913        // scalar even without an ingress apex.
31914        let mut spec = three_member_spec();
31915        spec.entrada = None;
31916        assert_eq!(
31917            spec.port_for_destination("cart"),
31918            DEFAULT_SERVICO_PORT,
31919            "port_for_destination on an internal-only Aplicacao must \
31920             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
31921             every destination"
31922        );
31923        assert_eq!(
31924            spec.port_for_destination("payment"),
31925            DEFAULT_SERVICO_PORT,
31926            "port_for_destination on an internal-only Aplicacao must \
31927             fall back uniformly across every destination — the fallback \
31928             is not entrada-shape-conditional"
31929        );
31930    }
31931
31932    #[test]
31933    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
31934        // Structural pin against a hypothetical future refactor that
31935        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
31936        // the resolver (a "normalize to the default when the author's
31937        // port matches the substrate default" collapse) — that would
31938        // break renderer sites that carry meaning on the emitted port
31939        // value beyond bare equality (a future per-cluster listener-
31940        // audit that keys off the author-declared port, not the
31941        // resolved-with-fallback port). Pin that a non-default
31942        // entrada.port is returned verbatim so drift here surfaces at
31943        // caixa-core build time.
31944        let mut spec = three_member_spec();
31945        if let Some(e) = spec.entrada.as_mut() {
31946            e.para = "cart".into();
31947            e.port = 8443;
31948        }
31949        assert_ne!(
31950            8443, DEFAULT_SERVICO_PORT,
31951            "test fixture must probe a port distinct from \
31952             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
31953        );
31954        assert_eq!(
31955            spec.port_for_destination("cart"),
31956            8443,
31957            "port_for_destination(entrada.para) must return entrada.port \
31958             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
31959        );
31960    }
31961
31962    #[test]
31963    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
31964        // Apex-identity pair-invariant pin composing both substrate-
31965        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
31966        // and [`Entrada::destination`] — at the emit-side call shape
31967        // every per-Aplicacao renderer's ingress-apex L4 port reader
31968        // now takes. The invariant:
31969        //
31970        //   spec.port_for_destination(entrada.destination()) == entrada.port
31971        //
31972        // holds by construction under today's single-destination
31973        // `:entrada` slot (`destination()` returns `entrada.para`, and
31974        // the resolver's apex arm matches `para == destination` and
31975        // returns `entrada.port`), and every downstream consumer that
31976        // composes the two accessors at the ingress apex — the
31977        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
31978        // `backendRefs[0].port` emit-site path, the peer future M4 CR
31979        // materializer's admission-webhook that promotes the scalar to
31980        // a per-CR override overlay, every future per-Aplicacao snapshot
31981        // renderer's apex-facing L4 port reader — reaches through the
31982        // same composition. Pin the identity across four permutations
31983        // (`:para` × `:port` including a non-default port to exercise
31984        // the honor-verbatim arm and a non-cart `:para` to exercise
31985        // destination-agnostic identity) so a future refactor that
31986        // silently split either accessor's apex behavior surfaces at
31987        // caixa-core build time — a subtle `destination()` renaming
31988        // that returned `entrada.host.as_str()` instead of
31989        // `entrada.para.as_str()` would blow this pin loudly, closing
31990        // the last quiet failure mode the two lifts admit in composition.
31991        //
31992        // Peer discipline with the sibling caixa-mesh cross-crate pin
31993        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
31994        // on the two-renderer pair-invariant axis; this pin encodes the
31995        // same two-consumer coherence rule at the substrate-primitive
31996        // level so the invariant survives even if every renderer is
31997        // deleted.
31998        for (para, port) in [
31999            ("cart", DEFAULT_SERVICO_PORT),
32000            ("cart", 8443u16),
32001            ("payment", 9090u16),
32002            ("catalog", 443u16),
32003        ] {
32004            let mut spec = three_member_spec();
32005            if let Some(e) = spec.entrada.as_mut() {
32006                e.para = para.into();
32007                e.port = port;
32008            }
32009            let expected_port = spec
32010                .entrada()
32011                .expect("three_member_spec carries a typed `:entrada` block")
32012                .port();
32013            let composed_port = {
32014                let entrada = spec.entrada().expect("entrada present");
32015                spec.port_for_destination(entrada.destination())
32016            };
32017            assert_eq!(
32018                composed_port, expected_port,
32019                "`spec.port_for_destination(entrada.destination())` must \
32020                 equal `entrada.port` under today's single-destination \
32021                 `:entrada` slot — this is the apex-identity contract \
32022                 every downstream ingress-apex L4 port reader relies on. \
32023                 Input :entrada :para: {para:?}, :entrada :port: {port}"
32024            );
32025        }
32026    }
32027
32028    #[test]
32029    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
32030        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
32031        // per-`:entrada` apex-arm membership probe must key off
32032        // [`Entrada::destination`], not the raw `.para` field access.
32033        // Structurally: setting ONLY the `:entrada :para` field to a
32034        // fresh non-cart destination on an otherwise-well-formed
32035        // Aplicacao must (1) leave `e.destination()` byte-equal to
32036        // `e.para.as_str()` (the accessor is byte-projective by
32037        // definition), and (2) cause the resolver's apex arm to fire
32038        // and return `entrada.port` at exactly that new destination
32039        // while every other destination string falls through to
32040        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
32041        // membership check. Pins against a future silent detour that
32042        // (a) re-derived the apex-arm membership probe off
32043        // `e.para == destination` in `port_for_destination` instead of
32044        // `e.destination() == destination`, silently disagreeing with
32045        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
32046        // consumers (`entrada.destination()` at
32047        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
32048        // caixa-mesh/src/lib.rs:2739) that already reach through the
32049        // accessor, (b) accessor-side introduced a per-tenant alias
32050        // arm the caller was unaware of, silently rewriting an
32051        // author-declared `:para "cart"` value to a canary-aliased
32052        // form — the raw-field-access resolver would fall through to
32053        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
32054        // while the peer emit-site consumers landed on the aliased
32055        // destination, splitting the ingress-apex L4 port at
32056        // cluster-apply time.
32057        //
32058        // Peer of the sibling
32059        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
32060        // (d0de220) composition pin on the per-`:membros` refusal-arm
32061        // axis — same "the shape-gate predicate must route through the
32062        // substrate-primitive typed dispatch" discipline extended onto
32063        // the per-`:entrada` apex-arm membership-probe axis. Closes
32064        // the last unlifted `.para` production-code read site on
32065        // `Entrada` in `caixa-core` — after this converge every
32066        // `caixa-core` `.para` field access outside the accessor's own
32067        // body and outside the `WitContract` per-`:contratos` sibling
32068        // axis is either a test-side field-setter or a doc-comment
32069        // reference.
32070        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
32071            let mut spec = three_member_spec();
32072            if let Some(e) = spec.entrada.as_mut() {
32073                e.para = para.into();
32074                e.port = port;
32075            }
32076            let e = spec
32077                .entrada
32078                .as_ref()
32079                .expect("three_member_spec carries a typed `:entrada` block");
32080            assert_eq!(
32081                e.destination(),
32082                e.para.as_str(),
32083                "Entrada::destination must byte-equal the .para field \
32084                 access — an accessor-side detour that no longer \
32085                 projects the raw field would silently split this \
32086                 drift-detection test from the port_for_destination \
32087                 apex-arm membership probe",
32088            );
32089            assert_eq!(
32090                spec.port_for_destination(para),
32091                port,
32092                "port_for_destination must key off the accessor-projected \
32093                 destination and return `entrada.port` on the apex arm — \
32094                 input :entrada :para: {para:?}, :entrada :port: {port}",
32095            );
32096            assert_eq!(
32097                spec.port_for_destination("ghost-destination-never-a-member"),
32098                DEFAULT_SERVICO_PORT,
32099                "port_for_destination must fall through to \
32100                 DEFAULT_SERVICO_PORT on a non-matching destination \
32101                 under the accessor-projected membership check — input \
32102                 :entrada :para: {para:?}, :entrada :port: {port}",
32103            );
32104        }
32105    }
32106
32107    #[test]
32108    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
32109        // The canonical per-`:politicas :rate-limit` `:rate`
32110        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
32111        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
32112        // typed `u32` verbatim, byte-equal to the raw field access
32113        // across every representative value in the accept-set — `1` (the
32114        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
32115        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
32116        // carves out on the sibling `PolicyRateLimitZero` refusal),
32117        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
32118        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
32119        // `0` (a past-the-guard sentinel that pins the accessor doesn't
32120        // perform a silent bounds-collapse into `1` on the zero arm —
32121        // validate rejects zero but the accessor must ship the raw slot
32122        // verbatim so a validate-time gate regression surfaces at the
32123        // emit boundary rather than being silently absorbed), `u32::MAX`
32124        // (a past-the-guard sentinel that pins the accessor doesn't
32125        // perform a silent bounds-collapse through
32126        // `POLICY_RATE_LIMIT_MAX` at the return path).
32127        //
32128        // First sub-struct required-scalar accessor pin on the
32129        // `RateLimit` axis — sibling in shape to the peer
32130        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
32131        // required-`u32` accessor pin on the peer per-sub-struct
32132        // required-axis. Pins against a future silent detour that
32133        // re-derived the token capacity from a peer axis (an accidental
32134        // `self.window.as_secs() as u32` collapse that read the
32135        // rate-limit window duration as a token count), a `0 → 1`
32136        // cluster-default projection (which would silently absorb the
32137        // `PolicyRateLimitZero` refusal case at the accessor boundary),
32138        // or a bounds-collapsing accessor that clamped the return
32139        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
32140        // gate owns the bounds; the accessor must ship the raw slot
32141        // verbatim).
32142        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
32143            let rl = RateLimit {
32144                rate,
32145                window: Duration::from_secs(1),
32146            };
32147            assert_eq!(
32148                rl.rate(),
32149                rate,
32150                "RateLimit::rate must return :politicas :rate-limit :rate \
32151                 verbatim (got {}, expected {rate})",
32152                rl.rate(),
32153            );
32154            assert_eq!(
32155                rl.rate(),
32156                rl.rate,
32157                "RateLimit::rate must byte-equal the raw .rate field \
32158                 access across every value in the u32 accept-set",
32159            );
32160        }
32161    }
32162
32163    #[test]
32164    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
32165        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32166        // `:rate-limit :rate` zero-floor arm must key off
32167        // [`RateLimit::rate`], not the raw `.rate` field access.
32168        // Structurally: a `RateLimit { rate: 0, window:
32169        // Duration::from_secs(1) }` embedded in a `:politicas
32170        // :rate-limit` slot must surface the `PolicyRateLimitZero`
32171        // refusal exactly, and a `RateLimit { rate: 1, window:
32172        // Duration::from_secs(1) }` (the lower boundary of the
32173        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
32174        // The pair jointly pins the accessor + validate-gate composition:
32175        // any future silent detour that had the accessor return a fresh
32176        // `1` on the zero arm (a `.rate().max(1)` collapse) would
32177        // silently absorb the `PolicyRateLimitZero` refusal at the
32178        // accessor boundary and the validate gate would accept a
32179        // struct-literal `RateLimit { rate: 0, .. }` — the composition
32180        // pin catches that at caixa-core build time.
32181        //
32182        // Peer of the sibling per-`CircuitBreaker`
32183        // [`CircuitBreaker::max_failures`] (3a74062) /
32184        // [`CircuitBreaker::window`] (373957f) accessor-composition
32185        // pins on the peer required-scalar axes — same "the validate /
32186        // shape-gate predicate must route through the substrate-primitive
32187        // typed dispatch" discipline extended onto the peer
32188        // per-`RateLimit` required-`u32` composition axis.
32189        let mut spec = three_member_spec();
32190        spec.politicas = MeshPolicy {
32191            rate_limit: Some(RateLimit {
32192                rate: 0,
32193                window: Duration::from_secs(1),
32194            }),
32195            ..MeshPolicy::default()
32196        };
32197        assert!(
32198            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
32199            "validate_politicas must reject rate == 0 with \
32200             PolicyRateLimitZero — the accessor and the validate gate \
32201             must route through the same substrate-primitive typed \
32202             dispatch on the :rate zero-floor arm",
32203        );
32204        spec.politicas = MeshPolicy {
32205            rate_limit: Some(RateLimit {
32206                rate: 1,
32207                window: Duration::from_secs(1),
32208            }),
32209            ..MeshPolicy::default()
32210        };
32211        assert!(
32212            spec.validate().is_ok(),
32213            "validate_politicas must accept rate == 1 (the lower \
32214             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
32215        );
32216    }
32217
32218    #[test]
32219    fn rate_limit_rate_projects_u32_by_copy() {
32220        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
32221        // `u32` is `Copy` and the accessor must return by value, not by
32222        // reference. Peer of the sibling per-`CircuitBreaker`
32223        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
32224        // peer required-scalar `:max-failures` axis, extended onto the
32225        // peer per-`RateLimit` required-`u32` copy-invariant shape —
32226        // the accessor's returned `u32` must outlive `&self` (multiple
32227        // calls must return equal values from a dropped-`&self` copy,
32228        // since the returned scalar carries no borrow), and calling the
32229        // accessor twice on the same RateLimit must yield the same
32230        // `u32` verbatim (idempotent, no side effects on `&self`).
32231        //
32232        // Pins against a future silent detour that returned `&u32`
32233        // (which would type-check but silently break every downstream
32234        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
32235        // first parameter is `u32`, and `&u32` would fold to a detached
32236        // copy at the call site with a `*` deref the sibling accessors
32237        // don't need), an accidental `.rate.wrapping_add(0)` detour that
32238        // returned a fresh copy through an arithmetic no-op (breaking a
32239        // future `const fn` regression), or a one-arm-only accessor
32240        // that returned a saturating value on some sentinel input
32241        // (breaking the pass-through invariant the sibling required-
32242        // scalar accessors carry).
32243        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
32244            let rl = RateLimit {
32245                rate,
32246                window: Duration::from_secs(1),
32247            };
32248            let first = rl.rate();
32249            let second = rl.rate();
32250            assert_eq!(
32251                first, second,
32252                "RateLimit::rate must be idempotent — two successive \
32253                 calls on the same &self must return the same u32",
32254            );
32255            assert_eq!(
32256                first, rate,
32257                "RateLimit::rate must return :politicas :rate-limit :rate \
32258                 verbatim by copy — got {first}, expected {rate}",
32259            );
32260        }
32261    }
32262
32263    #[test]
32264    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
32265        // The canonical per-`:politicas :rate-limit` `:window`
32266        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
32267        // pin: [`RateLimit::window`] must return the
32268        // `:politicas :rate-limit :window` typed `Duration` verbatim,
32269        // byte-equal to the raw field access across every
32270        // representative value in the accept-set — `Duration::from_secs(1)`
32271        // (the `"s"` canonical window, the lower row of
32272        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
32273        // [`AplicacaoSpec::validate_politicas`] gate accepts via
32274        // [`is_canonical_rate_limit_window`]),
32275        // `Duration::from_secs(60)` (the `"m"` canonical window, the
32276        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
32277        // window, the upper row), `Duration::ZERO` (a past-the-guard
32278        // sentinel that pins the accessor doesn't perform a silent
32279        // bounds-collapse into `Duration::from_secs(1)` on the zero
32280        // arm — validate rejects an off-set window through
32281        // `PolicyRateLimitWindowNotCanonical` but the accessor must
32282        // ship the raw slot verbatim so a validate-time gate
32283        // regression surfaces at the emit boundary rather than being
32284        // silently absorbed), `Duration::from_millis(500)` (a
32285        // sub-canonical past-the-guard sentinel that pins the accessor
32286        // doesn't silently normalize a non-canonical fractional
32287        // magnitude onto the nearest canonical row).
32288        //
32289        // Second sub-struct required-scalar accessor pin on the
32290        // `RateLimit` axis — sibling in shape to the just-landed
32291        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
32292        // accessor pin on the peer per-sub-struct required-axis,
32293        // extended onto the per-`RateLimit` required-`Duration` axis.
32294        // Pins against a future silent detour that re-derived the
32295        // refill period from a peer axis (an accidental
32296        // `Duration::from_secs(self.rate as u64)` collapse that read
32297        // the rate-limit token capacity as a refill-interval
32298        // duration), a `Duration::ZERO → Duration::from_secs(1)`
32299        // canonical-default projection (which would silently absorb
32300        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
32301        // accessor boundary), or a canonical-set-collapsing accessor
32302        // that clamped the return through [`rate_limit_window_unit`]
32303        // (the `AplicacaoSpec::validate` gate owns the canonical-set
32304        // membership; the accessor must ship the raw slot verbatim).
32305        for window in [
32306            Duration::from_secs(1),
32307            Duration::from_secs(60),
32308            Duration::from_secs(3600),
32309            Duration::ZERO,
32310            Duration::from_millis(500),
32311        ] {
32312            let rl = RateLimit { rate: 100, window };
32313            assert_eq!(
32314                rl.window(),
32315                window,
32316                "RateLimit::window must return :politicas :rate-limit :window \
32317                 verbatim (got {:?}, expected {window:?})",
32318                rl.window(),
32319            );
32320            assert_eq!(
32321                rl.window(),
32322                rl.window,
32323                "RateLimit::window must byte-equal the raw .window field \
32324                 access across every value in the Duration accept-set",
32325            );
32326        }
32327    }
32328
32329    #[test]
32330    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
32331        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32332        // `:rate-limit :window` canonical-set arm must key off
32333        // [`RateLimit::window`], not the raw `.window` field access.
32334        // Structurally: a `RateLimit { window: Duration::from_millis(500),
32335        // .. }` embedded in a `:politicas :rate-limit` slot must
32336        // surface the `PolicyRateLimitWindowNotCanonical` refusal
32337        // exactly (with the sub-canonical `Duration::from_millis(500)`
32338        // magnitude carried through verbatim), and a `RateLimit
32339        // { window: Duration::from_secs(1), .. }` (the lower row of
32340        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
32341        // The pair jointly pins the accessor + validate-gate
32342        // composition: any future silent detour that had the accessor
32343        // normalize the off-set window to the nearest canonical row
32344        // (a `.window().max(Duration::from_secs(1))` collapse, or a
32345        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
32346        // collapse) would silently absorb the
32347        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
32348        // boundary — including a drift in the error's `window` payload
32349        // (the emit-side diagnostic reader keys off the offending
32350        // magnitude verbatim, so a normalization at the accessor
32351        // boundary would silently pin the wrong magnitude in the
32352        // refusal). The composition pin catches that at caixa-core
32353        // build time.
32354        //
32355        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
32356        // (7f81a60) accessor-composition pin on the peer required-
32357        // scalar `:rate` axis — same "the validate / shape-gate
32358        // predicate must route through the substrate-primitive typed
32359        // dispatch, and the error payload must project through the
32360        // same accessor" discipline extended onto the peer
32361        // per-`RateLimit` required-`Duration` composition axis.
32362        let mut spec = three_member_spec();
32363        spec.politicas = MeshPolicy {
32364            rate_limit: Some(RateLimit {
32365                rate: 100,
32366                window: Duration::from_millis(500),
32367            }),
32368            ..MeshPolicy::default()
32369        };
32370        match spec.validate() {
32371            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
32372                assert_eq!(
32373                    window,
32374                    Duration::from_millis(500),
32375                    "PolicyRateLimitWindowNotCanonical must carry the \
32376                     offending :window magnitude verbatim through the \
32377                     accessor — got {window:?}, expected 500ms",
32378                );
32379            }
32380            other => panic!(
32381                "validate_politicas must reject non-canonical :window \
32382                 with PolicyRateLimitWindowNotCanonical — the accessor \
32383                 and the validate gate must route through the same \
32384                 substrate-primitive typed dispatch on the :window \
32385                 canonical-set arm; got {other:?}",
32386            ),
32387        }
32388        spec.politicas = MeshPolicy {
32389            rate_limit: Some(RateLimit {
32390                rate: 100,
32391                window: Duration::from_secs(1),
32392            }),
32393            ..MeshPolicy::default()
32394        };
32395        assert!(
32396            spec.validate().is_ok(),
32397            "validate_politicas must accept window == Duration::from_secs(1) \
32398             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
32399        );
32400    }
32401
32402    #[test]
32403    fn rate_limit_window_projects_duration_by_copy() {
32404        // The by-copy pin: [`RateLimit::window`] returns `Duration`
32405        // by copy — `Duration` is `Copy` and the accessor must return
32406        // by value, not by reference. Peer of the sibling per-`RateLimit`
32407        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
32408        // required-scalar `:rate` axis, extended onto the peer
32409        // per-`RateLimit` required-`Duration` copy-invariant shape —
32410        // the accessor's returned `Duration` must outlive `&self`
32411        // (multiple calls must return equal values from a
32412        // dropped-`&self` copy, since the returned scalar carries no
32413        // borrow), and calling the accessor twice on the same
32414        // RateLimit must yield the same `Duration` verbatim
32415        // (idempotent, no side effects on `&self`).
32416        //
32417        // Pins against a future silent detour that returned
32418        // `&Duration` (which would type-check but silently break every
32419        // downstream `Duration`-by-value consumer —
32420        // [`is_canonical_rate_limit_window`]'s first parameter is
32421        // `Duration`, and `&Duration` would fold to a detached copy at
32422        // the call site with a `*` deref the sibling accessors don't
32423        // need), an accidental `.window + Duration::ZERO` detour that
32424        // returned a fresh copy through an arithmetic no-op (breaking
32425        // a future `const fn` regression), or a one-arm-only accessor
32426        // that returned a canonical fallback on some sentinel input
32427        // (breaking the pass-through invariant the sibling required-
32428        // scalar accessors carry).
32429        for window in [
32430            Duration::from_secs(1),
32431            Duration::from_secs(60),
32432            Duration::from_secs(3600),
32433            Duration::ZERO,
32434            Duration::from_millis(500),
32435        ] {
32436            let rl = RateLimit { rate: 100, window };
32437            let first = rl.window();
32438            let second = rl.window();
32439            assert_eq!(
32440                first, second,
32441                "RateLimit::window must be idempotent — two successive \
32442                 calls on the same &self must return the same Duration",
32443            );
32444            assert_eq!(
32445                first, window,
32446                "RateLimit::window must return :politicas :rate-limit :window \
32447                 verbatim by copy — got {first:?}, expected {window:?}",
32448            );
32449        }
32450    }
32451
32452    #[test]
32453    fn placement_estrategia_default_pins_m3_canonical_value() {
32454        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
32455        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
32456        // active-active-across-every-named-cluster arm, the closest
32457        // canonical M3 production reference the substrate carries and
32458        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
32459        // for every un-`:placement`-declared Aplicacao. Pinning the arm
32460        // here surfaces a future rebrand of the M3-canonical
32461        // distribution default (a widening to `Sharded` once the
32462        // substrate discovers hash-keyed distribution as the more
32463        // common production shape, a tightening to `SingleNode` for
32464        // stateful Erlang/OTP distributed-app-takeover semantics
32465        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
32466        // operator pins through a future `:placement-overrides` slot)
32467        // as a deliberate test edit, not a silent contract migration.
32468        // Peer of the sibling M2 per-supervisor value pins
32469        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
32470        // /
32471        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
32472        // extended onto the M3 mesh-primitive-defining `:placement
32473        // :estrategia` axis.
32474        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
32475    }
32476
32477    #[test]
32478    fn placement_strategy_default_routes_through_lifted_default() {
32479        // Composition pin: the [`Default for PlacementStrategy`] impl's
32480        // return arm must route through the substrate-canonical
32481        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
32482        // a raw `Self::Replicated` arm. Prior to the lift the impl
32483        // carried an inline `Self::Replicated` arm with no compile-time
32484        // link back to the shared M3-canonical `Replicated` arm the
32485        // paired [`Default for Placement`] impl's struct-literal
32486        // `estrategia` field, the serde-side `#[serde(default)]` on
32487        // [`Placement::estrategia`] that resolves an author-omitted
32488        // wire-form `:placement :estrategia` scalar through the impl,
32489        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
32490        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
32491        // routes through [`Placement::default`] which routes through the
32492        // strategy default) all key off — so a future rebrand of the
32493        // M3-canonical distribution default would have had to be threaded
32494        // through the `Default` impl and the three peer routes in
32495        // lockstep or the four consumers would silently split. Byte-
32496        // parity against the lifted constant closes the split. Peer of
32497        // the sibling
32498        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
32499        // /
32500        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
32501        // composition pins on the M2 per-supervisor axes.
32502        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
32503    }
32504
32505    #[test]
32506    fn placement_default_estrategia_routes_through_lifted_default() {
32507        // Composition pin: the [`Default for Placement`] impl's
32508        // struct-literal `estrategia` field must route through the
32509        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
32510        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
32511        // impl that the sibling
32512        // `placement_strategy_default_routes_through_lifted_default` pin
32513        // already routes onto the constant). Structurally: every
32514        // `Placement::default()` call must yield an `estrategia` field
32515        // byte-equal to the lifted constant so the two paired defaults —
32516        // the [`Default for PlacementStrategy`] impl arm and the
32517        // struct-literal default arm here — cannot silently split on any
32518        // future M3-canonical distribution-default rebrand. Peer of the
32519        // sibling M2
32520        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
32521        // byte-parity pin on the [`Default for SupervisorSpec`]
32522        // struct-literal `estrategia` field extended onto the M3
32523        // mesh-primitive-defining slot family.
32524        assert_eq!(
32525            Placement::default().estrategia,
32526            PLACEMENT_ESTRATEGIA_DEFAULT,
32527        );
32528    }
32529
32530    #[test]
32531    fn placement_serde_default_estrategia_routes_through_lifted_default() {
32532        // Composition pin: the serde-side `#[serde(default)]` on
32533        // [`Placement::estrategia`] — the wire-format author-omitted
32534        // `:placement :estrategia` arm — must resolve onto the substrate-
32535        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
32536        // (via the [`Default for PlacementStrategy`] impl the sibling
32537        // `placement_strategy_default_routes_through_lifted_default` pin
32538        // already routes onto the constant). Structurally: a `Placement`
32539        // deserialized from a payload that omits the `estrategia` key
32540        // must yield an `estrategia` field byte-equal to the lifted
32541        // constant, so the wire-format author-omitted arm and the
32542        // [`PlacementStrategy::default`] impl arm cannot silently split
32543        // on any future M3-canonical distribution-default rebrand. Peer
32544        // of the sibling M2
32545        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
32546        // byte-parity pin on the wire-format author-omitted `:children
32547        // :restart` scalar extended onto the M3 mesh-primitive-defining
32548        // slot family.
32549        let omitted: Placement = serde_json::from_str("{}")
32550            .expect("Placement must deserialize with the estrategia key omitted");
32551        assert_eq!(
32552            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
32553            "an author-omitted :placement :estrategia slot must degrade onto \
32554             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
32555             {:?}, expected {:?})",
32556            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
32557        );
32558    }
32559
32560    // ── contrato_target_ctors! fold pins ────────────────────────────────
32561    //
32562    // Fixture edge triple + payload-field-name label pair for every
32563    // `contrato_target_ctors!`-generated ctor pin below. Kept as
32564    // non-default `("cart", "catalog", "wasi:http/proxy")` +
32565    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
32566    // the fixture default doesn't silently pass. Peer of the sibling
32567    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
32568    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
32569    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
32570    // `missing_entry_ctor_matches_struct_literal_wrap` /
32571    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
32572    // four `LayoutError` constructor families each closed on their
32573    // sibling envelopes.
32574    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
32575        (
32576            "cart".to_string(),
32577            "catalog".to_string(),
32578            "wasi:http/proxy".to_string(),
32579            WitTarget::HTTP_FIELD_NAME,
32580        )
32581    }
32582
32583    #[test]
32584    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
32585        // Equivalence pin: the ctor produces byte-equal
32586        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
32587        // coded struct-literal on the same edge fixture, so the fold
32588        // cannot silently drift on any future field-addition /
32589        // reordering / string-conversion tweak on the variant. Peer of
32590        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32591        // (17dd504) / the four `LayoutError` family equivalence pins.
32592        let (de, para, wit, expected) = contrato_target_ctor_fixture();
32593        let lifted = AplicacaoError::contrato_wrong_target(
32594            (de.clone(), para.clone(), wit.clone()),
32595            expected,
32596        );
32597        let struct_literal = AplicacaoError::ContratoWrongTarget {
32598            de,
32599            para,
32600            wit,
32601            expected,
32602        };
32603        assert_eq!(lifted, struct_literal);
32604    }
32605
32606    #[test]
32607    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
32608        // Equivalence pin peer of the sibling
32609        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
32610        // on the paired `ContratoMissingTarget` variant of the same
32611        // four-slot envelope shape the `contrato_target_ctors!` macro
32612        // closes.
32613        let (de, para, wit, expected) = contrato_target_ctor_fixture();
32614        let lifted = AplicacaoError::contrato_missing_target(
32615            (de.clone(), para.clone(), wit.clone()),
32616            expected,
32617        );
32618        let struct_literal = AplicacaoError::ContratoMissingTarget {
32619            de,
32620            para,
32621            wit,
32622            expected,
32623        };
32624        assert_eq!(lifted, struct_literal);
32625    }
32626
32627    #[test]
32628    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
32629        // Routing pin: the `(de, para, wit)` triple threads verbatim
32630        // onto same-named fields on both generated ctors, no wrapper-
32631        // side lowercase / trim / re-order. Sweeps a non-default triple
32632        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
32633        // wrapper-side transformation surfaces here rather than at a
32634        // downstream diagnostic-shape drift. Sibling of
32635        // `entrada_host_invalid_ctor_routes_host_through_to_string`
32636        // (17dd504) on the paired triple-carrying envelope.
32637        let edge = (
32638            "cart-svc".to_string(),
32639            "catalog-v2".to_string(),
32640            "nats:pub-sub".to_string(),
32641        );
32642        let wrong =
32643            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
32644        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
32645        let AplicacaoError::ContratoWrongTarget {
32646            de: wde,
32647            para: wpara,
32648            wit: wwit,
32649            ..
32650        } = wrong
32651        else {
32652            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
32653        };
32654        let AplicacaoError::ContratoMissingTarget {
32655            de: mde,
32656            para: mpara,
32657            wit: mwit,
32658            ..
32659        } = missing
32660        else {
32661            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
32662        };
32663        assert_eq!(wde, "cart-svc");
32664        assert_eq!(wpara, "catalog-v2");
32665        assert_eq!(wwit, "nats:pub-sub");
32666        assert_eq!(mde, "cart-svc");
32667        assert_eq!(mpara, "catalog-v2");
32668        assert_eq!(mwit, "nats:pub-sub");
32669    }
32670
32671    #[test]
32672    fn contrato_target_ctors_route_expected_through_verbatim() {
32673        // Routing pin: the `expected: &'static str` label threads
32674        // verbatim (identity, not copy-and-transform) onto the
32675        // `expected` field of both variants, so the four canonical
32676        // labels [`WitTarget::HTTP_FIELD_NAME`] /
32677        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
32678        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
32679        // pointer-equal (not merely value-equal) references — a wrapper-
32680        // side `.to_string()` / `Cow::Owned` promotion would break the
32681        // `&'static str` contract downstream consumers depend on.
32682        for label in [
32683            WitTarget::HTTP_FIELD_NAME,
32684            WitTarget::PUBSUB_FIELD_NAME,
32685            WitTarget::STORE_FIELD_NAME,
32686            WitTarget::CAPABILITY_EXPECTED,
32687        ] {
32688            let (de, para, wit, _) = contrato_target_ctor_fixture();
32689            let wrong = AplicacaoError::contrato_wrong_target(
32690                (de.clone(), para.clone(), wit.clone()),
32691                label,
32692            );
32693            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
32694            match wrong {
32695                AplicacaoError::ContratoWrongTarget { expected, .. } => {
32696                    assert!(
32697                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
32698                            && expected.len() == label.len(),
32699                        "contrato_wrong_target must thread the &'static str \
32700                         label pointer-equal onto the `expected` field \
32701                         (label = {label:?})",
32702                    );
32703                }
32704                other => panic!("expected ContratoWrongTarget, got {other:?}"),
32705            }
32706            match missing {
32707                AplicacaoError::ContratoMissingTarget { expected, .. } => {
32708                    assert!(
32709                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
32710                            && expected.len() == label.len(),
32711                        "contrato_missing_target must thread the &'static \
32712                         str label pointer-equal onto the `expected` field \
32713                         (label = {label:?})",
32714                    );
32715                }
32716                other => panic!("expected ContratoMissingTarget, got {other:?}"),
32717            }
32718        }
32719    }
32720
32721    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
32722    //
32723    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
32724    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
32725    // byte-equality mistake against the fixture default doesn't silently
32726    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
32727    // triple + expected-label envelope on
32728    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
32729    // struct_literal_wrap` (17dd504, host + reason envelope on
32730    // `entrada_host_invalid`) / the four `LayoutError` family
32731    // equivalence pins.
32732    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
32733        ("cart".to_string(), "catalog".to_string())
32734    }
32735
32736    #[test]
32737    fn empty_wit_ctor_matches_struct_literal_wrap() {
32738        // Equivalence pin: the ctor produces byte-equal
32739        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
32740        // struct-literal on the same edge pair, so the fold cannot
32741        // silently drift on any future field-addition / reordering /
32742        // string-conversion tweak on the variant. Peer of the sibling
32743        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
32744        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32745        // (17dd504) / the four `LayoutError` family equivalence pins.
32746        let (de, para) = contrato_empty_pair_ctor_fixture();
32747        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
32748        let struct_literal = AplicacaoError::EmptyWit { de, para };
32749        assert_eq!(lifted, struct_literal);
32750    }
32751
32752    #[test]
32753    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
32754        // Equivalence pin peer of the sibling
32755        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
32756        // paired `ContratoEndpointEmpty` variant of the same two-slot
32757        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
32758        let (de, para) = contrato_empty_pair_ctor_fixture();
32759        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
32760        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
32761        assert_eq!(lifted, struct_literal);
32762    }
32763
32764    #[test]
32765    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
32766        // Equivalence pin peer of the sibling
32767        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
32768        // above on the paired `ContratoSubjectEmpty` variant of the
32769        // same two-slot envelope shape.
32770        let (de, para) = contrato_empty_pair_ctor_fixture();
32771        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
32772        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
32773        assert_eq!(lifted, struct_literal);
32774    }
32775
32776    #[test]
32777    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
32778        // Equivalence pin peer of the sibling
32779        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
32780        // above on the paired `ContratoSlotEmpty` variant of the same
32781        // two-slot envelope shape.
32782        let (de, para) = contrato_empty_pair_ctor_fixture();
32783        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
32784        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
32785        assert_eq!(lifted, struct_literal);
32786    }
32787
32788    #[test]
32789    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
32790        // Routing pin: the `(de, para)` pair threads verbatim onto
32791        // same-named fields on all four generated ctors, no wrapper-
32792        // side lowercase / trim / re-order. Sweeps a non-default pair
32793        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
32794        // transformation surfaces here rather than at a downstream
32795        // diagnostic-shape drift. Sibling of
32796        // `contrato_target_ctors_route_edge_triple_through_verbatim`
32797        // (14b81d5) on the paired triple-carrying envelope and of
32798        // `entrada_host_invalid_ctor_routes_host_through_to_string`
32799        // (17dd504) on the sibling `{ host, reason }` envelope.
32800        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
32801        let variants: [(AplicacaoError, &'static str); 4] = [
32802            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
32803            (
32804                AplicacaoError::contrato_endpoint_empty(edge.clone()),
32805                "ContratoEndpointEmpty",
32806            ),
32807            (
32808                AplicacaoError::contrato_subject_empty(edge.clone()),
32809                "ContratoSubjectEmpty",
32810            ),
32811            (
32812                AplicacaoError::contrato_slot_empty(edge.clone()),
32813                "ContratoSlotEmpty",
32814            ),
32815        ];
32816        for (built, label) in variants {
32817            let (de, para) = match built {
32818                AplicacaoError::EmptyWit { de, para }
32819                | AplicacaoError::ContratoEndpointEmpty { de, para }
32820                | AplicacaoError::ContratoSubjectEmpty { de, para }
32821                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
32822                other => panic!("expected {label} pair variant, got {other:?}"),
32823            };
32824            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
32825            assert_eq!(
32826                para, "catalog-v2",
32827                "para field on {label} must thread verbatim",
32828            );
32829        }
32830    }
32831
32832    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
32833    //
32834    // Fixture edge pair + value + reason for every
32835    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
32836    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
32837    // fixed per-axis `<val>` / reason so a byte-equality mistake against
32838    // the fixture default doesn't silently pass. Peer of the sibling
32839    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
32840    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
32841    // (14b81d5, triple + expected-label envelope on
32842    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
32843    // struct_literal_wrap` (17dd504, host + reason envelope on
32844    // `entrada_host_invalid`).
32845    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
32846        ("cart".to_string(), "catalog".to_string())
32847    }
32848
32849    #[test]
32850    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
32851        // Equivalence pin: the ctor produces byte-equal
32852        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
32853        // open-coded struct-literal on the same
32854        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
32855        // silently drift on any future field-addition / reordering /
32856        // string-conversion tweak on the variant. Peer of the sibling
32857        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
32858        // (8580068) on the paired two-slot envelope of the same
32859        // `{ de, para, ... }` prefix, and of
32860        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
32861        // (17dd504) on the sibling `{ <field>: String, reason: String }`
32862        // two-slot envelope.
32863        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32864        let endpoint = "/charge";
32865        let reason = "sample reason text";
32866        let lifted =
32867            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
32868        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
32869            de,
32870            para,
32871            endpoint: endpoint.to_string(),
32872            reason: reason.to_string(),
32873        };
32874        assert_eq!(lifted, struct_literal);
32875    }
32876
32877    #[test]
32878    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
32879        // Equivalence pin peer of the sibling
32880        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
32881        // above on the paired `ContratoSubjectInvalid` variant of the
32882        // same four-slot envelope shape the
32883        // `contrato_pair_value_reason_ctors!` macro closes.
32884        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32885        let subject = "checkout.events.charge.failed";
32886        let reason = "sample reason text";
32887        let lifted =
32888            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
32889        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
32890            de,
32891            para,
32892            subject: subject.to_string(),
32893            reason: reason.to_string(),
32894        };
32895        assert_eq!(lifted, struct_literal);
32896    }
32897
32898    #[test]
32899    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
32900        // Equivalence pin peer of the sibling
32901        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
32902        // above on the paired `ContratoSlotInvalid` variant of the same
32903        // four-slot envelope shape.
32904        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32905        let slot = "checkout/$orderId";
32906        let reason = "sample reason text";
32907        let lifted =
32908            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
32909        let struct_literal = AplicacaoError::ContratoSlotInvalid {
32910            de,
32911            para,
32912            slot: slot.to_string(),
32913            reason: reason.to_string(),
32914        };
32915        assert_eq!(lifted, struct_literal);
32916    }
32917
32918    #[test]
32919    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
32920        // Equivalence pin peer of the sibling
32921        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
32922        // on the paired `ContratoWitInvalid` variant of the same four-
32923        // slot envelope shape the `contrato_pair_value_reason_ctors!`
32924        // macro closes. Fold pinned this test lands with the last
32925        // `{ de, para, <field>: String, reason: String }` open-coded
32926        // struct-literal inside [`WitContract::target`] rewritten to
32927        // route through the macro-generated
32928        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
32929        // between the ctor and the pre-lift struct-literal trips this
32930        // pin ahead of any downstream diagnostic-shape drift on the
32931        // `:contratos :wit` axis.
32932        let (de, para) = contrato_pair_value_reason_ctor_fixture();
32933        let wit = "wasi-http/proxy";
32934        let reason = "sample reason text";
32935        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
32936        let struct_literal = AplicacaoError::ContratoWitInvalid {
32937            de,
32938            para,
32939            wit: wit.to_string(),
32940            reason: reason.to_string(),
32941        };
32942        assert_eq!(lifted, struct_literal);
32943    }
32944
32945    #[test]
32946    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
32947        // Routing pin: the `(de, para)` pair threads verbatim onto
32948        // same-named fields on all four generated ctors, no wrapper-
32949        // side lowercase / trim / re-order. Sweeps a non-default pair
32950        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
32951        // transformation surfaces here rather than at a downstream
32952        // diagnostic-shape drift. Sibling of
32953        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
32954        // (8580068) on the paired two-slot envelope and of
32955        // `contrato_target_ctors_route_edge_triple_through_verbatim`
32956        // (14b81d5) on the paired triple-carrying envelope.
32957        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
32958        let variants: [(AplicacaoError, &'static str); 4] = [
32959            (
32960                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
32961                "ContratoEndpointInvalid",
32962            ),
32963            (
32964                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
32965                "ContratoSubjectInvalid",
32966            ),
32967            (
32968                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
32969                "ContratoSlotInvalid",
32970            ),
32971            (
32972                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
32973                "ContratoWitInvalid",
32974            ),
32975        ];
32976        for (built, label) in variants {
32977            let (de, para) = match built {
32978                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
32979                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
32980                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
32981                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
32982                other => panic!("expected {label} pair variant, got {other:?}"),
32983            };
32984            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
32985            assert_eq!(
32986                para, "catalog-v2",
32987                "para field on {label} must thread verbatim",
32988            );
32989        }
32990    }
32991
32992    #[test]
32993    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
32994        // Cross-arm invariance pin — the four ctors all route
32995        // `reason: impl Into<String>` verbatim onto their respective
32996        // typed variants through the shared
32997        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
32998        // pair (`&str` literal, `format!` output) against every ctor to
32999        // pin that no per-arm wrapper transformation drifted in against
33000        // the uniform macro-generated body. Peer of
33001        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
33002        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
33003        let edge = || ("cart".to_string(), "catalog".to_string());
33004        let via_literal = "literal reason text";
33005        let via_format = format!("{} reason text", "literal");
33006        assert_eq!(
33007            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
33008            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
33009        );
33010        assert_eq!(
33011            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
33012            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
33013        );
33014        assert_eq!(
33015            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
33016            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
33017        );
33018        assert_eq!(
33019            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
33020            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
33021        );
33022    }
33023
33024    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
33025    //
33026    // Fail-before-pass-after pins for the standalone
33027    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
33028    // (see the paired doc-block above the ctor definition) — the fold of
33029    // the last open-coded three-slot `{ de, para, endpoint: <val>
33030    // .to_string() }` struct-literal inside [`WitContract::target`]'s
33031    // HTTP-arm leading-slash gate onto one substrate primitive on the
33032    // envelope. A byte-mismatched ctor body would trip the equivalence
33033    // pin first, ahead of any downstream diagnostic-shape drift.
33034    //
33035    // Peer of the sibling standalone-ctor equivalence pins on the peer
33036    // one-off variants across caixa-core:
33037    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
33038    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
33039    // on the paired two-slot and four-slot per-`:contratos :endpoint`
33040    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
33041    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
33042    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
33043    // reason }` two- and three-slot envelopes; the
33044    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
33045    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
33046    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
33047        ("cart".to_string(), "catalog".to_string())
33048    }
33049
33050    #[test]
33051    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
33052        // Equivalence pin: the ctor produces byte-equal
33053        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
33054        // open-coded struct-literal on the same `(edge_pair, endpoint)`
33055        // pair, so the fold cannot silently drift on any future
33056        // field-addition / reordering / string-conversion tweak on the
33057        // variant. Same equivalence-pin shape as the sibling
33058        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33059        // (8580068) on the paired two-slot envelope and
33060        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
33061        // (14e13f1) on the paired four-slot envelope of the same
33062        // `{ de, para, ... }`-prefix `:endpoint` axis.
33063        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
33064        let endpoint = "charge";
33065        let lifted =
33066            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
33067        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
33068            de,
33069            para,
33070            endpoint: endpoint.to_string(),
33071        };
33072        assert_eq!(lifted, struct_literal);
33073    }
33074
33075    #[test]
33076    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
33077        // Routing pin on the `(de, para)` axis: sweep a non-default
33078        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33079        // lowercase / trim / re-order surfaces here rather than at a
33080        // downstream diagnostic-shape drift. Peer of
33081        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
33082        // (8580068) on the paired two-slot envelope and
33083        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
33084        // (14e13f1) on the paired four-slot envelope of the same
33085        // `{ de, para, ... }`-prefix `:contratos` axis.
33086        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33087        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
33088        match built {
33089            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
33090                assert_eq!(de, "cart-svc", "de field must thread verbatim");
33091                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
33092            }
33093            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
33094        }
33095    }
33096
33097    #[test]
33098    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
33099        // Routing pin on the `endpoint: &str` axis: sweep a non-default
33100        // value (`"charge"` — no leading `/`, the exact shape the
33101        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
33102        // through the sole payload-carrier constructor axis so any
33103        // wrapper-side transformation on the `endpoint.to_string()`
33104        // one-field construction surfaces here rather than at a
33105        // downstream diagnostic-shape mismatch. Sibling of
33106        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
33107        // (14e13f1) on the sibling four-slot envelope's payload-carrier
33108        // routing pin.
33109        let edge = || ("cart".to_string(), "catalog".to_string());
33110        let via_literal = "charge";
33111        let via_string = String::from("charge");
33112        assert_eq!(
33113            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
33114            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
33115        );
33116    }
33117
33118    // ── contrato_self_loop standalone ctor pins ─────────────────────────
33119    //
33120    // Fail-before-pass-after pins for the standalone
33121    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
33122    // doc-block above the ctor definition) — the fold of the last
33123    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
33124    // <ct>.world_ref().to_string() }` struct-literal inside
33125    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
33126    // arm onto one substrate primitive on the [`AplicacaoError`]
33127    // envelope, projecting through the paired [`WitContract::source`] /
33128    // [`WitContract::world_ref`] scalar accessors on the substrate
33129    // primitive. A byte-mismatched ctor body would trip the equivalence
33130    // pin first, ahead of any downstream diagnostic-shape drift.
33131    //
33132    // Peer of the sibling standalone-ctor equivalence pins on the peer
33133    // one-off variants across caixa-core:
33134    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
33135    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
33136    // envelope, the sibling
33137    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
33138    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
33139    // the paired two-slot and four-slot per-`:contratos :endpoint`
33140    // envelopes, and the sibling
33141    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
33142    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
33143    fn contrato_self_loop_ctor_fixture() -> WitContract {
33144        WitContract {
33145            de: "cart".to_string(),
33146            para: "cart".to_string(),
33147            wit: "wasi:http/proxy".to_string(),
33148            endpoint: Some("/self".to_string()),
33149            subject: None,
33150            slot: None,
33151        }
33152    }
33153
33154    #[test]
33155    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
33156        // Equivalence pin: the ctor produces byte-equal
33157        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
33158        // struct-literal that read the same two fields through
33159        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
33160        // any future field-addition / reordering / string-conversion
33161        // tweak on the variant. Same equivalence-pin shape as the
33162        // sibling `contrato_endpoint_not_absolute_ctor_matches_
33163        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
33164        // per-`:contratos :endpoint` envelope.
33165        let contract = contrato_self_loop_ctor_fixture();
33166        let lifted = AplicacaoError::contrato_self_loop(&contract);
33167        let struct_literal = AplicacaoError::ContratoSelfLoop {
33168            caixa: contract.source().to_string(),
33169            wit: contract.world_ref().to_string(),
33170        };
33171        assert_eq!(lifted, struct_literal);
33172    }
33173
33174    #[test]
33175    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
33176        // Routing pin sweeping non-default `caixa` and `:wit` values
33177        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
33178        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
33179        // axes so any wrapper-side lowercase / trim / re-order surfaces
33180        // here rather than at a downstream diagnostic-shape drift.
33181        // Peer of the sibling
33182        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
33183        // (cdf1a2c) routing pin on the sibling three-slot envelope.
33184        let contract = WitContract {
33185            de: "catalog-v2".to_string(),
33186            para: "catalog-v2".to_string(),
33187            wit: "nats:pub-sub".to_string(),
33188            endpoint: None,
33189            subject: Some("orders.>".to_string()),
33190            slot: None,
33191        };
33192        let built = AplicacaoError::contrato_self_loop(&contract);
33193        match built {
33194            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
33195                assert_eq!(
33196                    caixa, "catalog-v2",
33197                    "caixa slot must thread WitContract::source() verbatim"
33198                );
33199                assert_eq!(
33200                    wit, "nats:pub-sub",
33201                    "wit slot must thread WitContract::world_ref() verbatim"
33202                );
33203            }
33204            other => panic!("expected ContratoSelfLoop, got {other:?}"),
33205        }
33206    }
33207
33208    #[test]
33209    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
33210        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
33211        // [`WitContract::source`] accessor (matching the pre-lift open-
33212        // coded body's field selection), not [`WitContract::destination`].
33213        // Under today's `WitContract::is_self_loop()`-gated call site
33214        // the two are equal by that predicate's own contract, but a
33215        // future consumer that constructs the ctor against a not-yet-
33216        // gated candidate contract — an M4
33217        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
33218        // checking a per-`(:de, :para)`-patched candidate before the
33219        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
33220        // resolver rejecting a self-edge introduced by a cluster-local
33221        // `:contratos` override — needs the pre-lift field selection
33222        // pinned so a silent `.destination()` swap at the ctor body
33223        // surfaces here rather than at a downstream diagnostic mis-
33224        // attribution far from the self-loop diagnostic's owner
33225        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
33226        // direction).
33227        //
33228        // Deliberately constructs a non-self-loop pair (`"cart" →
33229        // "catalog"`) so the two accessors yield distinct bytes on the
33230        // fixture — a `.destination()` swap at the ctor body would land
33231        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
33232        // the assertion here.
33233        let contract = WitContract {
33234            de: "cart".to_string(),
33235            para: "catalog".to_string(),
33236            wit: "wasi:http/proxy".to_string(),
33237            endpoint: Some("/charge".to_string()),
33238            subject: None,
33239            slot: None,
33240        };
33241        let built = AplicacaoError::contrato_self_loop(&contract);
33242        match built {
33243            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
33244                assert_eq!(
33245                    caixa, "cart",
33246                    "caixa slot must project WitContract::source() (not destination)"
33247                );
33248            }
33249            other => panic!("expected ContratoSelfLoop, got {other:?}"),
33250        }
33251    }
33252
33253    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
33254    // macro definition (see the paired doc-block above the macro definition)
33255    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
33256    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
33257    // struct-literal onto one substrate primitive. The four per-variant
33258    // equivalence pins below (fail-before-pass-after by construction — a
33259    // byte-mismatched macro arm would trip its equivalence pin first) lock
33260    // each generated constructor to its struct-literal peer under
33261    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
33262    // [`AplicacaoSpec::validate_membros`], and
33263    // [`validate_no_self_membership`] on that variant produces a byte-equal
33264    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
33265    // cross-axis pin that follows (non-default caixa name) routes the sole
33266    // constructor input axis through `.to_string()`, so the fold does not
33267    // silently collapse onto a fixed name.
33268    //
33269    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
33270    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
33271    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
33272    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
33273    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
33274    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
33275    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
33276    // of the peer M2 `:behavior` envelope fold (67c31ec,
33277    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
33278    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
33279    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
33280
33281    #[test]
33282    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
33283        assert_eq!(
33284            AplicacaoError::contrato_member_missing("cart"),
33285            AplicacaoError::ContratoMemberMissing {
33286                caixa: "cart".to_string(),
33287            },
33288            "generated contrato_member_missing ctor must produce byte-equal \
33289             AplicacaoError to the open-coded struct-literal wrap on the \
33290             same &str fixture",
33291        );
33292    }
33293
33294    #[test]
33295    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
33296        assert_eq!(
33297            AplicacaoError::membro_versao_empty("cart"),
33298            AplicacaoError::MembroVersaoEmpty {
33299                caixa: "cart".to_string(),
33300            },
33301            "generated membro_versao_empty ctor must produce byte-equal \
33302             AplicacaoError to the open-coded struct-literal wrap on the \
33303             same &str fixture",
33304        );
33305    }
33306
33307    #[test]
33308    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
33309        assert_eq!(
33310            AplicacaoError::membro_duplicate("cart"),
33311            AplicacaoError::MembroDuplicate {
33312                caixa: "cart".to_string(),
33313            },
33314            "generated membro_duplicate ctor must produce byte-equal \
33315             AplicacaoError to the open-coded struct-literal wrap on the \
33316             same &str fixture",
33317        );
33318    }
33319
33320    #[test]
33321    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
33322        assert_eq!(
33323            AplicacaoError::membro_is_self_aplicacao("checkout"),
33324            AplicacaoError::MembroIsSelfAplicacao {
33325                caixa: "checkout".to_string(),
33326            },
33327            "generated membro_is_self_aplicacao ctor must produce byte-equal \
33328             AplicacaoError to the open-coded struct-literal wrap on the \
33329             same &str fixture",
33330        );
33331    }
33332
33333    #[test]
33334    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
33335        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
33336        // &str`) through a non-default fixture name against every generated
33337        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
33338        // wrapper-side lowercase / trim / truncate / re-order on the
33339        // `caixa.to_string()` sole-field construction surfaces here rather
33340        // than at a downstream diagnostic-shape mismatch. Peer of the
33341        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
33342        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
33343        // envelope (db09650), extended here onto the peer `AplicacaoError`
33344        // `{ caixa: String }` envelope so every substrate-primitive ctor
33345        // family in caixa-core carrying a single-slot `{ caixa: String }`
33346        // shape guarantees the sole-field construction routes the caller's
33347        // `&str` through `.to_string()` verbatim.
33348        let name = "cache-v2";
33349        assert_eq!(
33350            AplicacaoError::contrato_member_missing(name),
33351            AplicacaoError::ContratoMemberMissing {
33352                caixa: name.to_string(),
33353            },
33354        );
33355        assert_eq!(
33356            AplicacaoError::membro_versao_empty(name),
33357            AplicacaoError::MembroVersaoEmpty {
33358                caixa: name.to_string(),
33359            },
33360        );
33361        assert_eq!(
33362            AplicacaoError::membro_duplicate(name),
33363            AplicacaoError::MembroDuplicate {
33364                caixa: name.to_string(),
33365            },
33366        );
33367        assert_eq!(
33368            AplicacaoError::membro_is_self_aplicacao(name),
33369            AplicacaoError::MembroIsSelfAplicacao {
33370                caixa: name.to_string(),
33371            },
33372        );
33373    }
33374
33375    #[test]
33376    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
33377        assert_eq!(
33378            AplicacaoError::entrada_path_not_absolute("api/cart"),
33379            AplicacaoError::EntradaPathNotAbsolute {
33380                path: "api/cart".to_string(),
33381            },
33382            "generated entrada_path_not_absolute ctor must produce byte-equal \
33383             AplicacaoError to the open-coded struct-literal wrap on the \
33384             same &str fixture",
33385        );
33386    }
33387
33388    #[test]
33389    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
33390        assert_eq!(
33391            AplicacaoError::entrada_path_duplicate("/api/cart"),
33392            AplicacaoError::EntradaPathDuplicate {
33393                path: "/api/cart".to_string(),
33394            },
33395            "generated entrada_path_duplicate ctor must produce byte-equal \
33396             AplicacaoError to the open-coded struct-literal wrap on the \
33397             same &str fixture",
33398        );
33399    }
33400
33401    // ── membro_versao_invalid ctor pins ────────────────────────────────
33402    //
33403    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
33404    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
33405    // produces an `AplicacaoError` structurally identical to the pre-lift
33406    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
33407    // versao.to_string(), reason: reason.into() }` open-coded three-slot
33408    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
33409    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
33410    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33411    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
33412    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
33413    // extended here onto the paired per-`:membros :versao` axis on the
33414    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
33415    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
33416    // typed-error surface guarantee the shared three-field construction
33417    // routes through one substrate primitive per envelope.
33418
33419    #[test]
33420    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
33421        let caixa = "cart";
33422        let versao = "not-a-req";
33423        let reason = "sample reason text";
33424        assert_eq!(
33425            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
33426            AplicacaoError::MembroVersaoInvalid {
33427                caixa: caixa.to_string(),
33428                versao: versao.to_string(),
33429                reason: reason.to_string(),
33430            },
33431            "lifted membro_versao_invalid ctor must produce byte-equal \
33432             AplicacaoError to the open-coded struct-literal wrap on the \
33433             same (&str, &str, reason) fixture",
33434        );
33435    }
33436
33437    #[test]
33438    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
33439        // Cross-axis pin: sweep the two `&str`-shaped constructor input
33440        // axes (`caixa`, `versao`) through non-default fixtures so any
33441        // wrapper-side lowercase / trim / truncate / re-order on either
33442        // `.to_string()` field construction surfaces here rather than at
33443        // a downstream diagnostic-shape mismatch. Peer of the sibling
33444        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33445        // routing pin on the peer `SupervisorError` envelope.
33446        let caixa = "Cart-V2";
33447        let versao = "0.1.0-alpha+build.42";
33448        let reason = "constructed reason";
33449        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
33450        let AplicacaoError::MembroVersaoInvalid {
33451            caixa: got_caixa,
33452            versao: got_versao,
33453            reason: got_reason,
33454        } = err
33455        else {
33456            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
33457        };
33458        assert_eq!(got_caixa, caixa.to_string());
33459        assert_eq!(got_versao, versao.to_string());
33460        assert_eq!(got_reason, reason.to_string());
33461    }
33462
33463    #[test]
33464    fn membro_versao_invalid_ctor_routes_reason_through_into() {
33465        // Route pin: the `reason: impl Into<String>` bound accepts both
33466        // `&str` literals and `format!(…)` / `String` outputs verbatim,
33467        // matching the sibling
33468        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33469        // routing pin on the peer `SupervisorError::child_versao_invalid`.
33470        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
33471        // `require_valid_versao_requirement`-delivered `reason` closure
33472        // parameter (typed `String`) picks the ctor up without a per-arm
33473        // wrapper transformation, and every future consumer that
33474        // constructs the variant from a `format!(…)` reason surfaces
33475        // byte-equal to the `&str`-literal path.
33476        let caixa = "cart";
33477        let versao = "not-a-req";
33478        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
33479        let from_format =
33480            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
33481        let from_string =
33482            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
33483        assert_eq!(from_literal, from_format);
33484        assert_eq!(from_literal, from_string);
33485    }
33486
33487    #[test]
33488    fn aplicacao_path_only_ctors_route_path_through_to_string() {
33489        // Cross-axis pin: sweep the sole constructor input axis (`path:
33490        // &str`) through a non-default fixture path against every generated
33491        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
33492        // wrapper-side lowercase / trim / truncate / re-order on the
33493        // `path.to_string()` sole-field construction surfaces here rather
33494        // than at a downstream diagnostic-shape mismatch. Peer of the
33495        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
33496        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
33497        // envelope (d9f6867), extended here onto the sibling
33498        // `AplicacaoError` `{ path: String }` envelope so every substrate-
33499        // primitive ctor family in caixa-core carrying a single-slot
33500        // `{ <slot>: String }` shape guarantees the sole-field construction
33501        // routes the caller's `&str` through `.to_string()` verbatim.
33502        let path = "/api/v2/checkout";
33503        assert_eq!(
33504            AplicacaoError::entrada_path_not_absolute(path),
33505            AplicacaoError::EntradaPathNotAbsolute {
33506                path: path.to_string(),
33507            },
33508        );
33509        assert_eq!(
33510            AplicacaoError::entrada_path_duplicate(path),
33511            AplicacaoError::EntradaPathDuplicate {
33512                path: path.to_string(),
33513            },
33514        );
33515    }
33516
33517    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
33518    //
33519    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
33520    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
33521    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
33522    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
33523    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
33524    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
33525    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
33526    // substitution on any one variant surfaces here rather than at a downstream
33527    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
33528    // pins on `aplicacao_field_reason_ctors!` (981060b),
33529    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
33530    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
33531    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
33532    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
33533    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
33534    // per-envelope ctor-macro pins.
33535
33536    #[test]
33537    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
33538        let timeout = Duration::from_micros(1_500);
33539        assert_eq!(
33540            AplicacaoError::policy_timeout_not_canonical(timeout),
33541            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
33542            "generated policy_timeout_not_canonical ctor must produce byte-equal \
33543             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
33544             struct-literal wrap on the same `Copy`-`Duration` fixture",
33545        );
33546    }
33547
33548    #[test]
33549    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
33550        let timeout = Duration::from_secs(3_601);
33551        assert_eq!(
33552            AplicacaoError::policy_timeout_exceeds_cap(timeout),
33553            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
33554            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
33555             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
33556             struct-literal wrap on the same `Copy`-`Duration` fixture",
33557        );
33558    }
33559
33560    #[test]
33561    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
33562        let retries = 47_u32;
33563        assert_eq!(
33564            AplicacaoError::policy_retries_exceeds_cap(retries),
33565            AplicacaoError::PolicyRetriesExceedsCap { retries },
33566            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
33567             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
33568             struct-literal wrap on the same `Copy`-`u32` fixture",
33569        );
33570    }
33571
33572    #[test]
33573    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
33574        let max_failures = 1_337_u32;
33575        assert_eq!(
33576            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
33577            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
33578            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
33579             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
33580             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
33581        );
33582    }
33583
33584    #[test]
33585    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
33586        let window = Duration::from_micros(500);
33587        assert_eq!(
33588            AplicacaoError::policy_breaker_window_not_canonical(window),
33589            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
33590            "generated policy_breaker_window_not_canonical ctor must produce \
33591             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
33592             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
33593        );
33594    }
33595
33596    #[test]
33597    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
33598        let window = Duration::from_secs(3_700);
33599        assert_eq!(
33600            AplicacaoError::policy_breaker_window_exceeds_cap(window),
33601            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
33602            "generated policy_breaker_window_exceeds_cap ctor must produce \
33603             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
33604             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
33605        );
33606    }
33607
33608    #[test]
33609    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
33610        let rate = 1_000_001_u32;
33611        assert_eq!(
33612            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
33613            AplicacaoError::PolicyRateLimitExceedsCap { rate },
33614            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
33615             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
33616             struct-literal wrap on the same `Copy`-`u32` fixture",
33617        );
33618    }
33619
33620    #[test]
33621    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
33622        let window = Duration::from_secs(15);
33623        assert_eq!(
33624            AplicacaoError::policy_rate_limit_window_not_canonical(window),
33625            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
33626            "generated policy_rate_limit_window_not_canonical ctor must produce \
33627             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
33628             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
33629             fixture",
33630        );
33631    }
33632
33633    #[test]
33634    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
33635        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
33636        // constructor input axis through a non-default `Copy` fixture against
33637        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
33638        // wrapper-side silent `.into()` / silent constant-substitution / silent
33639        // field re-name away from the canonical `timeout | retries |
33640        // max_failures | window | rate` axes on any one variant, or a
33641        // `Duration | u32` axis silently rerouted through some other `Copy`
33642        // coercion, surfaces here rather than at a downstream per-`:politicas`
33643        // diagnostic-shape drift. Peer of the sibling
33644        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
33645        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
33646        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
33647        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33648        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
33649        // families, extended here onto the last M3 per-`:politicas` per-axis
33650        // `AplicacaoError` variant family folded onto a substrate primitive.
33651        //
33652        // Fixtures picked out of each variant's accept-set boundary rather
33653        // than the default value so a silent constant-substitution to `0` /
33654        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
33655        // structural-equality assertion. The two `Duration` fixtures pick the
33656        // sub-millisecond and above-cap ends respectively; the three `u32`
33657        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
33658        // `rate` respectively (each variant's cap sits well below the fixture
33659        // so the pre-lift struct-literal wrap the fixture is compared against
33660        // is the same shape the pre-lift wire-up produced).
33661        let sub_ms = Duration::from_micros(1_500);
33662        let above_hour = Duration::from_secs(3_700);
33663        let non_canonical_rl_window = Duration::from_secs(15);
33664        assert_eq!(
33665            AplicacaoError::policy_timeout_not_canonical(sub_ms),
33666            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
33667        );
33668        assert_eq!(
33669            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
33670            AplicacaoError::PolicyTimeoutExceedsCap {
33671                timeout: above_hour,
33672            },
33673        );
33674        assert_eq!(
33675            AplicacaoError::policy_retries_exceeds_cap(47),
33676            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
33677        );
33678        assert_eq!(
33679            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
33680            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
33681                max_failures: 1_337,
33682            },
33683        );
33684        assert_eq!(
33685            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
33686            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
33687        );
33688        assert_eq!(
33689            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
33690            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
33691        );
33692        assert_eq!(
33693            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
33694            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
33695        );
33696        assert_eq!(
33697            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
33698            AplicacaoError::PolicyRateLimitWindowNotCanonical {
33699                window: non_canonical_rl_window,
33700            },
33701        );
33702    }
33703
33704    #[test]
33705    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
33706        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
33707        // every generated ctor `const fn` so a caller can pin an
33708        // `AplicacaoError` at compile time — the same zero-runtime-work
33709        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
33710        // closure carried on its `Copy`-pass-through construction path (no
33711        // `.to_string()` / `.into()` allocation, no branching). If any future
33712        // edit silently drops the `const` qualifier from the macro body the
33713        // per-arm `const` bindings below fail to compile, which surfaces the
33714        // regression at the substrate-primitive definition rather than at
33715        // some downstream consumer that had come to rely on the `const`-
33716        // constructibility. Peer of the sibling per-variant
33717        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
33718        // equality axis; this pin closes the compile-time-const axis on the
33719        // same generated family.
33720        const TIMEOUT_NC: AplicacaoError =
33721            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
33722        const TIMEOUT_CAP: AplicacaoError =
33723            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
33724        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
33725        const MAX_FAIL_CAP: AplicacaoError =
33726            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
33727        const CB_WIN_NC: AplicacaoError =
33728            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
33729        const CB_WIN_CAP: AplicacaoError =
33730            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
33731        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
33732        const RL_WIN_NC: AplicacaoError =
33733            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
33734        assert!(matches!(
33735            TIMEOUT_NC,
33736            AplicacaoError::PolicyTimeoutNotCanonical { .. }
33737        ));
33738        assert!(matches!(
33739            TIMEOUT_CAP,
33740            AplicacaoError::PolicyTimeoutExceedsCap { .. }
33741        ));
33742        assert!(matches!(
33743            RETRIES_CAP,
33744            AplicacaoError::PolicyRetriesExceedsCap { .. }
33745        ));
33746        assert!(matches!(
33747            MAX_FAIL_CAP,
33748            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
33749        ));
33750        assert!(matches!(
33751            CB_WIN_NC,
33752            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
33753        ));
33754        assert!(matches!(
33755            CB_WIN_CAP,
33756            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
33757        ));
33758        assert!(matches!(
33759            RATE_CAP,
33760            AplicacaoError::PolicyRateLimitExceedsCap { .. }
33761        ));
33762        assert!(matches!(
33763            RL_WIN_NC,
33764            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
33765        ));
33766    }
33767
33768    // Per-variant equivalence + routing pins for the
33769    // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
33770    // (see the paired doc-block above the ctor definition) — the
33771    // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
33772    // Self` inherent constructor folds the uniform
33773    // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
33774    // one-field struct-literal onto one substrate primitive. Same
33775    // shape as the sibling
33776    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
33777    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
33778    // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
33779    // ctors — extended here onto the single-slot per-`:placement
33780    // :clusters` dedup-envelope.
33781
33782    #[test]
33783    fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
33784        // Equivalence pin: the ctor produces byte-equal
33785        // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
33786        // open-coded struct-literal that read the same field through
33787        // `c.clone()` at the caller site inside
33788        // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
33789        // field-addition / reordering / string-conversion tweak on the
33790        // variant.
33791        let cluster = "rio";
33792        let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
33793        let struct_literal = AplicacaoError::PlacementClusterDuplicate {
33794            cluster: cluster.to_string(),
33795        };
33796        assert_eq!(lifted, struct_literal);
33797    }
33798
33799    #[test]
33800    fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
33801        // Routing pin: sweep the sole constructor input axis
33802        // (`cluster: &str`) through a non-default fixture name so any
33803        // wrapper-side lowercase / trim / truncate / re-order on the
33804        // `cluster.to_string()` sole-field construction surfaces here
33805        // rather than at a downstream diagnostic-shape mismatch. Peer of
33806        // the sibling
33807        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
33808        // (d9f6867) cross-axis pin on the sibling one-slot
33809        // `{ caixa: String }` envelope — extended here onto the sibling
33810        // `{ cluster: String }` envelope so the sole `String`-slot
33811        // construction routes the caller's `&str` through `.to_string()`
33812        // verbatim.
33813        let cluster = "sao-paulo-2";
33814        let built = AplicacaoError::placement_cluster_duplicate(cluster);
33815        match built {
33816            AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
33817                assert_eq!(
33818                    c, cluster,
33819                    "cluster slot must thread the caller's `&str` verbatim through .to_string()"
33820                );
33821            }
33822            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
33823        }
33824    }
33825
33826    // Per-variant equivalence + routing pins for the
33827    // [`AplicacaoError::placement_without_clusters`] standalone ctor
33828    // (see the paired doc-block above the ctor definition) — the
33829    // generated `pub const fn placement_without_clusters(placement:
33830    // &Placement) -> Self` inherent constructor folds the uniform
33831    // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
33832    // }` one-field `Copy`-pass-through struct-literal onto one substrate
33833    // primitive. Same shape as the sibling
33834    // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
33835    // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
33836    // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
33837    // ctors — extended here onto the one-slot per-`:placement`
33838    // empty-clusters envelope.
33839
33840    #[test]
33841    fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
33842        // Equivalence pin: the ctor produces byte-equal
33843        // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
33844        // open-coded struct-literal that read the same field through
33845        // `p.estrategia()` at the caller site inside
33846        // [`AplicacaoSpec::validate_placement`]. Guards any future
33847        // field-addition / reordering / accessor-return tweak on the
33848        // variant.
33849        let placement = Placement {
33850            estrategia: PlacementStrategy::Replicated,
33851            clusters: vec![],
33852            affinity: None,
33853            shard_key: None,
33854        };
33855        let lifted = AplicacaoError::placement_without_clusters(&placement);
33856        let struct_literal = AplicacaoError::PlacementWithoutClusters {
33857            estrategia: placement.estrategia(),
33858        };
33859        assert_eq!(lifted, struct_literal);
33860    }
33861
33862    #[test]
33863    fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
33864        // Routing pin: sweep the sole constructor input axis
33865        // (`placement: &Placement`) through every variant in the closed
33866        // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
33867        // re-derivation / off-by-one arm-swap / stale-field read on the
33868        // `placement.estrategia()` sole-field projection surfaces here
33869        // rather than at a downstream diagnostic-shape mismatch. Peer of
33870        // the sibling
33871        // `validate_placement_reads_through_lifted_estrategia_accessor`
33872        // three-consumer coherence pin — extended here onto the ctor
33873        // itself so the accessor-projection posture is byte-witnessed at
33874        // the substrate primitive rather than only at the caller-site
33875        // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
33876        // future addition to the closed accept-set surfaces as an
33877        // exhaustiveness gap on this iteration list.
33878        for estrategia in [
33879            PlacementStrategy::SingleNode,
33880            PlacementStrategy::Replicated,
33881            PlacementStrategy::Sharded,
33882        ] {
33883            let placement = Placement {
33884                estrategia,
33885                clusters: vec![],
33886                affinity: None,
33887                shard_key: None,
33888            };
33889            let built = AplicacaoError::placement_without_clusters(&placement);
33890            match built {
33891                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
33892                    assert_eq!(
33893                        e,
33894                        placement.estrategia(),
33895                        "estrategia slot must thread the caller's `Placement` verbatim \
33896                         through Placement::estrategia() — the ctor reads through the \
33897                         lifted accessor",
33898                    );
33899                    assert_eq!(
33900                        e, estrategia,
33901                        "estrategia slot must byte-equal the fixture-declared variant",
33902                    );
33903                }
33904                other => panic!("expected PlacementWithoutClusters, got {other:?}"),
33905            }
33906        }
33907    }
33908
33909    #[test]
33910    fn placement_without_clusters_ctor_is_const_fn() {
33911        // Fail-before-pass-after pin on
33912        // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
33913        // surface posture. The ctor threads the paired
33914        // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
33915        // return through one `const fn` construction — any future
33916        // accidental downgrade to non-`const` (a `.clone()` on the
33917        // `Copy`-scalar `estrategia:` field expression, an owned-`String`
33918        // materialization on the sibling non-`estrategia:` axis) fails
33919        // `placement_without_clusters_via_const_fn` at caixa-core build
33920        // time with E0015 (`cannot call non-const method`), strictly
33921        // stronger than a runtime `assert!`. Sibling of the peer
33922        // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
33923        // posture on the sibling per-`:politicas` cap-scalar envelopes
33924        // and the peer [`Placement::estrategia`] const-fn accessor pin at
33925        // [`placement_estrategia_accessor_is_const_fn`] on the paired
33926        // substrate primitive.
33927        const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
33928            AplicacaoError::placement_without_clusters(p)
33929        }
33930        let placement = Placement {
33931            estrategia: PlacementStrategy::Sharded,
33932            clusters: vec![],
33933            affinity: None,
33934            shard_key: Some("tenantId".into()),
33935        };
33936        assert_eq!(
33937            placement_without_clusters_via_const_fn(&placement),
33938            AplicacaoError::placement_without_clusters(&placement),
33939        );
33940    }
33941}