Skip to main content

caixa_core/
aplicacao.rs

1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//!   :nome      "checkout"
14//!   :versao    "0.1.0"
15//!   :kind      Aplicacao
16//!   :membros   ((:caixa "catalog"     :versao "^0.1")
17//!               (:caixa "cart"        :versao "^0.1")
18//!               (:caixa "payment"     :versao "^0.2"))
19//!   :contratos ((:de "cart" :para "catalog"
20//!                :wit "wasi:http/proxy" :endpoint "/products/:id")
21//!               (:de "cart" :para "payment"
22//!                :wit "wasi:http/proxy" :endpoint "/charge"))
23//!   :politicas ((:timeout "30s")
24//!               (:retries 3)
25//!               (:circuit-breaker (:max-failures 5 :window "60s"))
26//!               (:mtls-required t))
27//!   :placement (:estrategia replicated
28//!               :clusters   ("rio" "mar" "plo"))
29//!   :entrada   (:host  "checkout.quero.cloud"
30//!               :para  "cart"
31//!               :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55    /// Caller Servico — must reference an entry in the Aplicacao's
56    /// `:membros`. The Servico's caixa.lisp must declare a matching
57    /// `:capabilities` import for the `:wit` world.
58    pub de: String,
59
60    /// Callee Servico — must reference an entry in `:membros`. The
61    /// Servico must declare a matching `:capabilities` export.
62    pub para: String,
63
64    /// WIT world reference — e.g. `"wasi:http/proxy"`,
65    /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66    /// M4 promotes these to a typed enum once the WIT registry
67    /// stabilizes in tatara-lisp.
68    pub wit: String,
69
70    /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub endpoint: Option<String>,
73
74    /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub subject: Option<String>,
77
78    /// Key/value or queue slot, present when `:wit` is store-shaped.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160    let bytes = wit.as_bytes();
161    let mut i = 0;
162    while i < prefixes.len() {
163        let prefix = prefixes[i].as_bytes();
164        if prefix.len() <= bytes.len() {
165            let mut j = 0;
166            let mut matches = true;
167            while j < prefix.len() {
168                if bytes[j] != prefix[j] {
169                    matches = false;
170                    break;
171                }
172                j += 1;
173            }
174            if matches {
175                return true;
176            }
177        }
178        i += 1;
179    }
180    false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320    !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361impl WitContract {
362    /// Substrate-canonical per-`:contratos` caller-Servico scalar
363    /// accessor every consumer that reads the edge's source endpoint
364    /// keys off — returns the author-declared `:contratos :de`
365    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
366    /// own [`String`] storage.
367    ///
368    /// The `:contratos :de` slot names the caller-side member Servico
369    /// on a typed inter-Servico edge (validated by
370    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
371    /// Aplicacao declares — a stray `:de` that doesn't name a member is
372    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
373    /// caller-attachment miss at cluster-apply time). Peer of the
374    /// sibling [`WitContract::destination`] accessor on the same
375    /// per-`:contratos` entry — the pair `( source(), destination() )`
376    /// jointly names the typed edge every renderer that fans on the
377    /// caller-callee identity keys off (the
378    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
379    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
380    /// map, the per-edge dedup key, the per-edge membership-lookup
381    /// diagnostic).
382    ///
383    /// Prior to this lift the `.de` byte-string was accessed inline at
384    /// four caixa-core sites (the two validate-side membership lookups
385    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
386    /// tuple's caller-arm at
387    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
388    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
389    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
390    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
391    /// — five open-coded `.de.as_str()` field-accesses that expressed
392    /// no compile-time link back to the typed slot. A future extension
393    /// of the `:contratos :de` axis to a richer author surface (a
394    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
395    /// canary flow, a per-cluster caller-alias table the operator pins
396    /// through a future `:placement`-scoped slot, the M4
397    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
398    /// admission-webhook that promotes the scalar to a caller-set
399    /// projection) would have had to be threaded through every
400    /// open-coded copy in lockstep or one consumer would silently
401    /// disagree with the peers on which caller Servico a given edge
402    /// resolves to. Lifting the resolution rule to a typed method on
403    /// the substrate primitive means every downstream caller-facing
404    /// consumer reaches for one typed dispatch — the resolver's
405    /// accept-set migrates as a unit on any future axis addition.
406    ///
407    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
408    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
409    /// axis — same "one typed dispatch on the substrate primitive,
410    /// thin projections at each consumer" discipline extended onto the
411    /// per-`:contratos` caller-Servico byte-string axis.
412    ///
413    /// Declared `pub const fn` — the body composes exclusively through
414    /// the `pub const fn` [`String::as_str`] projection (const-stable
415    /// since Rust 1.87, well within the workspace MSRV), so every
416    /// downstream `const`-context consumer of the per-`:contratos`
417    /// caller-Servico byte-string reaches through the same substrate-
418    /// primitive dispatch at const-eval time as at runtime. Peer of
419    /// the sibling `pub const fn` [`Self::destination`] /
420    /// [`Self::world_ref`] scalar accessors on the same
421    /// per-`:contratos` byte-string trio (the family closure the
422    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
423    /// locks load-bearing), and mirror on the method-surface of the
424    /// sibling free-function [`wit_shape_matches`] +
425    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
426    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
427    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
428    /// dispatch family.
429    #[must_use]
430    pub const fn source(&self) -> &str {
431        self.de.as_str()
432    }
433
434    /// Substrate-canonical per-`:contratos` callee-Servico scalar
435    /// accessor every consumer that reads the edge's destination
436    /// endpoint keys off — returns the author-declared
437    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
438    /// from the typed slot's own [`String`] storage.
439    ///
440    /// The `:contratos :para` slot names the callee-side member Servico
441    /// on a typed inter-Servico edge (validated by
442    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
443    /// Aplicacao declares — a stray `:para` that doesn't name a member
444    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
445    /// callee-attachment miss at cluster-apply time). Callee-side twin
446    /// of the sibling [`WitContract::source`] accessor — the pair
447    /// jointly names the typed edge every renderer that fans on the
448    /// caller-callee identity keys off, and this accessor is also the
449    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
450    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
451    /// composes with `destination()` at every emit site that projects a
452    /// per-edge destination Servico's L4 listener port.
453    ///
454    /// Prior to this lift the `.para` byte-string was accessed inline
455    /// at five sites — four caixa-core (the validate-side membership
456    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
457    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
458    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
459    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
460    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
461    /// — with no compile-time link back to the typed slot. A future
462    /// extension of the `:contratos :para` axis to a richer author
463    /// surface (a multi-callee weighted-fan-out overlay for canary /
464    /// blue-green routing on typed edges, a per-cluster callee-alias
465    /// table the operator pins through a future `:placement`-scoped
466    /// slot, the M4 CR materializer's per-CR admission-webhook that
467    /// promotes the scalar to a callee-set projection) would have had
468    /// to be threaded through every open-coded copy in lockstep or one
469    /// consumer would silently disagree on which callee Servico a given
470    /// edge resolves to (a per-CNP `endpointSelector` that names a
471    /// different destination than its L4 port resolver reads for, a
472    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
473    /// as distinct while the adjacency map collapses them, or vice
474    /// versa). Lifting to a typed method on the substrate primitive
475    /// means every downstream callee-facing consumer reaches for one
476    /// typed dispatch.
477    ///
478    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
479    /// (6db982c) accessor — both name the "destination-Servico
480    /// byte-string" concept on their respective mesh-slot atoms (per-
481    /// ingress apex vs. per-typed-edge callee), and both extend the
482    /// substrate-primitive-owns-the-resolver discipline onto the
483    /// per-slot destination-Servico scalar axis. Composes with
484    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
485    /// emit-side per-edge L4 port reader — the composition
486    /// `spec.port_for_destination(c.destination())` pins the CNP per-
487    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
488    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
489    /// `spec.port_for_destination(entrada.destination())`.
490    ///
491    /// Declared `pub const fn` — sibling in `const`-eval posture to the
492    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
493    /// per-`:contratos` byte-string scalar accessors, all three
494    /// projecting through the `pub const fn` [`String::as_str`]
495    /// (const-stable since Rust 1.87). See [`Self::source`] for the
496    /// family-closure rationale.
497    #[must_use]
498    pub const fn destination(&self) -> &str {
499        self.para.as_str()
500    }
501
502    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
503    /// accessor every consumer that reads the edge's WIT world
504    /// discriminator keys off — returns the author-declared
505    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
506    /// the typed slot's own [`String`] storage.
507    ///
508    /// The `:contratos :wit` slot names the WIT world the typed edge
509    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
510    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
511    /// be a well-shaped WIT world reference via
512    /// [`crate::render::is_wit_world_ref`] and by
513    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
514    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
515    /// [`WitContract::source`] / [`WitContract::destination`] accessors
516    /// on the same per-`:contratos` entry — the triple
517    /// `( source(), destination(), world_ref() )` jointly names the
518    /// typed edge every renderer that fans on the caller-callee-shape
519    /// identity keys off (the per-edge dedup key at
520    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
521    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
522    /// [`caixa_mesh::cilium_network_policies`], the
523    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
524    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
525    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
526    ///
527    /// Prior to this lift the `.wit` byte-string was accessed inline at
528    /// five sites — three caixa-core (the `WitContract::is_*` shape-
529    /// dispatch predicates' `&self.wit` arg, the validate-side empty
530    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
531    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
532    /// printer's `{}` format-slot at `c.wit`) — five open-coded
533    /// `.wit` field-accesses that expressed no compile-time link back to
534    /// the typed slot. A future extension of the `:contratos :wit` axis
535    /// to a richer author surface (an M4 promotion from `String` to a
536    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
537    /// lisp per this struct's own `:wit` field docstring, a per-cluster
538    /// WIT-alias table the operator pins through a future
539    /// `:placement`-scoped slot, a canonicalization pass that lowercases
540    /// `wasi:*` prefixes) would have had to be threaded through every
541    /// open-coded copy in lockstep or one consumer would silently
542    /// disagree with the peers on which WIT shape a given edge resolves
543    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
544    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
545    /// empty-check that missed a whitespace-only string a peer accessor
546    /// stripped, or vice versa). Lifting to a typed method on the
547    /// substrate primitive means every downstream WIT-shape-facing
548    /// consumer reaches for one typed dispatch — the resolver's
549    /// accept-set migrates as a unit on any future axis addition.
550    ///
551    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
552    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
553    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
554    /// 6db982c), per-`:membros` [`Membro::nome`] /
555    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
556    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
557    /// on the substrate primitive, thin projections at each consumer"
558    /// discipline extended onto the last unlifted per-`:contratos`
559    /// scalar (the WIT-world-reference arm).
560    ///
561    /// [fag]: caixa-feira/src/cmd/app.rs
562    ///
563    /// Declared `pub const fn` — sibling in `const`-eval posture to the
564    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
565    /// per-`:contratos` byte-string scalar accessors on the trio, and
566    /// the load-bearing enabler for the paired `pub const fn`
567    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
568    /// [`Self::is_capability`] WIT-shape-predicate family (each
569    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
570    /// the `const`-eval posture by construction once this accessor
571    /// carries it). See [`Self::source`] for the family-closure
572    /// rationale and the paired
573    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
574    /// for the load-bearing witness.
575    #[must_use]
576    pub const fn world_ref(&self) -> &str {
577        self.wit.as_str()
578    }
579
580    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
581    /// payload-target scalar accessor every consumer that reads the
582    /// edge's L7 HTTP request path payload keys off — returns the
583    /// author-declared `:contratos :endpoint` byte-string verbatim as
584    /// an `Option<&str>`, borrowed from the typed slot's own
585    /// `Option<String>` storage; `None` when the slot is absent (the
586    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
587    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
588    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
589    /// [`WitTarget::Capability`] edge carries none of the three).
590    ///
591    /// The `:contratos :endpoint` slot carries the HTTP request path
592    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
593    /// — same shape required of `:entrada :paths`, gated by the shared
594    /// [`crate::render::is_gateway_api_http_path`] predicate) that
595    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
596    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
597    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
598    /// downstream consumer that reads the payload keys off this scalar
599    /// (the [`WitContract::target`] Http-arm payload extraction that
600    /// materializes [`WitTarget::Http { endpoint }`] under the paired
601    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
602    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
603    /// key's endpoint arm that pins the payload as part of the six-tuple
604    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
605    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
606    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
607    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
608    /// emission path that lands the payload verbatim as a Cilium L7
609    /// `path:` rule).
610    ///
611    /// Prior to this lift the `.endpoint` field was accessed inline at
612    /// two production sites in `caixa-core/src/aplicacao.rs` — the
613    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
614    /// self.endpoint.as_deref();` binding at the top of the method, and
615    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
616    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
617    /// field-accesses that expressed no compile-time link back to the
618    /// typed slot. A future extension of the `:contratos :endpoint`
619    /// axis to a richer author surface (an M4 promotion from
620    /// `Option<String>` to a typed HTTP path-template enum once the
621    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
622    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
623    /// alias table the operator pins through a future `:placement`-
624    /// scoped slot, a canonicalization pass that percent-encodes non-
625    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
626    /// materializer applies per-tenant) would have had to be threaded
627    /// through both open-coded copies in lockstep or the two consumers
628    /// would silently disagree on which HTTP path a given edge resolves
629    /// to — the [`WitContract::target`] payload-extraction reading
630    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
631    /// the operator-resolved `"/tenant-a/lookup"` would silently split
632    /// the [`WitTarget::Http`]-arm rendered payload from the actual
633    /// dedup-key uniqueness axis, a two-consumer split at the validator
634    /// far from the source `caixa.lisp` with no field naming the
635    /// payload-drift root cause. Lifting the resolution rule to a typed
636    /// method on the substrate primitive means every downstream
637    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
638    /// L7-payload surface reaches for exactly one typed dispatch — the
639    /// resolver's accept-set migrates as a unit on any future axis
640    /// addition.
641    ///
642    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
643    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
644    /// accessors on the M3 mesh-slot family — same "one typed dispatch
645    /// on the substrate primitive, thin projections at each consumer"
646    /// discipline extended onto the per-`:contratos` HTTP-shaped
647    /// payload-carrier `Option<String>` optional-scalar axis. First
648    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
649    /// atom — opens the "optional per-slot payload-carrier scalar"
650    /// projection pattern the sibling per-`:contratos` `:subject` /
651    /// `:slot` future lifts fold on, matching the closed
652    /// per-`:contratos` scalar-value accessor family
653    /// ([`WitContract::source`] / [`WitContract::destination`] /
654    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
655    /// scalar `String` axes. Named `endpoint()` to match the storage
656    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
657    /// author-facing label const; the accessor's identity name maps
658    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
659    /// docstring already carries.
660    #[must_use]
661    pub const fn endpoint(&self) -> Option<&str> {
662        match &self.endpoint {
663            Some(s) => Some(s.as_str()),
664            None => None,
665        }
666    }
667
668    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
669    /// payload-target scalar accessor every consumer that reads the
670    /// edge's NATS / Kafka publish subject payload keys off — returns
671    /// the author-declared `:contratos :subject` byte-string verbatim
672    /// as an `Option<&str>`, borrowed from the typed slot's own
673    /// `Option<String>` storage; `None` when the slot is absent (the
674    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
675    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
676    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
677    /// [`WitTarget::Capability`] edge carries none of the three).
678    ///
679    /// The `:contratos :subject` slot carries the NATS / Kafka publish
680    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
681    /// per-edge target selector — `orders.paid`, `events.>`, whatever
682    /// subject namespace the author names on the pub-sub edge) that
683    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
684    /// arm's `subject: &'a str` payload when the edge's `:wit` world
685    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
686    /// downstream consumer that reads the payload keys off this scalar
687    /// (the [`WitContract::target`] PubSub-arm payload extraction that
688    /// materializes [`WitTarget::PubSub { subject }`] under the paired
689    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
690    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
691    /// key's subject arm that pins the payload as part of the six-tuple
692    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
693    /// future M4 per-edge WIT registry resolver's pub-sub-arm
694    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
695    /// materializer's per-edge NATS admission webhook, the future
696    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
697    /// as a NATS subject the operator pins per-CR).
698    ///
699    /// Prior to this lift the `.subject` field was accessed inline at
700    /// two production sites in `caixa-core/src/aplicacao.rs` — the
701    /// [`WitContract::target`] payload-shape dispatch's `let subject =
702    /// self.subject.as_deref();` binding at the top of the method, and
703    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
704    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
705    /// field-accesses that expressed no compile-time link back to the
706    /// typed slot. A future extension of the `:contratos :subject` axis
707    /// to a richer author surface (an M4 promotion from `Option<String>`
708    /// to a typed NATS-subject-template enum once the WIT registry
709    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
710    /// struct's own `:wit` field docstring, a per-cluster subject-alias
711    /// table the operator pins through a future `:placement`-scoped
712    /// slot, a canonicalization pass that lowercases / dedupes wildcard
713    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
714    /// applies per-tenant) would have had to be threaded through both
715    /// open-coded copies in lockstep or the two consumers would silently
716    /// disagree on which NATS subject a given edge resolves to — the
717    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
718    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
719    /// resolved `"tenant-a.orders.paid"` would silently split the
720    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
721    /// key uniqueness axis, a two-consumer split at the validator far
722    /// from the source `caixa.lisp` with no field naming the payload-
723    /// drift root cause. Lifting the resolution rule to a typed method
724    /// on the substrate primitive means every downstream pub-sub-payload-
725    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
726    /// surface reaches for exactly one typed dispatch — the resolver's
727    /// accept-set migrates as a unit on any future axis addition.
728    ///
729    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
730    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
731    /// carrier axis — second `Option<&str>`-return accessor on the
732    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
733    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
734    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
735    /// key/value-store arm as the last unlifted per-`:contratos`
736    /// `Option<String>` axis. Named `subject()` to match the storage
737    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
738    /// author-facing label const; the accessor's identity name maps
739    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
740    /// docstring already carries.
741    #[must_use]
742    pub const fn subject(&self) -> Option<&str> {
743        match &self.subject {
744            Some(s) => Some(s.as_str()),
745            None => None,
746        }
747    }
748
749    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
750    /// shaped payload-target scalar accessor every consumer that reads
751    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
752    /// off — returns the author-declared `:contratos :slot` byte-string
753    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
754    /// own `Option<String>` storage; `None` when the slot is absent
755    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
756    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
757    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
758    /// [`WitTarget::Capability`] edge carries none of the three).
759    ///
760    /// The `:contratos :slot` slot carries the key/value store
761    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
762    /// arm's per-edge target selector — `carts/{cart_id}`,
763    /// `sessions/{tenant}/{sid}`, whatever key-template the author
764    /// names on the store edge) that [`WitContract::target`] projects
765    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
766    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
767    /// accept-set. Every downstream consumer that reads the payload
768    /// keys off this scalar (the [`WitContract::target`] Store-arm
769    /// payload extraction that materializes [`WitTarget::Store { slot }`]
770    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
771    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
772    /// key's store arm that pins the payload as part of the six-tuple
773    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
774    /// the future M4 per-edge WIT registry resolver's store-arm
775    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
776    /// materializer's per-edge key/value admission webhook, the future
777    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
778    /// as a key-template the operator pins per-CR).
779    ///
780    /// Prior to this lift the `.slot` field was accessed inline at two
781    /// production sites in `caixa-core/src/aplicacao.rs` — the
782    /// [`WitContract::target`] payload-shape dispatch's `let slot =
783    /// self.slot.as_deref();` binding at the top of the method, and
784    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
785    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
786    /// field-accesses that expressed no compile-time link back to the
787    /// typed slot. A future extension of the `:contratos :slot` axis
788    /// to a richer author surface (an M4 promotion from `Option<String>`
789    /// to a typed key-template enum once the WIT registry stabilizes
790    /// key-template parameter shapes in tatara-lisp per this struct's
791    /// own `:wit` field docstring, a per-cluster slot-alias table the
792    /// operator pins through a future `:placement`-scoped slot, a
793    /// canonicalization pass that lowercases the bucket prefix, a
794    /// per-CR fully-qualified rewrite the M4 CR materializer applies
795    /// per-tenant) would have had to be threaded through both
796    /// open-coded copies in lockstep or the two consumers would
797    /// silently disagree on which key-template a given edge resolves
798    /// to — the [`WitContract::target`] payload-extraction reading
799    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
800    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
801    /// would silently split the [`WitTarget::Store`]-arm rendered
802    /// payload from the actual dedup-key uniqueness axis, a
803    /// two-consumer split at the validator far from the source
804    /// `caixa.lisp` with no field naming the payload-drift root cause.
805    /// Lifting the resolution rule to a typed method on the substrate
806    /// primitive means every downstream store-payload-facing consumer
807    /// of the Aplicacao's per-`:contratos` payload surface reaches for
808    /// exactly one typed dispatch — the resolver's accept-set migrates
809    /// as a unit on any future axis addition.
810    ///
811    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
812    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
813    /// accessors on the M3 mesh-slot payload-carrier axis — third and
814    /// final `Option<&str>`-return accessor on the per-`:contratos`
815    /// mesh-slot atom, closes the last unlifted per-`:contratos`
816    /// `Option<String>` axis and completes the "optional per-slot
817    /// payload-carrier scalar" projection pattern the peer HTTP /
818    /// pub-sub arms established across the three payload-shape
819    /// dispatch arms. Named `slot()` to match the storage field's
820    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
821    /// author-facing label const; the accessor's identity name maps
822    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
823    /// docstring already carries.
824    #[must_use]
825    pub const fn slot(&self) -> Option<&str> {
826        match &self.slot {
827            Some(s) => Some(s.as_str()),
828            None => None,
829        }
830    }
831
832    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
833    /// caller-callee-pair accessor every consumer that constructs an
834    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
835    /// caller-callee pair keys off — returns the author-declared
836    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
837    /// owned `(String, String)` tuple, projected through the lifted
838    /// [`WitContract::source`] / [`WitContract::destination`] scalar
839    /// accessors so any future rebrand on the caller-arm / callee-arm
840    /// projection axis (an M4 per-cluster caller-alias table the
841    /// operator pins through a future `:placement`-scoped slot, a
842    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
843    /// a per-`:membros` alias overlay from the future `:membros
844    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
845    /// acknowledges) reaches every diagnostic-construction site by
846    /// construction.
847    ///
848    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
849    /// owned form" primitive every per-`:contratos` diagnostic variant on
850    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
851    /// nine variants [`AplicacaoError::EmptyWit`],
852    /// [`AplicacaoError::ContratoEndpointEmpty`],
853    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
854    /// [`AplicacaoError::ContratoEndpointInvalid`],
855    /// [`AplicacaoError::ContratoSubjectEmpty`],
856    /// [`AplicacaoError::ContratoSubjectInvalid`],
857    /// [`AplicacaoError::ContratoSlotEmpty`],
858    /// [`AplicacaoError::ContratoSlotInvalid`], and
859    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
860    /// para: String` field pair the constructor site reads verbatim off
861    /// the [`WitContract`] the diagnostic points at, so a diagnostic
862    /// whose `de:` and `para:` labels silently drift off the source
863    /// caller/callee — a per-cluster caller-alias rewrite that landed on
864    /// one variant's inline `de: c.de.clone()` field access but not on
865    /// its sibling variant's, an accidental swap of the `de:` and `para:`
866    /// arms in a copy-paste of the constructor block — would emit a
867    /// build-time error whose "which caixa is at fault" question the
868    /// operator answers wrongly, far from the source `caixa.lisp`.
869    ///
870    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
871    /// pair was inlined at seven [`WitContract::target`] error-
872    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
873    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
874    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
875    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
876    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
877    /// the [`AplicacaoError::ContratoSlotEmpty`] /
878    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
879    /// two [`AplicacaoSpec::validate`] error-construction sites (the
880    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
881    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
882    /// insert-first-seen closure) — nine open-coded `.de.clone() +
883    /// .para.clone()` pairs that expressed no compile-time contract that
884    /// the caller-arm and callee-arm arms of the same diagnostic
885    /// construction reach for the same [`WitContract`] instance or that
886    /// the `de:` and `para:` label pair binds to the fields the author
887    /// declared. Any future rebrand on the axis — an M4 per-cluster
888    /// caller/callee-alias rewrite the operator pins through a future
889    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
890    /// per-CR fully-qualified namespace prefix the M4
891    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
892    /// per-tenant, a canonicalization pass that lowercases the caller +
893    /// callee identifiers post-parse — would have had to be threaded
894    /// through every open-coded copy in lockstep or one variant's
895    /// diagnostic would silently name a different caller/callee pair
896    /// than its peer, silently degrading the "which caixa is at fault"
897    /// self-locating signal every operator-facing typed diagnostic
898    /// exists to carry. Lifting the pair to a typed method on the
899    /// substrate primitive means every downstream diagnostic-construction
900    /// site reaches for exactly one typed dispatch — the resolver's
901    /// projection migrates as a unit on any future axis addition.
902    ///
903    /// Peer of the sibling per-`:contratos` scalar accessor family
904    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
905    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
906    /// scalar-value axes — first composite-projection accessor on the
907    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
908    /// form `.clone()` field-accesses that pair the sibling
909    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
910    /// one typed dispatch. Named `edge_pair()` to reflect the identity
911    /// name of the projected tuple (the typed-edge caller-callee pair,
912    /// distinct from the sibling triple-projection
913    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
914    /// closure in [`WitContract::target`] + the paired
915    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
916    /// site's `(de, para, wit)` triple onto one typed dispatch).
917    #[must_use]
918    pub fn edge_pair(&self) -> (String, String) {
919        (self.source().to_string(), self.destination().to_string())
920    }
921
922    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
923    /// :wit)` triple every per-edge diagnostic constructor that names
924    /// all three axes threads verbatim into its `de:` / `para:` /
925    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
926    /// / missing-target / invalid-wit / capability-with-payload arms
927    /// (eight sites all shape `let (de, para, wit) = edge();
928    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
929    /// accessor landed) and the sibling
930    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
931    /// constructor (which paired `edge_pair()` for the `(de, para)`
932    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
933    /// typed-dispatch + raw-field-access shape the sibling accessor
934    /// family already flagged as a drift risk). Nine total call sites
935    /// collapse onto this helper.
936    ///
937    /// Lifted with the same one-source-of-truth discipline
938    /// [`WitContract::edge_pair`] carries on the paired
939    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
940    /// arms compose through the lifted [`WitContract::source`] /
941    /// [`WitContract::destination`] / [`WitContract::world_ref`]
942    /// scalar accessors byte-for-byte (pinned by the paired
943    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
944    /// composition-pin), so any future rebrand on the per-`:contratos`
945    /// caller / callee / world-ref axis (an M4 per-cluster
946    /// caller/callee-alias rewrite the operator pins through a future
947    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
948    /// per-CR fully-qualified namespace prefix the M4
949    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
950    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
951    /// on `source()` / `destination()`, a per-CR canonicalization pass
952    /// that lowercases the WIT world ref post-parse) migrates as a
953    /// single caixa-core edit rather than a coordinated rewrite of
954    /// nine open-coded triple-constructors.
955    ///
956    /// Peer of the sibling per-`:contratos` composite-projection
957    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
958    /// composite-value axes — closes the last unlifted owned-form
959    /// composite-tuple axis on the per-`:contratos` diagnostic-
960    /// construction surface. Named `edge_triple()` to reflect the
961    /// identity name of the projected tuple (the typed-edge
962    /// caller-callee-wit triple, sibling to the caller-callee-only
963    /// pair `edge_pair()` returns).
964    #[must_use]
965    pub fn edge_triple(&self) -> (String, String, String) {
966        (
967            self.source().to_string(),
968            self.destination().to_string(),
969            self.world_ref().to_string(),
970        )
971    }
972
973    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
974    /// dedups typed edges keys off — routes through the lifted
975    /// [`WitContract::source`] / [`WitContract::destination`] /
976    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
977    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
978    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
979    /// type alias's six axes migrate as a unit on any future axis
980    /// addition (adding a seventh field to [`WitContract`] is one
981    /// [`ContratoIdentity`] alias edit + one accessor addition + one
982    /// arm here, not a coordinated rewrite of every open-coded
983    /// six-tuple builder that dedups on the identity axis).
984    ///
985    /// Sibling of [`WitContract::edge_pair`] /
986    /// [`WitContract::edge_triple`] on the composite-projection axis:
987    /// the pair projects the caller-callee axes, the triple extends it
988    /// with the world-ref, this method extends it with the three
989    /// payload-carrier axes. Every projection returns the same six
990    /// scalar accessors' outputs; the three methods differ only in
991    /// which arms they surface.
992    ///
993    /// Declared `pub const fn` — every callee is itself `pub const fn`
994    /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
995    /// project through `pub const fn` [`String::as_str`], const-stable
996    /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
997    /// [`Self::slot`] project through the same `String::as_str` under a
998    /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
999    /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1000    /// closed the const-eval surface on) and tuple construction from
1001    /// borrowed-reference / `Option`-of-borrowed-reference arms is
1002    /// itself trivially const. The `ContratoIdentity<'_>` alias
1003    /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1004    /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1005    /// no heap allocation, no non-const call folded through the tuple's
1006    /// construction. Sibling in `const`-eval posture to the peer
1007    /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1008    /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1009    /// composite-projection family the sibling
1010    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1011    /// already anchors — this extends the same `const`-eval-surface
1012    /// posture onto the peer six-arm composite-projection axis where
1013    /// the projection surfaces the full identity tuple rather than a
1014    /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1015    /// bearing by
1016    /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1017    /// (a future accidental downgrade fires E0015 at the wrapper at
1018    /// caixa-core build time).
1019    #[must_use]
1020    pub const fn identity(&self) -> ContratoIdentity<'_> {
1021        (
1022            self.source(),
1023            self.destination(),
1024            self.world_ref(),
1025            self.endpoint(),
1026            self.subject(),
1027            self.slot(),
1028        )
1029    }
1030
1031    /// True when this contract targets an HTTP-shaped WIT world.
1032    ///
1033    /// Declared `pub const fn` — routes through the paired `pub const
1034    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1035    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1036    /// (d46420c). Sibling in `const`-eval posture to the peer
1037    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1038    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1039    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1040    /// the same `const`-eval-surface posture as the free-function
1041    /// classifier family it composes through. Pinned load-bearing by
1042    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1043    /// test (a future accidental downgrade to non-`const` fires E0015
1044    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1045    /// build time).
1046    #[must_use]
1047    pub const fn is_http(&self) -> bool {
1048        wit_shape_is_http(self.world_ref())
1049    }
1050
1051    /// True when this contract targets a pub-sub-shaped WIT world.
1052    ///
1053    /// Declared `pub const fn` — sibling in `const`-eval posture to
1054    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1055    /// [`Self::is_capability`] WIT-shape-predicate family. See
1056    /// [`Self::is_http`] for the family-closure rationale.
1057    #[must_use]
1058    pub const fn is_pubsub(&self) -> bool {
1059        wit_shape_is_pubsub(self.world_ref())
1060    }
1061
1062    /// True when this contract targets a key/value-shaped WIT world.
1063    ///
1064    /// Declared `pub const fn` — sibling in `const`-eval posture to
1065    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1066    /// [`Self::is_capability`] WIT-shape-predicate family. See
1067    /// [`Self::is_http`] for the family-closure rationale.
1068    #[must_use]
1069    pub const fn is_store(&self) -> bool {
1070        wit_shape_is_store(self.world_ref())
1071    }
1072
1073    /// True when this contract targets *none* of the three known payload-
1074    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1075    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1076    /// open on the [`WitContract`] surface. Returns the exact-inverse
1077    /// disjunction of the peer trio — `true` when none of the three
1078    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1079    /// author-declared WIT world is a pure typed capability edge with no
1080    /// payload selector (the shape [`WitContract::target`] projects onto
1081    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1082    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1083    ///
1084    /// The `:contratos :wit` shape-space is closed at four arms
1085    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1086    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1087    /// everything else on the payload-less capability arm), and every
1088    /// downstream consumer that must filter contratos by shape-class
1089    /// keys off the four sibling predicates (the [`WitContract::target`]
1090    /// dispatch's implicit `else` after the three payload-shape arm
1091    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1092    /// every future substrate-side capability-shape-only emitter — the
1093    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1094    /// future `feira app graph --capability` per-Aplicacao capability-
1095    /// column filter, the future per-cluster capability-scope reconciler
1096    /// that skips L4/L7 emission for payload-less edges since Cilium
1097    /// can't introspect WASI capability calls, the future
1098    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1099    /// shape shape-count histogram). Every such consumer reaches for one
1100    /// typed dispatch on the substrate primitive so the "which arm
1101    /// carries the capability-only shape?" answer lives at one caixa-core
1102    /// edit rather than open-coded across per-consumer
1103    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1104    /// negations, each of which would silently drop a future fourth
1105    /// payload-arm addition without a compile-time signal at the
1106    /// consumer site.
1107    ///
1108    /// Prior to this lift the "not one of the three known payload
1109    /// shapes" classification sat inline at [`WitContract::target`]'s
1110    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1111    /// [`WitTarget::Capability`] admission arm after the three `if
1112    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1113    /// { … }` guards) with no named accessor for downstream consumers
1114    /// to reach through. A future substrate-side capability-only
1115    /// filter or a future capability-scope reconciler would have had to
1116    /// re-inline the same triplet negation at every emit site with no
1117    /// compile-time link back to the sibling trio, and a future arm
1118    /// addition (a hypothetical fourth payload-shape prefix set — a
1119    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1120    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1121    /// trajectory bullet) would land the new predicate on the payload-
1122    /// carrying trio and silently misclassify the new shape as
1123    /// capability at every triplet-negation consumer site, propagating
1124    /// the drift far from the caixa-core prefix-set commit.
1125    ///
1126    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1127    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1128    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1129    /// axis, mirroring the paired post-projection [`WitTarget`]
1130    /// `gen_platform::IsVariant`-derived 4-way predicate set
1131    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1132    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1133    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1134    /// arm-set). The two typed axes — pre-projection on the raw
1135    /// `:contratos :wit` string, post-projection on the validated typed
1136    /// view — now carry a matched 4-arm predicate discipline: every
1137    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1138    /// predicate on the [`WitContract`] surface, and any future
1139    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1140    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1141    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1142    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1143    /// pre-projection axis through a matching peer prefix-set + peer
1144    /// predicate lift by construction — the compile-time exhaustiveness
1145    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1146    /// the post-projection accessor family stays in sync, and the sibling
1147    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1148    /// partition-witness pin locks the pre-projection classification in
1149    /// load-bearing so a peer prefix-set addition that widened one arm's
1150    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1151    /// surfaces as a test failure at caixa-core build time rather than a
1152    /// silent per-consumer split at renderer emit time.
1153    ///
1154    /// Composes byte-for-byte through the lifted peer trio
1155    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1156    /// any future rebrand of any prefix-set const flows through this
1157    /// method by construction without a coordinated per-consumer rewrite
1158    /// (pinned by the sibling
1159    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1160    /// composition-witness).
1161    ///
1162    /// Note: purely syntactic classification on the `:wit` prefix-set —
1163    /// unlike [`Self::target`], which additionally rejects value-shape-
1164    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1165    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1166    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1167    /// structurally malformed returns `true` from `is_capability()` (the
1168    /// prefix set matches nothing), and the surrounding
1169    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1170    /// is where the [`AplicacaoError::EmptyWit`] /
1171    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1172    /// predicate is the classifier, not the validator.
1173    ///
1174    /// Declared `pub const fn` — closes the WIT-shape-predicate
1175    /// family's `const`-eval-surface pass at the fourth (payload-less)
1176    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1177    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1178    /// See [`Self::is_http`] for the family-closure rationale.
1179    #[must_use]
1180    pub const fn is_capability(&self) -> bool {
1181        wit_shape_is_capability(self.world_ref())
1182    }
1183
1184    /// True when this contract's caller equals its callee — a
1185    /// structurally degenerate typed edge that no `:contratos` entry can
1186    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1187    /// Servico B" is an *inter*-Servico contract between two distinct
1188    /// graph nodes). A Servico contracting with itself resolves to an
1189    /// in-process call the wasm-engine never routes through the mesh at
1190    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1191    /// per-edge policy can express the intended shape — the pub-sub
1192    /// path silently rendered a self-allow rule that is a no-op (intra-
1193    /// pod traffic bypasses the mesh entirely), and the synchronous
1194    /// paths surfaced as a misleading `ContratoCycle` whose path was
1195    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1196    /// deadlock. Every downstream consumer that must reject the shape
1197    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1198    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1199    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1200    /// axis, every future adjacency-graph builder that must skip self-
1201    /// edges rather than fold them into an incidental cycle) now keys
1202    /// off exactly one typed dispatch on the substrate primitive, so
1203    /// any future rebrand on the axis (an M4-typed-caller enum whose
1204    /// identity comparison rule the accessor could route through, an
1205    /// operator-side per-cluster caller/callee-alias table the
1206    /// materializer resolves per-CR before the equality probe, a
1207    /// promotion of the pointwise `==` to a set-membership check once
1208    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1209    /// so a per-replica self-edge is rejected under the same predicate)
1210    /// migrates as a single caixa-core edit rather than a coordinated
1211    /// rewrite of every downstream self-edge consumer. Composes
1212    /// byte-for-byte through the lifted [`Self::source`] /
1213    /// [`Self::destination`] scalar accessors — the accessor pair every
1214    /// per-`:contratos` scalar-value axis already routes through — so
1215    /// any future rebrand of the underlying `:de` / `:para` storage
1216    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1217    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1218    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1219    /// same one body without a coordinated per-consumer rewrite.
1220    ///
1221    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1222    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1223    /// on the `:wit` world-ref axis — extended onto the per-edge
1224    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1225    /// partition the WIT-shape-space; `is_self_loop` partitions the
1226    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1227    /// the graph-theoretic identity of the shape (a loop from a graph
1228    /// node to itself, distinct from the sibling multi-node
1229    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1230    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1231    /// variant already carrying the term.
1232    ///
1233    /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
1234    /// shape-predicate on the substrate's `const`-eval surface. The peer
1235    /// per-`:contratos` shape-predicate family [`Self::is_http`] /
1236    /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
1237    /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
1238    /// posture on the WIT-world-ref classifier axis; this lift extends it
1239    /// onto the peer caller-callee identity-space predicate. The body
1240    /// projects the `:de` / `:para` `String` storage through the sibling
1241    /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
1242    /// accessors, then compares the resulting `&str` byte-slices under a
1243    /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
1244    /// const-stable since Rust 1.39), primitive-`usize` `!=` on
1245    /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
1246    /// — every operation `const`-eval-callable on stable Rust, no
1247    /// iterator methods, no `PartialEq for str` trait dispatch (which
1248    /// remains non-`const` on stable). Mirrors the peer `pub const fn`
1249    /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
1250    /// loop verbatim on the paired-slice-equality shape. Every downstream
1251    /// substrate-side `const`-context consumer of the per-`:contratos`
1252    /// self-edge partition (a future `const _: () = assert!(…)` module-
1253    /// scope invariant pin over a per-fixture typed [`WitContract`] once
1254    /// the type's carriers admit `const`-context construction, a future
1255    /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
1256    /// composer that fans on the identity-space partition at compile
1257    /// time) reaches through the same typed dispatch on the substrate
1258    /// primitive at const-eval time as at runtime. Pinned by
1259    /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
1260    /// witnesses the `const`-eval posture via a `const fn` wrapper so any
1261    /// future accidental downgrade to non-`const` trips at caixa-core
1262    /// build time with E0015 (`cannot call non-const method`), strictly
1263    /// stronger than a runtime `assert!`.
1264    #[must_use]
1265    pub const fn is_self_loop(&self) -> bool {
1266        // Compose through the paired `pub const fn` [`Self::source`] /
1267        // [`Self::destination`] scalar accessors so any future rebrand of
1268        // the underlying `:de` / `:para` storage (a lift from `String` to
1269        // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
1270        // arena the M4 CR materializer authors, a `smol_str::SmolStr`
1271        // inline-buffer swap) flows through the same one body without a
1272        // coordinated per-consumer rewrite. Peer of the sibling
1273        // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1274        // [`Self::is_capability`] shape-predicate family — each of which
1275        // composes through the paired [`Self::world_ref`] scalar accessor
1276        // onto the peer `pub const fn` [`wit_shape_is_http`] /
1277        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
1278        // [`wit_shape_is_capability`] free-function classifier — the same
1279        // "typed dispatch composes with typed dispatch, not raw field
1280        // access" discipline extended onto the caller-callee identity-
1281        // space partition. Pinned by
1282        // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
1283        // above.
1284        let a = self.source().as_bytes();
1285        let b = self.destination().as_bytes();
1286        if a.len() != b.len() {
1287            return false;
1288        }
1289        // Manual byte-level equality loop — mirrors the peer
1290        // [`wit_shape_matches`] combinator's manual `starts_with` loop
1291        // verbatim on the paired-slice-equality shape. `PartialEq for
1292        // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
1293        // trait dispatch it routes through is not `const`), so a naive
1294        // `self.source() == self.destination()` body would trip on
1295        // `const`-eval-callability; the byte-slice loop dispatches
1296        // through primitive-`u8` `!=`, primitive-`usize` comparison, and
1297        // const-stable slice indexing (since Rust 1.79) — every
1298        // operation `const`-eval-callable on stable.
1299        let mut i = 0;
1300        while i < a.len() {
1301            if a[i] != b[i] {
1302                return false;
1303            }
1304            i += 1;
1305        }
1306        true
1307    }
1308
1309    /// Reject a `:contratos` entry whose `:de` or `:para` names a
1310    /// caixa the `:membros` graph does not contain — the substrate-
1311    /// primitive per-edge graph-membership gate every consumer of the
1312    /// typed inter-Servico edge's endpoint-resolution axis reaches
1313    /// through one dispatch.
1314    ///
1315    /// A `:contratos` entry is a typed directed edge between two
1316    /// declared members (MESH-COMPOSITION §III.1 — "the typed edges
1317    /// address graph nodes, so a reference to a node the graph does
1318    /// not contain is a build error"). Both endpoints must resolve
1319    /// against the same [`AplicacaoSpec::membro_names`] oracle: the
1320    /// paired [`AplicacaoError::ContratoMemberMissing`] diagnostic
1321    /// framing does not distinguish `:de` from `:para` (both arms
1322    /// carry the offending `caixa` name verbatim without a
1323    /// slot-discriminator field, unlike the sibling per-arm shape
1324    /// gate [`validate_contrato_caixa`] whose paired
1325    /// [`AplicacaoError::ContratoCaixaEmpty`] / `ContratoCaixaInvalid`
1326    /// variants each carry a `slot: &'static str` tag). So the two
1327    /// arms are byte-identical modulo the accessor projection they
1328    /// key off, and folding them into one per-edge dispatch preserves
1329    /// every existing diagnostic-fired output byte-for-byte while
1330    /// closing the last inline duplication the substrate-primitive
1331    /// per-edge gate family carried inside
1332    /// [`AplicacaoSpec::validate_contratos`].
1333    ///
1334    /// Routes through the paired [`Self::source`] / [`Self::destination`]
1335    /// scalar accessors so every future rebrand of the underlying
1336    /// `:de` / `:para` storage (a lift from `String` to a typed
1337    /// `ServicoName(String)` newtype, a per-Aplicacao interning arena
1338    /// the M4 CR materializer authors, a per-cluster caller-alias
1339    /// table the operator pins through a future `:placement`-scoped
1340    /// slot, an M4 promotion from `String` to a typed edge-endpoint
1341    /// enum) flows through the same body without a coordinated
1342    /// per-consumer rewrite. Peer of the sibling per-edge substrate
1343    /// primitives already lifted on the same `impl WitContract`
1344    /// surface ([`Self::is_self_loop`] on the identity-space arm,
1345    /// [`Self::target`] on the payload-shape ↔ target-consistency
1346    /// arm, [`Self::identity`] on the dedup-key arm) — this run
1347    /// extends the shape to the last per-edge axis
1348    /// [`AplicacaoSpec::validate_contratos`] carried as an inline
1349    /// twin-arm cascade.
1350    ///
1351    /// Every future consumer that wants to re-check *one* edge's
1352    /// graph-membership reaches through one call: the M4
1353    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
1354    /// admission-webhook re-checking `:contratos` after a
1355    /// per-`(:de, :para)` edge patch without re-walking the whole
1356    /// `:contratos` list, the per-`:contratos`-edge `:politicas`
1357    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
1358    /// resolves an effective per-edge [`MeshPolicy`] and must
1359    /// re-check the edge's endpoints against the same membership
1360    /// oracle before it can key a per-edge override off the endpoint
1361    /// tuple. Pre-lift each such consumer was structurally forced to
1362    /// either re-inline the twin `if !names.contains(...)` cascade
1363    /// (the duplication the PRIME DIRECTIVE names as a bug) or call
1364    /// [`AplicacaoSpec::validate_contratos`] and pay a whole-list
1365    /// walk to re-check one edge. Post-lift each reaches the axis
1366    /// through one dispatch on the substrate primitive.
1367    ///
1368    /// `:de` runs before `:para` per the canonical edge-direction
1369    /// order the sibling per-arm shape gate
1370    /// [`validate_contrato_caixa`] arm ordering, the self-loop
1371    /// diagnostic string, and every peer arm ordering in
1372    /// [`AplicacaoSpec::validate_contratos`] already use — a
1373    /// well-shaped-but-phantom `:de` fires before a well-shaped-but-
1374    /// phantom `:para`, preserving byte-equal ordering with the
1375    /// pre-lift inline cascade.
1376    fn require_endpoints_in(
1377        &self,
1378        names: &std::collections::HashSet<&str>,
1379    ) -> Result<(), AplicacaoError> {
1380        if !names.contains(self.source()) {
1381            return Err(AplicacaoError::contrato_member_missing(self.source()));
1382        }
1383        if !names.contains(self.destination()) {
1384            return Err(AplicacaoError::contrato_member_missing(self.destination()));
1385        }
1386        Ok(())
1387    }
1388
1389    /// Typed view of the contract's payload target. Enforces that the
1390    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1391    /// fields agree, and that each carried value is itself
1392    /// value-shape valid:
1393    ///
1394    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1395    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1396    ///     `PathPrefix` invariant — same shape required of `:entrada
1397    ///     :paths`)
1398    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1399    ///     non-empty (NATS / Kafka publish without a subject is a
1400    ///     no-op subscribe, never the author's intent)
1401    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1402    ///     non-empty (an empty slot template addresses the bucket
1403    ///     root, defeating the per-key isolation the slot exists for)
1404    ///   - Anything else ⇒ none of the three; the contract is a pure
1405    ///     typed capability edge with no payload selector.
1406    ///
1407    /// Translates the Apollo Federation discipline ("conflicts are
1408    /// errors at compile time, not warnings at runtime";
1409    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1410    /// a contract whose WIT shape disagrees with its target field, or
1411    /// whose target field carries a value-shape-invalid string, is a
1412    /// build error — not a silent renderer drop. The returned
1413    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1414    /// non-empty (and absolute, for `Http`); every downstream consumer
1415    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1416    /// the M4 per-edge policy resolver) can rely on that without
1417    /// re-checking.
1418    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1419        // Route the HTTP-shaped payload-target extraction through the
1420        // lifted [`WitContract::endpoint`] accessor rather than the raw
1421        // `self.endpoint.as_deref()` field access — the two production
1422        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1423        // payload-carrier scalar (this method's Http-arm payload
1424        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1425        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1426        // off exactly one typed dispatch on the substrate primitive, so
1427        // any future rebrand on the axis (an M4 per-cluster endpoint-
1428        // alias rewrite, a per-CR fully-qualified path prefix the M4
1429        // materializer applies per-tenant, an M4 promotion from
1430        // `Option<String>` to a typed HTTP path-template enum) migrates
1431        // as a single caixa-core edit rather than a coordinated rewrite
1432        // of the two call sites — peer of the sibling M3 per-`:placement`
1433        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1434        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1435        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1436        let endpoint = self.endpoint();
1437        let subject = self.subject();
1438        // Route the store-arm payload-carrier scalar through the
1439        // lifted [`WitContract::slot`] accessor rather than the raw
1440        // `self.slot.as_deref()` field access — the two production
1441        // consumers of the per-`:contratos :slot` key/value-store-
1442        // shaped payload-carrier scalar (this method's Store-arm
1443        // payload extraction, the [`AplicacaoSpec::validate`]
1444        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1445        // arm) now key off exactly one typed dispatch on the substrate
1446        // primitive. Closes the last unlifted per-`:contratos`
1447        // `Option<String>` axis, completing the payload-carrier
1448        // accessor family peer of the sibling per-`:contratos`
1449        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1450        // (90de675) lifts across the HTTP / pub-sub arms.
1451        let slot = self.slot();
1452        // Route the local `(de, para, wit)` triple-projection closure
1453        // through the lifted [`WitContract::edge_triple`] typed accessor
1454        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1455        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1456        // triple-carrying diagnostic constructors below (wrong-target /
1457        // missing-target on all three payload arms + capability-with-
1458        // payload + invalid-wit) now key off exactly one typed dispatch
1459        // on the substrate-primitive composite projection, sibling to
1460        // the peer [`WitContract::edge_pair`]-routed
1461        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1462        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1463        // diagnostic constructors on the same per-`:contratos`
1464        // diagnostic-construction surface.
1465        let edge = || self.edge_triple();
1466
1467        // The `:wit` value drives every downstream dispatch — the
1468        // is_http/is_pubsub/is_store prefix matchers below, the
1469        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1470        // exclusion. Until this gate landed `target()` accepted any
1471        // non-empty string and silently demoted unrecognized shapes to
1472        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1473        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1474        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1475        // package, the paste-from-binary footgun a multi-line blob
1476        // accidentally landing in the slot, the un-percent-encoded
1477        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1478        // routing, got L4-only" footgun. Empty is still pre-checked at
1479        // the [`AplicacaoSpec::validate`] call site via the narrower
1480        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1481        // validate layer); the value-shape gate here picks up the
1482        // structurally-invalid non-empty cases the empty check misses,
1483        // and remains correct under direct `target()` calls outside
1484        // validate (the predicate's defensive empty arm returns a
1485        // parser-shaped reason rather than silently falling through to
1486        // the Capability arm). Same trajectory as c4213a4 (WitContract
1487        // endpoint/subject/slot value-shape gates lifted into
1488        // `target()`) on the peer payload axes.
1489        //
1490        // Routed through the lifted [`WitContract::world_ref`] accessor
1491        // rather than the raw `&self.wit` field access — the two
1492        // production consumers of the per-`:contratos :wit` world-ref
1493        // byte-string on the value-shape axis (this method's invalid-
1494        // wit gate, the [`AplicacaoSpec::validate`] duplicate-
1495        // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
1496        // [`WitContract::identity`]) now key off exactly one typed
1497        // dispatch on the substrate primitive, so any future rebrand on
1498        // the axis (an M4 promotion from `String` to a typed WIT
1499        // world-ref enum once the WIT registry stabilizes in
1500        // tatara-lisp, a per-CR canonicalization pass that lowercases
1501        // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
1502        // inline-buffer swap on the storage arm) migrates as a single
1503        // caixa-core edit rather than a coordinated rewrite of the two
1504        // call sites — sibling of the peer [`WitContract::endpoint`] /
1505        // [`WitContract::subject`] / [`WitContract::slot`] accessor-
1506        // routed payload-carrier extractions above on the same
1507        // [`WitContract::target`] body, completing the per-`:contratos`
1508        // scalar-accessor-routing pass at the last unlifted raw-field-
1509        // access site inside `impl WitContract`. Same "typed dispatch
1510        // composes with typed dispatch, not with raw field access"
1511        // discipline the sibling [`WitContract::edge_pair`] /
1512        // [`WitContract::edge_triple`] / [`WitContract::identity`]
1513        // composite-projection accessors and the
1514        // [`WitContract::is_self_loop`] identity-space predicate
1515        // already route through. Pinned by
1516        // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
1517        if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
1518            return Err(AplicacaoError::contrato_wit_invalid(
1519                self.edge_pair(),
1520                self.world_ref(),
1521                reason,
1522            ));
1523        }
1524
1525        if self.is_http() {
1526            if subject.is_some() || slot.is_some() {
1527                return Err(AplicacaoError::contrato_wrong_target(
1528                    edge(),
1529                    WitTarget::HTTP_FIELD_NAME,
1530                ));
1531            }
1532            let ep = endpoint.ok_or_else(|| {
1533                AplicacaoError::contrato_missing_target(edge(), WitTarget::HTTP_FIELD_NAME)
1534            })?;
1535            if ep.is_empty() {
1536                return Err(AplicacaoError::contrato_endpoint_empty(self.edge_pair()));
1537            }
1538            if !ep.starts_with('/') {
1539                return Err(AplicacaoError::contrato_endpoint_not_absolute(
1540                    self.edge_pair(),
1541                    ep,
1542                ));
1543            }
1544            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1545            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1546            // API v1 HTTPPathMatch.value admission grammar with the
1547            // sibling `:entrada :paths` axis. Until this gate landed
1548            // `target()` only refused the empty string + the missing-
1549            // leading-`/` form; a structurally invalid endpoint
1550            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1551            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1552            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1553            // path-traversal segment, the >1024-byte slug) silently
1554            // passed validate and the failure surfaced at apply time
1555            // as a Cilium policy rejection / silent traffic drop, far
1556            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1557            // grammar `:entrada :paths` already gates (55410e4), now
1558            // shared with `:contratos :endpoint` through the lifted
1559            // `crate::render::is_gateway_api_http_path` predicate.
1560            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1561                return Err(AplicacaoError::contrato_endpoint_invalid(
1562                    self.edge_pair(),
1563                    ep,
1564                    reason,
1565                ));
1566            }
1567            return Ok(WitTarget::Http { endpoint: ep });
1568        }
1569        if self.is_pubsub() {
1570            if endpoint.is_some() || slot.is_some() {
1571                return Err(AplicacaoError::contrato_wrong_target(
1572                    edge(),
1573                    WitTarget::PUBSUB_FIELD_NAME,
1574                ));
1575            }
1576            let s = subject.ok_or_else(|| {
1577                AplicacaoError::contrato_missing_target(edge(), WitTarget::PUBSUB_FIELD_NAME)
1578            })?;
1579            if s.is_empty() {
1580                return Err(AplicacaoError::contrato_subject_empty(self.edge_pair()));
1581            }
1582            // The `:subject` lands at runtime as the NATS subject the
1583            // producer publishes to and the consumer subscribes from.
1584            // Until this gate landed `target()` only refused the
1585            // empty string; a structurally invalid subject
1586            // (`"foo..bar"` — empty token between separators,
1587            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1588            // server's subject parser rejects, `"foo bar"` —
1589            // un-percent-encoded whitespace, `"foo.café"` —
1590            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1591            // empty leading/trailing tokens, the >256-byte
1592            // paste-from-binary slug) silently passed validate and
1593            // the failure surfaced at runtime as a NATS server-side
1594            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1595            // a silent message drop, far from the source caixa.lisp.
1596            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1597            // trajectory `:contratos :endpoint` (4f0390b) and
1598            // `:contratos :wit` (6226bf4) already gate, now shared
1599            // with `:contratos :subject` through the lifted
1600            // `crate::render::is_nats_subject` predicate.
1601            if let Err(reason) = crate::render::is_nats_subject(s) {
1602                return Err(AplicacaoError::contrato_subject_invalid(
1603                    self.edge_pair(),
1604                    s,
1605                    reason,
1606                ));
1607            }
1608            return Ok(WitTarget::PubSub { subject: s });
1609        }
1610        if self.is_store() {
1611            if endpoint.is_some() || subject.is_some() {
1612                return Err(AplicacaoError::contrato_wrong_target(
1613                    edge(),
1614                    WitTarget::STORE_FIELD_NAME,
1615                ));
1616            }
1617            let sl = slot.ok_or_else(|| {
1618                AplicacaoError::contrato_missing_target(edge(), WitTarget::STORE_FIELD_NAME)
1619            })?;
1620            if sl.is_empty() {
1621                return Err(AplicacaoError::contrato_slot_empty(self.edge_pair()));
1622            }
1623            // Value-shape gate on the third (and last) typed payload
1624            // axis the `WitContract::target` dispatch carries — the
1625            // peer of [`crate::render::is_gateway_api_http_path`] for
1626            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1627            // for `:subject` (63e18a0). Until this gate landed
1628            // `target()` only refused the empty string; a structurally
1629            // invalid slot (`"check out/$order"` — un-percent-encoded
1630            // whitespace whose runtime behavior varies unpredictably
1631            // across kv backends, `"checkout/\x01order"` — control
1632            // character that Redis admits but corrupts on next read
1633            // and DynamoDB rejects outright, `"chéckout/$order"` —
1634            // un-percent-encoded non-ASCII byte each backend re-encodes
1635            // differently, `"checkout\n/$order"` — embedded newline,
1636            // the 513-byte paste-from-binary slug) silently passed
1637            // validate and surfaced at runtime as a per-backend kv
1638            // write rejection (DynamoDB / etcd) or as a silent
1639            // next-read corruption (Redis-via-RESP3), far from the
1640            // source caixa.lisp with no field naming which `:contratos`
1641            // edge carried the typo. The lifted predicate makes the
1642            // kv-backend intersection-floor a substrate-level
1643            // invariant at validate time, not a runtime "this passed
1644            // validate but the kv backend rejected on first write"
1645            // surprise — closes the typed payload-axis value-shape
1646            // trajectory across all three legs of the four
1647            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1648            // that caixa-mesh + the future kv emitters land in.
1649            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1650                return Err(AplicacaoError::contrato_slot_invalid(
1651                    self.edge_pair(),
1652                    sl,
1653                    reason,
1654                ));
1655            }
1656            return Ok(WitTarget::Store { slot: sl });
1657        }
1658
1659        // Unrecognized WIT world — must not carry any payload target.
1660        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1661            return Err(AplicacaoError::contrato_wrong_target(
1662                edge(),
1663                WitTarget::CAPABILITY_EXPECTED,
1664            ));
1665        }
1666        Ok(WitTarget::Capability)
1667    }
1668
1669    /// Substrate-canonical post-validation projection of the typed
1670    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1671    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1672    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1673    /// [`typed_view`]-shaped entry point that composes `validate` into
1674    /// the projection) reaches through when it needs the typed
1675    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1676    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1677    /// coherence for every `:contratos` entry. The peer accessor to the
1678    /// [`Self::target`] `Result`-returning validator on the same
1679    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1680    /// pre-validation validator that computes the projection *and* raises
1681    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1682    /// (`:wit`, payload) mismatch; this method is the post-validation
1683    /// projection every downstream consumer reaches through once the
1684    /// pre-validation gate has succeeded.
1685    ///
1686    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1687    ///
1688    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1689    /// the same message" pattern sat inline at two production sites with
1690    /// no compile-time link between them: the
1691    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1692    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1693    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1694    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1695    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1696    /// (`c.target().expect("validated by typed_view").graph_label()`),
1697    /// each open-coding the same `.target().expect("validated by
1698    /// typed_view")` pair with the message spelled twice. A future
1699    /// vocabulary shift on the panic-message axis (a tightening from
1700    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1701    /// validate"` as the substrate's validator entry-point vocabulary
1702    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1703    /// panic to a `debug_assert` under a `--release` build profile) would
1704    /// have had to be threaded through both open-coded call sites in
1705    /// lockstep or one consumer would silently disagree with the peer on
1706    /// which invariant the panic message names. Same "same shape written
1707    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1708    /// discipline the sibling [`Self::edge_pair`] /
1709    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1710    /// lifts already establish on the paired composite-projection axis;
1711    /// this lift extends it onto the post-validation typed-view axis.
1712    ///
1713    /// Every future downstream consumer of the projected typed view
1714    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1715    /// CR materializer's per-edge admission webhook, the future
1716    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1717    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1718    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1719    /// `--kv` per-shape column emitters) reaches through this one typed
1720    /// dispatch on the substrate primitive rather than an open-coded
1721    /// per-consumer `.target().expect(…)` pair with the message
1722    /// re-inlined. The invariant the accessor's panic path pins — "this
1723    /// call is only reachable after [`AplicacaoSpec::validate`] has
1724    /// succeeded on the containing spec" — is the substrate's answer to
1725    /// give exactly once, at the primitive, not once per consumer.
1726    ///
1727    /// # Panics
1728    ///
1729    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1730    /// would return an `Err` — i.e. if this contract's
1731    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1732    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1733    /// this accessor only from a code path that has already reached the
1734    /// containing [`AplicacaoSpec`] through a validating entry-point
1735    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1736    /// [`typed_view`] compose, the future M4 CR admission webhook's
1737    /// per-CR validate). Use [`Self::target`] instead on any pre-
1738    /// validation code path.
1739    ///
1740    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1741    #[must_use]
1742    pub fn target_projected(&self) -> WitTarget<'_> {
1743        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1744    }
1745
1746    /// Canonical panic message the [`Self::target_projected`]
1747    /// post-validation projection accessor threads through when the
1748    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1749    /// has succeeded" precondition. Lifted as a `pub const` on the
1750    /// [`WitContract`] surface so the byte-string lives in one place
1751    /// across the substrate — the [`Self::target_projected`] method
1752    /// body, the two prior production call sites' comments now naming
1753    /// the const, and every future consumer that must format-match the
1754    /// panic-message shape (a future test suite that asserts the panic-
1755    /// message byte-string across a fuzzed invalid-contract corpus,
1756    /// a future custom-panic hook in `caixa-operator` that surfaces the
1757    /// message with per-`:contratos` telemetry, the future admission
1758    /// webhook's per-CR validate-error report) reaches through the same
1759    /// canonical `&'static str`. A future rebrand on the panic-message
1760    /// axis (a tightening from `"validated by typed_view"` to `"validated
1761    /// by AplicacaoSpec::validate"` as the substrate's validator
1762    /// entry-point vocabulary sharpens once caixa-core grows a
1763    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1764    /// [`typed_view`]) lands at one caixa-core edit rather than a
1765    /// coordinated per-consumer sweep — same "one canonical declaration
1766    /// per axis, next to the accessor that reads it" discipline the peer
1767    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1768    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1769    /// const family already establishes on the paired per-consumer-axis
1770    /// diagnostic-scalar surface.
1771    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1772}
1773
1774/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1775/// gate (see [`AplicacaoSpec::validate`]): every field that
1776/// distinguishes one contract from another, in declaration order
1777/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1778/// with equal [`ContratoIdentity`]s are the same typed edge declared
1779/// twice — the graph-edge analogue of duplicate `:membros` /
1780/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1781/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1782/// clippy's `type_complexity` lint (and so a future axis added to
1783/// `WitContract` is one alias edit, not a coordinated rewrite of
1784/// every set instantiation).
1785pub type ContratoIdentity<'a> = (
1786    &'a str,
1787    &'a str,
1788    &'a str,
1789    Option<&'a str>,
1790    Option<&'a str>,
1791    Option<&'a str>,
1792);
1793
1794/// Typed view of a [`WitContract`]'s payload target. Each variant
1795/// carries the field its WIT shape requires; constructing a `Http`
1796/// view without an endpoint is impossible by the type system.
1797///
1798/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1799/// instead of probing `Option<String>` fields one by one — the
1800/// "which payload field is set?" question is answered once, at
1801/// validation time.
1802#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1803pub enum WitTarget<'a> {
1804    /// HTTP-shaped WIT world. Carries the configured request path.
1805    Http { endpoint: &'a str },
1806    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1807    ///
1808    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1809    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1810    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1811    /// method name byte-identical to the sibling
1812    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1813    /// arm-discriminator that routes through
1814    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1815    /// through `matches!` on the variant), so the two arm-discriminator
1816    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1817    /// every downstream consumer through the same `is_pubsub()` name.
1818    #[is_variant(name = "pubsub")]
1819    PubSub { subject: &'a str },
1820    /// Key-value-shaped WIT world. Carries the slot template.
1821    Store { slot: &'a str },
1822    /// A typed capability edge with no payload selector — the WIT
1823    /// world stands on its own (rare; reserved for plain capability
1824    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1825    Capability,
1826}
1827
1828impl<'a> WitTarget<'a> {
1829    /// Canonical author-facing `:contratos` payload field name for the
1830    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1831    /// [`AplicacaoError::ContratoMissingTarget`] /
1832    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1833    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1834    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1835    /// the `feira app graph` verb prints. Peer of
1836    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1837    /// on the payload-field-name axis; declared as a peer const next
1838    /// to the [`WitTarget::Http`] variant so a future rename on the
1839    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1840    /// :endpoint …)))` field lands in exactly one place, not scattered
1841    /// across the [`WitContract::target`] gate's six `expected:`
1842    /// literals, the label template, and every downstream consumer
1843    /// that prints a per-arm prefix. Same trajectory as the peer
1844    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1845    /// for the arm's shape, next to the variant declaration.
1846    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1847    /// Canonical author-facing `:contratos` payload field name for the
1848    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1849    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1850    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1851    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1852    /// Canonical author-facing `:contratos` payload field name for the
1853    /// key/value-store-shaped arm. Peer of
1854    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1855    /// on the payload-field-name axis; see
1856    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1857    pub const STORE_FIELD_NAME: &'static str = "slot";
1858
1859    /// Canonical stable human-readable label the payload-less
1860    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1861    /// the byte-string every consumer that formats a payload-less
1862    /// typed capability edge as text lands on (the
1863    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1864    /// naming which identical edge was declared twice, the future
1865    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1866    /// policy resolver's audit view, the operator's mesh-graph audit).
1867    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1868    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1869    /// author-facing label-scalar consts — the same
1870    /// "one canonical declaration per arm, next to the variant, so a
1871    /// future rename lands in one place" discipline extended to the
1872    /// payload-less arm. Until this lift landed the byte-string sat
1873    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1874    /// match arm, once in the pin test asserting the label's
1875    /// [`WitTarget::Capability`] output — with no compile-time link
1876    /// between the two: a rebrand on either side (an operator-facing
1877    /// vocabulary shift, a per-consumer disambiguation like
1878    /// `"(capability — no payload; typed edge only)"`) would silently
1879    /// desynchronize until a downstream consumer surfaced the drift at
1880    /// runtime.
1881    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1882
1883    /// Canonical `expected:` scalar the
1884    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1885    /// through for the payload-less [`WitTarget::Capability`] arm — the
1886    /// byte-string authors read as "this WIT world's shape is not one
1887    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1888    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1889    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1890    /// [`Self::STORE_FIELD_NAME`] consts on the
1891    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1892    /// same "which payload field name goes in the diagnostic" dispatch
1893    /// the three payload-arm consts cover, extended to the payload-less
1894    /// arm. Until this lift landed the byte-string sat twice — once
1895    /// inline in the [`Self::target`] Capability-arm rejection at the
1896    /// production dispatch, once in the pin test asserting the
1897    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1898    /// no compile-time link between the two: a rebrand on either side
1899    /// (an author-facing vocabulary shift to `"capability"` /
1900    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1901    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1902    /// [`WitTarget::Capability`] into per-shape peers) would silently
1903    /// desynchronize until a downstream consumer surfaced the drift at
1904    /// runtime. Same "one canonical declaration per arm, next to the
1905    /// variant, so a future rename lands in one place" discipline the
1906    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1907    /// established for the payload-less arm's human-readable label
1908    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1909    /// so both halves of the "how does the Capability arm surface at
1910    /// its two consumer axes (human-readable label, wrong-target
1911    /// diagnostic)" pipeline route through peer consts declared next
1912    /// to the variant.
1913    ///
1914    /// Pairwise-distinctness against the three payload-arm scalars
1915    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1916    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1917    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1918    /// test — the 4-way closure of the 3-way
1919    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1920    /// the `ContratoWrongTarget::expected` axis, matching the peer
1921    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1922    /// scalar-value distinctness discipline the sibling M3 typed-enum
1923    /// discriminator axis already carries.
1924    pub const CAPABILITY_EXPECTED: &'static str = "none";
1925
1926    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1927    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1928    /// as under [`Self::graph_label`] — the sibling
1929    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1930    /// payload-column axis (the graph verb spells payload-less as
1931    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1932    /// diagnostic's `(capability — no payload)` on the human-readable
1933    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1934    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1935    /// family — extends the "one canonical declaration per arm, next to
1936    /// the variant, so a future rename lands in one place" discipline
1937    /// onto the third payload-less-arm consumer axis (`feira app graph`
1938    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1939    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1940    /// axis).
1941    ///
1942    /// Until this lift landed the byte-string sat inline in
1943    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1944    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1945    /// `"(capability-only)".to_string()` literal, with no compile-time link
1946    /// back to the [`WitTarget::Capability`] variant declaration nor to
1947    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1948    /// peer consts already carrying the "one canonical declaration per
1949    /// payload-less-arm consumer axis" discipline. A rebrand on either
1950    /// side (the graph verb's operator-facing vocabulary tightening from
1951    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1952    /// the WIT registry vocabulary sharpens, an M4 split of
1953    /// [`Self::Capability`] into per-shape peers) would silently
1954    /// desynchronize the graph-verb byte-string from the paired
1955    /// per-arm-adjacent const and land two spellings of the same axis in
1956    /// two spots.
1957    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1958
1959    /// The `(author-facing field name, payload)` pair this typed target
1960    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1961    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1962    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1963    /// [`Self::Store`], `None` for the payload-less
1964    /// [`Self::Capability`] arm.
1965    ///
1966    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1967    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1968    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1969    /// (returns the first component) route through, so a future
1970    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1971    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1972    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1973    /// exactly one new match-arm here (a compile-time exhaustiveness
1974    /// error otherwise), not a coordinated three-way rewrite of the
1975    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1976    /// + every downstream consumer that reaches for the pair.
1977    ///
1978    /// Until this lift landed the three payload arms sat in
1979    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1980    /// invocations (one per variant, each hand-quoting the paired
1981    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1982    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1983    /// "same shape, written N times" duplication THEORY.md §I.3.5
1984    /// ("Generation first, composition second, hand-authoring last;
1985    /// the duplication budget is zero") promotes to a build-time
1986    /// concern, with each per-arm site paired to its own const with no
1987    /// compile-time link between the format template and the arm's
1988    /// payload extraction.
1989    #[must_use]
1990    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1991        match *self {
1992            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1993            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1994            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1995            WitTarget::Capability => None,
1996        }
1997    }
1998
1999    /// The canonical author-facing `:contratos` payload field name
2000    /// this typed target arm carries (`Http` → `Some("endpoint")`,
2001    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
2002    /// `None` for the payload-less `Capability` arm.
2003    ///
2004    /// Routes through [`Self::payload_pair`] — the single 4-arm
2005    /// dispatch [`Self::label`] also reads — so a future variant
2006    /// addition is one match-arm edit at [`Self::payload_pair`], not a
2007    /// per-consumer rewrite. Same "exhaustive-match at one canonical
2008    /// dispatch, thin projections at each consumer" trajectory the
2009    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
2010    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
2011    #[must_use]
2012    pub const fn field_name(&self) -> Option<&'static str> {
2013        match self.payload_pair() {
2014            Some((f, _)) => Some(f),
2015            None => None,
2016        }
2017    }
2018
2019    /// The underlying scalar the payload-carrying arm carries — the
2020    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
2021    /// subject ([`Self::PubSub`] `:subject`), or slot template
2022    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
2023    /// `&'a str` storage — or `None` on the payload-less
2024    /// [`Self::Capability`] arm.
2025    ///
2026    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
2027    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
2028    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
2029    /// the paired sub-selector axis. Both per-half accessors read from
2030    /// one authoritative match, so a future [`WitTarget`] variant
2031    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
2032    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
2033    /// on [`Self::payload_pair`] and both per-half projections + every
2034    /// downstream consumer picks the new arm up by construction — no
2035    /// coordinated N-way rewrite across the paired accessor dispatches,
2036    /// the [`Self::label`] / [`Self::graph_label`] format templates,
2037    /// and every future WIT-registry-shaped consumer.
2038    ///
2039    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2040    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2041    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2042    /// both per-half projections as thin readers, every downstream
2043    /// consumer through the same match" discipline extended onto the
2044    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2045    /// gap between the two paired-dispatch surfaces: the peer
2046    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2047    /// the first-component projection until this lift; the second-
2048    /// component sibling now sits alongside so both halves reach every
2049    /// future consumer through the same substrate-primitive dispatch.
2050    ///
2051    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2052    #[must_use]
2053    pub const fn payload(&self) -> Option<&'a str> {
2054        match self.payload_pair() {
2055            Some((_, p)) => Some(p),
2056            None => None,
2057        }
2058    }
2059
2060    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2061    /// consumer that fans on the L7-HTTP-shaped payload keys off —
2062    /// returns the [`Self::Http`]-arm's author-declared request path
2063    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2064    /// projected target is [`Self::Http { endpoint }`], `None` on the
2065    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2066    /// [`Self::Capability`], each of which carries no HTTP endpoint by
2067    /// definition).
2068    ///
2069    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2070    /// `path:` rule payload every substrate-side L7-introspecting
2071    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2072    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2073    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2074    /// on the L7 introspection branch; every peer WIT shape stays
2075    /// L4-only because Cilium can't introspect NATS / key-value / plain
2076    /// capability edges), and every future L7-introspecting consumer
2077    /// of the projected target's HTTP endpoint (the future M4
2078    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2079    /// materializer's per-edge L7 admission-webhook overlay, the
2080    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2081    /// path bucket-key resolver, the future per-`:contratos`-edge
2082    /// mTLS-required overlay's HTTP-shape scope filter, the future
2083    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2084    /// through the same typed dispatch.
2085    ///
2086    /// Prior to this lift the sole production consumer of the projected-
2087    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2088    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2089    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2090    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2091    /// }`) — reached the payload through a raw per-arm `if let` pattern-
2092    /// match that expressed no compile-time link back to the substrate
2093    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2094    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2095    /// scalar accessor on the peer per-`:contratos` raw-field axis but
2096    /// with no post-projection peer on the typed-view surface. A future
2097    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2098    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2099    /// gRPC-shaped worlds per this enum's own docstring at
2100    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2101    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2102    /// would have had to be threaded through the caixa-mesh L7 emit
2103    /// branch's raw `if let` in lockstep — either coalescing the two
2104    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2105    /// emit path per-arm — with no substrate-primitive dispatch making
2106    /// the "which arms count as L7-HTTP-shaped for path-emission
2107    /// purposes" question the substrate's answer to give. Lifting the
2108    /// resolution to a typed method on the substrate primitive means
2109    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2110    /// projected-target HTTP endpoint reaches for exactly one typed
2111    /// dispatch — the resolver's accept-set migrates as a unit on any
2112    /// future arm-family widening, and the caixa-mesh L7 emit branch
2113    /// reads through the same substrate primitive.
2114    ///
2115    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2116    /// (7020470) `Option<&str>` scalar accessor on the raw
2117    /// `:contratos :endpoint` field-access axis — same "one typed
2118    /// dispatch on the substrate primitive, thin projections at each
2119    /// consumer" discipline extended onto the peer post-projection typed-
2120    /// view surface (the [`WitContract::endpoint`] pre-projection
2121    /// accessor returns `Some` for any author-declared `:endpoint`
2122    /// value regardless of the paired `:wit` world's HTTP-shape
2123    /// classification — the raw slot before validation crosses it —
2124    /// while this post-projection [`Self::http_endpoint`] accessor
2125    /// returns `Some` iff the target has been projected onto the
2126    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2127    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2128    /// coherence; the two accessors close the pre-projection /
2129    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2130    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2131    /// the three payload-carrying arms) — extends the per-arm
2132    /// projection family onto the [`Self::Http`] specialization axis
2133    /// that the pan-arm accessor's shape blends into a single arm-
2134    /// agnostic view; paired with [`Self::pubsub_subject`] /
2135    /// [`Self::store_slot`] on the sibling per-arm axes so every
2136    /// per-payload-arm shape carries a named post-projection accessor
2137    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2138    /// accept-set the substrate primitive owns.
2139    #[must_use]
2140    pub const fn http_endpoint(&self) -> Option<&'a str> {
2141        match *self {
2142            WitTarget::Http { endpoint } => Some(endpoint),
2143            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2144        }
2145    }
2146
2147    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2148    /// consumer that fans on the pub-sub-shaped payload keys off —
2149    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2150    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2151    /// the projected target is [`Self::PubSub { subject }`], `None` on
2152    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2153    /// [`Self::Capability`], each of which carries no NATS-shaped
2154    /// subject by definition).
2155    ///
2156    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2157    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2158    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2159    /// CR materializer's `spec.subjects[]` projection, the future
2160    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2161    /// bucket-key resolver, the future `feira app graph --pubsub`
2162    /// per-Aplicacao subject column, any future substrate-lifted
2163    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2164    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2165    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2166    /// future pub-sub-shape consumer reaches for the same typed
2167    /// dispatch this accessor exposes so the "which arm carries the
2168    /// subject scalar?" answer lives at one caixa-core edit rather
2169    /// than open-coded across per-consumer `if let WitTarget::PubSub
2170    /// { subject } = c.target()…` pattern-matches.
2171    ///
2172    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2173    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2174    /// the pre-projection [`WitContract::subject`] scalar accessor on
2175    /// the raw `:contratos :subject` field-access axis — same "one
2176    /// typed dispatch on the substrate primitive, thin projections at
2177    /// each consumer" discipline extended onto the per-arm pub-sub
2178    /// post-projection axis. The pre-projection accessor returns
2179    /// `Some` for any author-declared `:subject` value regardless of
2180    /// the paired `:wit` world's pub-sub-shape classification (the raw
2181    /// slot before validation crosses it); this post-projection
2182    /// accessor returns `Some` iff the target has been projected onto
2183    /// the [`Self::PubSub`] arm, i.e. only after the
2184    /// [`WitContract::target`] gate has admitted the
2185    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2186    /// the pre-/post-projection pair on the pub-sub-subject axis to
2187    /// match the pair the [`WitContract::endpoint`] +
2188    /// [`Self::http_endpoint`] surfaces already close on the peer
2189    /// HTTP-endpoint axis.
2190    ///
2191    /// Sibling of the unified pan-arm [`Self::payload`]
2192    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2193    /// extends the per-arm projection family onto the [`Self::PubSub`]
2194    /// specialization axis that the pan-arm accessor's shape blends
2195    /// into a single arm-agnostic view; the pair
2196    /// (`pubsub_subject`, `store_slot`) closes the trio
2197    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2198    /// payload arm now carries its own per-arm-shape post-projection
2199    /// accessor.
2200    #[must_use]
2201    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2202        match *self {
2203            WitTarget::PubSub { subject } => Some(subject),
2204            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2205        }
2206    }
2207
2208    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2209    /// every consumer that fans on the store-shaped payload keys off —
2210    /// returns the [`Self::Store`]-arm's author-declared slot template
2211    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2212    /// projected target is [`Self::Store { slot }`], `None` on the
2213    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2214    /// [`Self::Capability`], each of which carries no
2215    /// key/value-store slot by definition).
2216    ///
2217    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2218    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2219    /// every future substrate-side store-introspecting per-`(:de,
2220    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2221    /// namespace / prefix reconciler's per-slot projection, the future
2222    /// per-store-backend routing overlay's slot-shape gate, the future
2223    /// `feira app graph --store` per-Aplicacao slot column, any future
2224    /// substrate-lifted store-shape emitter that reads a projected
2225    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2226    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2227    /// Every future store-shape consumer reaches for the same typed
2228    /// dispatch this accessor exposes so the "which arm carries the
2229    /// slot scalar?" answer lives at one caixa-core edit rather than
2230    /// open-coded across per-consumer
2231    /// `if let WitTarget::Store { slot } = c.target()…`
2232    /// pattern-matches.
2233    ///
2234    /// Peer of the sibling [`Self::http_endpoint`] +
2235    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2236    /// axes and of the pre-projection [`WitContract::slot`] scalar
2237    /// accessor on the raw `:contratos :slot` field-access axis — same
2238    /// "one typed dispatch on the substrate primitive, thin projections
2239    /// at each consumer" discipline extended onto the per-arm store
2240    /// post-projection axis. Closes the pre-/post-projection pair on
2241    /// the store-slot axis to match the pairs the
2242    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2243    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2244    /// already close on the peer HTTP-endpoint and pub-sub-subject
2245    /// axes; the substrate-side pre-/post-projection accessor family
2246    /// now spans all three payload arms as a matched trio, so any
2247    /// future arm-shape widening (a `Rest`/`Grpc` split of
2248    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2249    /// lands one accessor without threading through the sibling
2250    /// pre-projection or the peer per-arm post-projection surfaces a
2251    /// compile-time exhaustiveness error at the substrate primitive,
2252    /// not a silent per-consumer split at renderer emit time.
2253    ///
2254    /// Sibling of the unified pan-arm [`Self::payload`]
2255    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2256    /// closes the per-arm projection family onto the [`Self::Store`]
2257    /// specialization axis that the pan-arm accessor's shape blends
2258    /// into a single arm-agnostic view. The trio
2259    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2260    /// pan-arm accept-set on every payload-carrying arm: exactly one
2261    /// per-arm accessor returns `Some(payload)` and the two peers
2262    /// return `None`, and every payload-less [`Self::Capability`]
2263    /// input returns `None` on all three — the partition the sibling
2264    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2265    /// pin locks in load-bearing.
2266    #[must_use]
2267    pub const fn store_slot(&self) -> Option<&'a str> {
2268        match *self {
2269            WitTarget::Store { slot } => Some(slot),
2270            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2271        }
2272    }
2273
2274    /// Render this typed target as a stable human-readable label
2275    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2276    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2277    /// the WIT world is a pure capability edge).
2278    ///
2279    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2280    /// gate so the diagnostic names *which* identical edge was
2281    /// declared twice (not just which `(de, para, wit)` triple).
2282    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2283    /// on the payload-carrying arms (`Some((field, payload)) →
2284    /// format!(":{field} {payload:?}")`) and through the lifted
2285    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2286    /// [`Self::Capability`] arm — so a future variant addition (the
2287    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2288    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2289    /// `Queue`-shaped peer) becomes a single new match-arm on
2290    /// [`Self::payload_pair`] rather than a rewrite of this template
2291    /// (and every downstream consumer that reaches for the label
2292    /// shape: the per-edge policy resolver in M4, the `feira app
2293    /// graph` view, the operator's mesh-graph audit). Until this
2294    /// lift landed the three payload arms carried three near-identical
2295    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2296    /// [`Self::Capability`] arm carried the payload-less byte-string
2297    /// twice (once inline here, once in the pin test) — closing the
2298    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2299    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2300    /// / 4a1e490) peer-const lifts already established for the
2301    /// payload-carrying arms.
2302    #[must_use]
2303    pub fn label(&self) -> String {
2304        match self.payload_pair() {
2305            Some((field, payload)) => format!(":{field} {payload:?}"),
2306            None => Self::CAPABILITY_LABEL.to_string(),
2307        }
2308    }
2309
2310    /// Render this typed target as the `feira app graph` per-`:contratos`
2311    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2312    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2313    /// payload-less arm).
2314    ///
2315    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2316    /// on the payload-carrying arms (`Some((field, payload)) →
2317    /// format!("{field}={payload}")`) and through the lifted
2318    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2319    /// [`Self::Capability`] arm — so a future variant addition
2320    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2321    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2322    /// `Queue`-shaped peer) becomes one match-arm edit at
2323    /// [`Self::payload_pair`], propagating through this graph-verb
2324    /// projection at zero call-site cost, sibling to the peer
2325    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2326    /// same 4-arm dispatch.
2327    ///
2328    /// Until this lift landed the [`caixa-feira`]
2329    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2330    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2331    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2332    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2333    /// `format!("{}={endpoint}", ...)` template and hard-coding
2334    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2335    /// back to the paired [`WitTarget::Capability`] variant declaration.
2336    /// A future variant addition would have had to be threaded through
2337    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2338    /// verb's inline match in lockstep or the two projections would
2339    /// silently disagree on the arm-set the graph verb prints — the
2340    /// duplicate-`:contratos` diagnostic reading one shape while the
2341    /// graph verb's payload column silently dropped the new arm to
2342    /// `(capability-only)`. Lifting the graph-verb projection onto the
2343    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2344    /// the axis: both projections migrate as a unit.
2345    ///
2346    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2347    /// quoting) shape is graph-verb-canonical — distinct from the
2348    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2349    /// duplicate-`:contratos` diagnostic seeds (see
2350    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2351    /// on the payload-less axis for the paired distinction).
2352    #[must_use]
2353    pub fn graph_label(&self) -> String {
2354        match self.payload_pair() {
2355            Some((field, payload)) => format!("{field}={payload}"),
2356            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2357        }
2358    }
2359}
2360
2361/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2362/// pretty-printed byte-string every consumer that formats a typed
2363/// payload target as user-facing text lands on (the
2364/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2365/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2366/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2367/// graph` per-`:contratos`-edge payload column that reaches the graph
2368/// verb through `format!("{target}")`, the future M4 per-edge policy
2369/// resolver's per-edge audit-log line, the operator's mesh-graph
2370/// per-edge inspection view) reaches for the same lifted
2371/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2372/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2373/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2374/// routes through — extending the three-path-convergence
2375/// (`Debug` for structural inspection, `Display` for user-facing text,
2376/// per-arm typed accessor for the canonical byte-string) discipline the
2377/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2378/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2379/// onto the fourth (and only remaining) typed-shape-discriminator axis
2380/// on the caixa surface.
2381///
2382/// Pre-lift the two paths were structurally independent — every consumer
2383/// reaching for a payload byte-string past the [`WitTarget::label`]
2384/// helper had to pick between three paths ([`WitTarget::label`],
2385/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2386/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2387/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2388/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2389/// that reached for `format!("{target}")` — the canonical shape every
2390/// user-facing pretty-print site on the sibling typed-enum axes already
2391/// uses — would silently land on the `Debug` derive's structural output
2392/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2393/// than the `label()` helper's stable byte-string (`:endpoint
2394/// "/charge"` — the author-facing `:contratos` keyword form) the
2395/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2396/// already threads through. The two spellings would diverge silently in
2397/// every downstream diagnostic / graph / audit line reached through
2398/// `format!` rather than through the `label()` helper. Routing
2399/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2400/// path: every `format!("{v}")` call reaches the same
2401/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2402/// and the duplicate-`:contratos` gate already route through, so a
2403/// future variant addition (the M4-and-later per-edge WIT registry may
2404/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2405/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2406/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2407/// match — rather than fanning out through hand-rolled per-arm
2408/// [`std::fmt::Display`] arms.
2409///
2410/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2411/// is the typed view returned by [`WitContract::target`], not a
2412/// closed-set discriminator enum with a gen-platform Discriminant
2413/// registration, so the `Debug` derive's structural output (which every
2414/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2415/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2416/// shape for structural inspection; `Display` (via `label`) reveals the
2417/// stable author-facing payload projection.
2418///
2419/// Pin tests
2420/// [`tests::wit_target_display_routes_through_label_helper`] and
2421/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2422/// assert the two paths agree byte-for-byte on every variant, so a
2423/// future variant addition or `label()` reimplementation that hand-rolls
2424/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2425/// build error visible at caixa-core test time, not a silent
2426/// per-consumer dispatch miss at diagnostic / audit / graph time.
2427impl std::fmt::Display for WitTarget<'_> {
2428    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2429        f.write_str(&self.label())
2430    }
2431}
2432
2433// ── one Aplicacao member ─────────────────────────────────────────────
2434
2435/// A Servico participating in the Aplicacao. Same shape as
2436/// `crate::supervisor::ChildSpec` but without a restart policy —
2437/// supervision is per-Servico (each member has its own
2438/// `:supervisor`), the Aplicacao orchestrates *placement*.
2439#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2440#[serde(rename_all = "camelCase")]
2441pub struct Membro {
2442    /// Member caixa's `:nome`. Resolves through the same dep
2443    /// resolution path as `crate::dep::Dep`.
2444    pub caixa: String,
2445
2446    /// Semver constraint.
2447    pub versao: String,
2448}
2449
2450impl Membro {
2451    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2452    /// accessor every consumer that reads the member's Servico identity
2453    /// keys off — returns the author-declared `:membros :caixa`
2454    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2455    /// own [`String`] storage.
2456    ///
2457    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2458    /// participating in the Aplicacao — validated by
2459    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2460    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2461    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2462    /// [`validate_no_self_membership`]) — and every downstream consumer
2463    /// that fans on the member's identity keys off this scalar (the
2464    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2465    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2466    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2467    /// identity, the self-membership gate, the
2468    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2469    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2470    /// CR materializer's per-member resolver).
2471    ///
2472    /// Prior to this lift the `.caixa` byte-string was read inline at
2473    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2474    /// set collector at
2475    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2476    /// [`validate_membros`] validation-side member-caixa gate at
2477    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2478    /// per-member duplicate-gate dedup key at
2479    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2480    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2481    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2482    /// [`validate_no_self_membership`] self-loop gate at
2483    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2484    /// expressed no compile-time link back to the typed slot. Every
2485    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2486    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2487    /// `name:` axis, so a future extension of the `:membros :caixa`
2488    /// axis to a richer author surface — a per-cluster alias table the
2489    /// operator pins through a future `:placement`-scoped slot, a
2490    /// namespace-qualified rewrite the M4 CR materializer applies
2491    /// per-CR, a per-member overlay from the future `:membros
2492    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2493    /// acknowledges — would have had to be threaded through every
2494    /// open-coded copy in lockstep or one consumer would silently
2495    /// disagree with the peers on which caixa a given member resolves
2496    /// to. A member-set lookup that treated the name as `"cart"` while
2497    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2498    /// silently split the `:contratos` membership-lookup diagnostic from
2499    /// the cycle-detector's node identity — a two-consumer split at the
2500    /// validator far from the source `caixa.lisp` with no field naming
2501    /// the identity-drift root cause. Lifting the resolution rule to a
2502    /// typed method on the substrate primitive means every downstream
2503    /// consumer of the Aplicacao's per-`:membros` identity surface
2504    /// reaches for exactly one typed dispatch — the resolver's
2505    /// accept-set migrates as a unit on any future axis addition.
2506    ///
2507    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2508    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2509    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2510    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2511    /// destination-Servico scalar accessors — same "one typed dispatch
2512    /// on the substrate primitive, thin projections at each consumer"
2513    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2514    /// byte-string axis. Named `nome()` to match the tatara-lisp
2515    /// author-surface term the field's docstring already reaches for
2516    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2517    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2518    /// already carries — the accessor's name maps directly onto the
2519    /// canonical caixa-identity vocabulary rather than shadowing the
2520    /// field's storage-side `caixa` label.
2521    #[must_use]
2522    pub const fn nome(&self) -> &str {
2523        self.caixa.as_str()
2524    }
2525
2526    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2527    /// requirement scalar accessor every consumer that reads the
2528    /// member's version pin keys off — returns the author-declared
2529    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2530    /// from the typed slot's own [`String`] storage.
2531    ///
2532    /// The `:membros :versao` slot carries the Cargo-shaped semver
2533    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2534    /// pins which release of the member-caixa the Aplicacao composes
2535    /// against — the same requirement grammar the peer `:deps :versao`
2536    /// / `:children :versao` axes carry, resolved through the shared
2537    /// [`crate::render::require_valid_versao_requirement`] cascade and
2538    /// the shared [`crate::version::parse_requirement`] parser. Every
2539    /// downstream consumer that fans on the member's version pin keys
2540    /// off this scalar (the [`validate_membros`] per-member requirement
2541    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2542    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2543    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2544    /// version-lock overlay the operator pins through a future
2545    /// `:placement`-scoped slot, the future
2546    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2547    /// version resolver, the future `feira app deploy` pipeline's
2548    /// per-member lacre BLAKE3-closure lookup).
2549    ///
2550    /// Prior to this lift the `.versao` byte-string was accessed inline
2551    /// at two `&str`-shaped sites — the [`validate_membros`]
2552    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2553    /// …)` and the `feira app graph` per-member printer's `println!(
2554    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2555    /// prior to this lift) — two open-coded field-accesses that expressed
2556    /// no compile-time link back to the typed slot. A future extension of
2557    /// the `:membros :versao` axis to a richer author surface (a
2558    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2559    /// flow, a lacre-projected concrete-version rewrite the operator
2560    /// materializes at CR-admission time, a future `:membros :versao-lock`
2561    /// per-cluster override slot) would have had to be threaded through
2562    /// every open-coded copy in lockstep or one consumer would silently
2563    /// disagree with the peers on which release constraint a given
2564    /// member resolves to. Lifting the resolution rule to a typed method
2565    /// on the substrate primitive means every downstream requirement-
2566    /// facing consumer reaches for exactly one typed dispatch — the
2567    /// resolver's accept-set migrates as a unit on any future axis
2568    /// addition.
2569    ///
2570    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2571    /// member-caixa `:nome` scalar accessor — the pair
2572    /// `(nome(), versao_requirement())` jointly projects the
2573    /// `(caixa, versao)` field pair every renderer that fans on
2574    /// per-member identity + version pin keys off, closing the last
2575    /// unlifted per-`:membros` scalar axis so every downstream
2576    /// per-`:membros` reader now routes through a typed dispatch on the
2577    /// substrate primitive. Named `versao_requirement()` rather than
2578    /// `versao()` because the field's storage-side `.versao` label is
2579    /// already the author-surface term (`:versao`); the accessor's name
2580    /// carries the semantic role — the semver *requirement* string the
2581    /// shared [`crate::version::parse_requirement`] entry-point consumes
2582    /// — so a raw field access and a typed dispatch read differently at
2583    /// every consumer site.
2584    ///
2585    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2586    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2587    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2588    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2589    /// destination-Servico scalar accessors — same "one typed dispatch
2590    /// on the substrate primitive, thin projections at each consumer"
2591    /// discipline extended onto the per-`:membros` member-`:versao`
2592    /// semver-requirement byte-string axis.
2593    #[must_use]
2594    pub const fn versao_requirement(&self) -> &str {
2595        self.versao.as_str()
2596    }
2597}
2598
2599// ── mesh-level policies ──────────────────────────────────────────────
2600
2601/// Mesh policies that apply to every `:contratos` edge unless
2602/// overridden per-edge in M4. V0 is a single global policy block.
2603#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2604#[serde(rename_all = "camelCase")]
2605pub struct MeshPolicy {
2606    /// Per-call timeout. Authored as a duration string (`"30s"`).
2607    #[serde(
2608        default,
2609        skip_serializing_if = "Option::is_none",
2610        with = "supervisor::duration_codec"
2611    )]
2612    pub timeout: Option<Duration>,
2613
2614    /// Number of retries on transient failure. None = no retries.
2615    #[serde(default, skip_serializing_if = "Option::is_none")]
2616    pub retries: Option<u32>,
2617
2618    /// Circuit breaker config. Trips after N failures within W
2619    /// duration; closes after a cooldown.
2620    #[serde(default, skip_serializing_if = "Option::is_none")]
2621    pub circuit_breaker: Option<CircuitBreaker>,
2622
2623    /// Whether mTLS is required for every contrato. Default: true
2624    /// (sandboxing-by-default; explicit opt-out only).
2625    #[serde(default, skip_serializing_if = "Option::is_none")]
2626    pub mtls_required: Option<bool>,
2627
2628    /// Token-bucket rate limit. Authored as `"100/s"` or
2629    /// `"5000/m"`; stored as `(rate, window)`.
2630    #[serde(
2631        default,
2632        skip_serializing_if = "Option::is_none",
2633        with = "rate_limit_codec"
2634    )]
2635    pub rate_limit: Option<RateLimit>,
2636}
2637
2638impl MeshPolicy {
2639    /// True when no `:politicas` axis carries a value — every field is
2640    /// `None`. The same emptiness contract every other M2/M3 typed
2641    /// surface carries ([`crate::LimitsSpec::is_empty`],
2642    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2643    /// typed slot onto a cluster artifact key off this predicate to
2644    /// decide "emit the slot" vs "skip the slot entirely", so an
2645    /// authored-but-unset `:politicas (())` round-trips to a rendered
2646    /// artifact that's structurally identical to one that omits the
2647    /// slot. Lifted as a typed predicate (rather than per-renderer
2648    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2649    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2650    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2651    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2652    /// not a coordinated rewrite of every consumer that's reaching
2653    /// for the emptiness semantic.
2654    #[must_use]
2655    pub const fn is_empty(&self) -> bool {
2656        self.timeout().is_none()
2657            && self.retries().is_none()
2658            && self.circuit_breaker().is_none()
2659            && self.mtls_required().is_none()
2660            && self.rate_limit().is_none()
2661    }
2662
2663    /// Substrate-canonical cross-axis coherence predicate on the
2664    /// `:politicas` slot: does the `:circuit-breaker :window` rolling
2665    /// failure-observation interval span at least one full
2666    /// `:timeout`-bounded call?
2667    ///
2668    /// The first *cross-axis* invariant on the `:politicas` surface —
2669    /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
2670    /// zero-floor + canonical-form + cap brackets) validates one axis
2671    /// in isolation, so a `MeshPolicy` whose axes are each individually
2672    /// well-formed could still name a structurally inert pair. The
2673    /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
2674    /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
2675    /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
2676    /// both above the zero floor) and is nonetheless a breaker that
2677    /// cannot trip on the failure mode it exists to catch: a call
2678    /// dispatched at t=0 is declared failed at t=30s, by which point
2679    /// the 10s window open at dispatch has rolled twice over, so no
2680    /// window can ever hold even one timeout-derived failure however
2681    /// high the call volume. Envoy's `outlier_detection.interval`
2682    /// carries the identical relation against the per-route request
2683    /// timeout; Hystrix ships the canonical ratio in its defaults
2684    /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
2685    /// `execution.isolation.thread.timeoutInMilliseconds`).
2686    ///
2687    /// Vacuously `true` when either axis is absent — a `:politicas`
2688    /// that names only one of the pair declares no relation for the
2689    /// substrate to hold it to (`:timeout` alone is a per-call deadline
2690    /// with no breaker; `:circuit-breaker` alone is a breaker whose
2691    /// failures arrive from the transport's own error signal rather
2692    /// than from a substrate-imposed deadline, so no dispatch-to-report
2693    /// lag is knowable at author time). This is the same
2694    /// "unset means the cluster default applies, not zero" partition
2695    /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
2696    /// arm already carry.
2697    ///
2698    /// Lifted as a typed predicate on the substrate primitive rather
2699    /// than open-coded at the validate gate so every downstream
2700    /// consumer of the pair reaches the invariant through one dispatch:
2701    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2702    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2703    /// (MESH-COMPOSITION §III.2 #3) that must emit
2704    /// `outlier_detection.interval` and the per-route `timeout` as one
2705    /// coherent Envoy block, the future M4
2706    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2707    /// webhook, and the future per-`:contratos`-edge `:politicas`
2708    /// override that same roadmap acknowledges — which resolves an
2709    /// *effective* pair per edge (edge-level `:timeout` against the
2710    /// Aplicacao-level `:window`, or vice versa) and so must re-check
2711    /// the relation on a pair neither axis's declaration site can see
2712    /// whole. Naming the invariant once means that resolver folds this
2713    /// predicate over its resolved pair instead of re-deriving the
2714    /// comparison, exactly as the sibling cross-slot
2715    /// [`PlacementStrategy::is_shard_keyed`] predicate names the
2716    /// `:placement`/`:shard-key` relation for its own consumers.
2717    #[must_use]
2718    pub const fn breaker_window_observes_timeout(&self) -> bool {
2719        match (self.timeout(), self.circuit_breaker()) {
2720            (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
2721            _ => true,
2722        }
2723    }
2724
2725    /// Substrate-canonical cross-axis coherence predicate on the
2726    /// `:politicas` slot: can the token-bucket rate declared by
2727    /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
2728    /// :window` to reach `:max-failures`?
2729    ///
2730    /// The second cross-axis invariant on the `:politicas` surface —
2731    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2732    /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
2733    /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
2734    /// pair is validated in isolation by the per-axis brackets in
2735    /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
2736    /// max-failures zero-floor + cap, both windows zero-floor +
2737    /// integer-millisecond + cap, rate-limit window canonical-form),
2738    /// so a `MeshPolicy` whose axes are each individually well-formed
2739    /// can still name a structurally inert pair. The pair
2740    /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
2741    /// "10s") }` passes every per-axis bracket and is nonetheless a
2742    /// breaker that cannot trip on the failure mode it exists to
2743    /// catch: the token bucket admits `rate × (cb.window / rl.window)`
2744    /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
2745    /// no window can accumulate five failures however catastrophically
2746    /// the upstream is failing. Envoy's
2747    /// `outlier_detection.consecutive_5xx` paired against
2748    /// `local_rate_limit.token_bucket.max_tokens` /
2749    /// `fill_interval` carries the identical relation; every
2750    /// production playbook that pairs the two axes (Envoy, Istio, AWS
2751    /// App Mesh, Kong) recommends sizing the rate at or above the
2752    /// breaker's minimum-request-volume threshold for exactly this
2753    /// reason.
2754    ///
2755    /// The typed test is the integer inequality
2756    /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
2757    /// (rearranged from `rate × cb.window / rl.window >= max_failures`
2758    /// so no floating-point division mediates the comparison and so
2759    /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
2760    /// exactly). Both multiplicands are `saturating_mul`'d into
2761    /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
2762    /// have not yet passed [`AplicacaoSpec::validate_politicas`]
2763    /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
2764    /// panic the predicate; a saturated pair collapses to the
2765    /// "vacuously coherent" branch the peer per-axis brackets reject
2766    /// via their own zero-floor / cap arms first.
2767    ///
2768    /// Vacuously `true` when either axis is absent — a `:politicas`
2769    /// that names only one of the pair declares no relation for the
2770    /// substrate to hold it to (`:rate-limit` alone is a per-edge
2771    /// token-bucket declaration with no failure counter to starve;
2772    /// `:circuit-breaker` alone is a rolling-window failure counter
2773    /// whose call rate is unconstrained by the substrate, so no
2774    /// bucket-derived upper bound on calls-per-window is knowable at
2775    /// author time). Same "unset means the cluster default applies,
2776    /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
2777    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2778    /// carry.
2779    ///
2780    /// Lifted as a typed predicate on the substrate primitive rather
2781    /// than open-coded at the validate gate so every downstream
2782    /// consumer of the pair reaches the invariant through one
2783    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2784    /// below, the future `CiliumClusterwideEnvoyConfig`
2785    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2786    /// must emit `local_rate_limit.token_bucket.{max_tokens,
2787    /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
2788    /// / `outlier_detection.interval` as one coherent Envoy block,
2789    /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2790    /// materializer's admission webhook, and the future
2791    /// per-`:contratos`-edge `:politicas` override the same roadmap
2792    /// acknowledges — which resolves an *effective* pair per edge
2793    /// (edge-level `:rate-limit` against the Aplicacao-level
2794    /// `:circuit-breaker`, or vice versa) and so must re-check the
2795    /// relation on a pair neither axis's declaration site can see
2796    /// whole. Naming the invariant once means that resolver folds
2797    /// this predicate over its resolved pair instead of re-deriving
2798    /// the comparison, exactly as the sibling cross-axis
2799    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2800    /// names the `(:timeout, :window)` relation for its own consumers.
2801    #[must_use]
2802    pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
2803        match (self.rate_limit(), self.circuit_breaker()) {
2804            (Some(rl), Some(cb)) => {
2805                let calls_per_cb_window =
2806                    (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
2807                let trip_threshold_per_cb_window =
2808                    (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
2809                calls_per_cb_window >= trip_threshold_per_cb_window
2810            }
2811            _ => true,
2812        }
2813    }
2814
2815    /// Substrate-canonical cross-axis coherence predicate on the
2816    /// `:politicas` slot: can one client's declared `:retries` all
2817    /// complete before `:circuit-breaker :max-failures` trips the
2818    /// breaker mid-retry?
2819    ///
2820    /// The third cross-axis invariant on the `:politicas` surface —
2821    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2822    /// the `(:timeout, :circuit-breaker :window)` pair and
2823    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2824    /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
2825    /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
2826    /// the pair is validated in isolation by the per-axis brackets in
2827    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
2828    /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
2829    /// are each individually well-formed can still name a
2830    /// structurally-inert retry policy. The pair
2831    /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
2832    /// passes every per-axis bracket and is nonetheless a retry
2833    /// policy the substrate cannot honor: one client's initial attempt
2834    /// plus three retries is four attempts, but the breaker trips on
2835    /// the third failure — the fourth attempt (the last declared
2836    /// retry) is blocked by the open breaker, so the substrate
2837    /// declared four attempts and structurally allows three.
2838    ///
2839    /// The typed test is the integer inequality
2840    /// `cb.max_failures() > retries` — the retries count is the
2841    /// *number of retry attempts beyond the initial* (Envoy's
2842    /// `retry_policy.num_retries` semantics), so a client makes at
2843    /// most `retries + 1` attempts per client call, each of which may
2844    /// fail. For the breaker to *admit* the retry policy through
2845    /// completion, its trip threshold must not be reached by one
2846    /// client's failures alone: `retries + 1 <= max_failures`,
2847    /// equivalently `retries < max_failures`, equivalently
2848    /// `max_failures > retries`. The boundary case
2849    /// `max_failures == retries + 1` accepts (the R+1th failure — the
2850    /// last retry — trips the breaker exactly as it completes; retries
2851    /// are fully executed). The strict-below case
2852    /// `max_failures <= retries` rejects (the breaker trips before
2853    /// retries exhaust, silently truncating the declared retry policy
2854    /// mid-run — the same declared-but-structurally-inert footgun the
2855    /// sibling per-axis cap arms close on the single-axis surfaces).
2856    ///
2857    /// Vacuously `true` when either axis is absent — a `:politicas`
2858    /// that names only one of the pair declares no relation for the
2859    /// substrate to hold it to (`:retries` alone is a client-retry
2860    /// policy with no failure counter to trip; `:circuit-breaker`
2861    /// alone is a failure counter whose per-client attempt count is
2862    /// unconstrained by the substrate, so no per-client saturation
2863    /// bound on failures-per-client-call is knowable at author time).
2864    /// Same "unset means the cluster default applies, not zero"
2865    /// partition [`MeshPolicy::is_empty`] and the sibling
2866    /// [`MeshPolicy::breaker_window_observes_timeout`] /
2867    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
2868    /// carry.
2869    ///
2870    /// Lifted as a typed predicate on the substrate primitive rather
2871    /// than open-coded at the validate gate so every downstream
2872    /// consumer of the pair reaches the invariant through one
2873    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2874    /// below, the future `CiliumClusterwideEnvoyConfig`
2875    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2876    /// must emit `retry_policy.num_retries` alongside
2877    /// `outlier_detection.consecutive_5xx` as one coherent Envoy
2878    /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2879    /// materializer's admission webhook, and the future
2880    /// per-`:contratos`-edge `:politicas` override the same roadmap
2881    /// acknowledges — which resolves an *effective* pair per edge
2882    /// (edge-level `:retries` against the Aplicacao-level
2883    /// `:circuit-breaker`, or vice versa) and so must re-check the
2884    /// relation on a pair neither axis's declaration site can see
2885    /// whole. Naming the invariant once means that resolver folds
2886    /// this predicate over its resolved pair instead of re-deriving
2887    /// the comparison, exactly as the sibling cross-axis
2888    /// [`MeshPolicy::breaker_window_observes_timeout`] and
2889    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
2890    /// name the `(:timeout, :window)` and `(:rate-limit,
2891    /// :circuit-breaker)` relations for their own consumers.
2892    #[must_use]
2893    pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
2894        match (self.retries(), self.circuit_breaker()) {
2895            (Some(retries), Some(cb)) => cb.max_failures() > retries,
2896            _ => true,
2897        }
2898    }
2899
2900    /// Substrate-canonical cross-axis coherence predicate on the
2901    /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
2902    /// admit one client's full `:retries + 1` attempt burst inside a
2903    /// single refill window?
2904    ///
2905    /// The fourth cross-axis invariant on the `:politicas` surface,
2906    /// completing the triangle of pairs the three sibling gates carve
2907    /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
2908    /// on the `(:timeout, :circuit-breaker :window)` pair,
2909    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2910    /// `(:rate-limit, :circuit-breaker)` pair, and
2911    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
2912    /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
2913    /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
2914    /// among the three scalar `:politicas` axes (`:retries`,
2915    /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
2916    /// coherence surface every production overlay (Envoy, Istio,
2917    /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
2918    /// the pair is validated in isolation by the per-axis brackets in
2919    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
2920    /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
2921    /// whose axes are each individually well-formed can still name a
2922    /// structurally-truncated retry policy the rate limiter refuses to
2923    /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
2924    /// per-axis bracket and is nonetheless a retry policy the substrate
2925    /// cannot honor: one client's initial attempt plus five retries is
2926    /// six attempts, but the token bucket admits at most three tokens
2927    /// per one-second refill window, so the fourth attempt onward is
2928    /// blocked by the rate limiter itself — the substrate declared six
2929    /// attempts and structurally allows three. Envoy's
2930    /// `local_rate_limit.token_bucket.max_tokens` paired against
2931    /// `retry_policy.num_retries` carries the identical relation; every
2932    /// production playbook that pairs the two axes recommends sizing
2933    /// the bucket capacity above any single client's retry budget so
2934    /// the retry policy is not silently truncated by the same rate
2935    /// limiter it feeds through.
2936    ///
2937    /// The typed test is the integer inequality
2938    /// `rl.rate() >= retries + 1` — the retries count is the *number of
2939    /// retry attempts beyond the initial* (Envoy's
2940    /// `retry_policy.num_retries` semantics), so a client makes at most
2941    /// `retries + 1` attempts per client call, each of which consumes
2942    /// one token from the local rate-limit bucket. For the bucket to
2943    /// *admit* the retry burst without dropping tokens, its capacity
2944    /// must not be reached by one client's attempts alone:
2945    /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
2946    /// boundary case `rate == retries + 1` accepts (the bucket admits
2947    /// exactly one client's full retry sequence per refill window —
2948    /// retries fully executed). The strict-below case `rate <= retries`
2949    /// rejects (the bucket exhausts before retries complete, silently
2950    /// truncating the declared retry policy mid-run — the same
2951    /// declared-but-structurally-inert footgun the sibling per-axis cap
2952    /// arms close on the single-axis surfaces). The equivalent
2953    /// coherent-direction form `rl.rate() > retries` sidesteps the
2954    /// `retries + 1` addition entirely (both `rate` and `retries` are
2955    /// `u32`; the `>` comparison is total on the type with no overflow
2956    /// against past-the-guard struct-literal `retries` values a caller
2957    /// might pass before `validate` runs), matching the peer
2958    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
2959    /// `>`-comparison discipline on the sibling
2960    /// `(:retries, :max-failures)` pair.
2961    ///
2962    /// Vacuously `true` when either axis is absent — a `:politicas`
2963    /// that names only one of the pair declares no relation for the
2964    /// substrate to hold it to (`:retries` alone is a client-retry
2965    /// policy with no rate limiter to saturate; `:rate-limit` alone is
2966    /// a token-bucket declaration whose per-client attempt count is
2967    /// unconstrained by the substrate, so no per-client saturation
2968    /// bound on tokens-per-client-call is knowable at author time).
2969    /// Same "unset means the cluster default applies, not zero"
2970    /// partition [`MeshPolicy::is_empty`] and the three sibling
2971    /// cross-axis predicates
2972    /// ([`MeshPolicy::breaker_window_observes_timeout`],
2973    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
2974    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
2975    ///
2976    /// Lifted as a typed predicate on the substrate primitive rather
2977    /// than open-coded at the validate gate so every downstream
2978    /// consumer of the pair reaches the invariant through one dispatch:
2979    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2980    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2981    /// (MESH-COMPOSITION §III.2 #3) that must emit
2982    /// `local_rate_limit.token_bucket.max_tokens` alongside
2983    /// `retry_policy.num_retries` as one coherent Envoy block, the
2984    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
2985    /// admission webhook, and the future per-`:contratos`-edge
2986    /// `:politicas` override the same roadmap acknowledges — which
2987    /// resolves an *effective* pair per edge (edge-level `:retries`
2988    /// against the Aplicacao-level `:rate-limit`, or vice versa) and
2989    /// so must re-check the relation on a pair neither axis's
2990    /// declaration site can see whole. Naming the invariant once means
2991    /// that resolver folds this predicate over its resolved pair
2992    /// instead of re-deriving the comparison, exactly as the three
2993    /// sibling cross-axis predicates name the
2994    /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
2995    /// `(:retries, :max-failures)` relations for their own consumers,
2996    /// closing the fourth and last cross-axis relation on the scalar
2997    /// `:politicas` axis-triple.
2998    #[must_use]
2999    pub const fn rate_limit_admits_retry_burst(&self) -> bool {
3000        match (self.retries(), self.rate_limit()) {
3001            (Some(retries), Some(rl)) => rl.rate() > retries,
3002            _ => true,
3003        }
3004    }
3005
3006    /// Substrate-canonical fold over the four cross-axis coherence
3007    /// predicates on the `:politicas` slot — returns the *first*
3008    /// cross-axis violation (as its [`AplicacaoError`] variant) in the
3009    /// canonical "more-foundational-cross-axis first" ordering
3010    /// [`MeshPolicy::breaker_window_observes_timeout`] on
3011    /// `(:timeout, :circuit-breaker :window)` →
3012    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
3013    /// `(:rate-limit, :circuit-breaker)` →
3014    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
3015    /// `(:retries, :circuit-breaker :max-failures)` →
3016    /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
3017    /// :rate-limit)`. Returns `None` when every cross-axis relation
3018    /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
3019    /// coherent shape both land here).
3020    ///
3021    /// The ordering discipline this method encodes was open-coded four
3022    /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
3023    /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
3024    /// "cross-axis gate fires only when :<axis> is present"); let <b>
3025    /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
3026    /// axis-fetch step depended on the predicate having just returned
3027    /// `false` (structurally guaranteed both paired axes are `Some`,
3028    /// but the compiler cannot see through the predicate body, so
3029    /// every arm re-called the accessor with `.expect(…)` to reach
3030    /// the axis it just tested). Two unsound consequences: (1) the
3031    /// validate gate carried eight `.expect(…)` panic call sites the
3032    /// predicate contract already forbids on every well-typed input
3033    /// but the type system does not enforce; (2) the
3034    /// "which-cross-axis-fires-first-when-two-apply" contract lived
3035    /// twice — once in each predicate's own doc comments and once at
3036    /// the validate call site's four-arm cascade. Lifting the four-arm
3037    /// cascade onto this substrate primitive collapses both
3038    /// duplications: the predicate contract and the axis-fetch step
3039    /// live in the same body (no `.expect(…)` — the pattern match at
3040    /// each arm rebinds the paired axes so their `Some` presence is a
3041    /// compile-time property of the local scope), and the ordering
3042    /// discipline lives once at the top of the primitive rather than
3043    /// scattered across four sibling doc-comment blocks that must
3044    /// stay in lockstep.
3045    ///
3046    /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
3047    /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
3048    /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
3049    /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
3050    /// §III.2 #3 acknowledges — the last of which resolves an
3051    /// *effective* per-edge pair and must emit *the same* diagnostic
3052    /// on the same paired-axis input as `feira build`) reaches through
3053    /// one call rather than re-inlining the four pattern-matches +
3054    /// accessor-fetches + variant-constructions + ordering-cascade.
3055    ///
3056    /// Returns owned copies of every axis carried into the diagnostic:
3057    /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
3058    /// occurs on the happy path when no violation fires.
3059    #[must_use]
3060    pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
3061        // Ordering discipline this fold encodes matches the four
3062        // per-arm predicate doc comments' pairwise-ordering contract:
3063        // window-below-timeout wins over every arm that names `:rate-
3064        // limit` or `:retries` (its diagnostic is more self-locating —
3065        // the pair is a per-call-deadline invariant every synchronous
3066        // edge carries whether or not `:rate-limit`/`:retries` is
3067        // declared); the starve arm wins over the two retry arms (its
3068        // diagnostic reasons across the token-bucket-vs-breaker
3069        // relation, an axis the retry arms do not touch); the
3070        // retries-saturate arm wins over the retries-burst arm (its
3071        // diagnostic reasons across the per-client-vs-breaker
3072        // relation, which carries whether or not `:rate-limit` is
3073        // declared). Each arm rebinds the paired axes through the
3074        // pattern match, so the `.expect(…)` panics the four-block
3075        // cascade at `validate_politicas` carried collapse to no-op
3076        // pattern rebindings the compiler statically proves exhaust.
3077        if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
3078            && !self.breaker_window_observes_timeout()
3079        {
3080            return Some(AplicacaoError::policy_breaker_window_below_timeout(&cb, t));
3081        }
3082        if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
3083            && !self.breaker_can_trip_under_rate_limit()
3084        {
3085            return Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
3086                rate: rl.rate(),
3087                rl_window: rl.window(),
3088                max_failures: cb.max_failures(),
3089                cb_window: cb.window(),
3090            });
3091        }
3092        if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
3093            && !self.retries_fit_under_breaker_trip_threshold()
3094        {
3095            return Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
3096                retries,
3097                max_failures: cb.max_failures(),
3098            });
3099        }
3100        if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
3101            && !self.rate_limit_admits_retry_burst()
3102        {
3103            return Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
3104                retries,
3105                rate: rl.rate(),
3106            });
3107        }
3108        None
3109    }
3110
3111    /// Substrate-canonical compound entry gate over the whole
3112    /// `:politicas` typed slot — folds every per-axis bracket
3113    /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
3114    /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
3115    /// window-canonical-form) *and* the compound cross-axis fold
3116    /// [`MeshPolicy::first_cross_axis_violation`] into one call every
3117    /// consumer of a validated [`MeshPolicy`] reaches through.
3118    ///
3119    /// Returns the first violation as its [`AplicacaoError`] variant,
3120    /// or `Ok(())` when every per-axis value lies in its accept-set and
3121    /// every cross-axis relation holds. Per-axis brackets run strictly
3122    /// before the cross-axis fold — the sibling
3123    /// [`AplicacaoSpec::validate_politicas`] gate carried the same
3124    /// ordering discipline for the same reason: a per-axis
3125    /// structurally-invalid value (a `Duration::ZERO` `:window`, an
3126    /// above-cap `:rate-limit` rate) surfaces its own self-locating
3127    /// diagnostic first, ahead of any cross-axis arm that would send
3128    /// the author to reconcile two values one of which is not a
3129    /// meaningful window at all. Within the per-axis phase, arms fire
3130    /// in the same slot-order the peer per-axis brackets carry
3131    /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
3132    /// each internally ordered zero-floor before canonical-form before
3133    /// cap by [`crate::render::require_positive_bounded_u32`] /
3134    /// [`crate::render::require_positive_canonical_bounded_duration`]);
3135    /// within the cross-axis phase, arms fire in the canonical
3136    /// more-foundational-cross-axis-first ordering
3137    /// [`MeshPolicy::first_cross_axis_violation`] encodes.
3138    ///
3139    /// Lifted as a typed method on the substrate primitive so every
3140    /// downstream consumer of a validated [`MeshPolicy`] reaches the
3141    /// invariant through one dispatch: the
3142    /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
3143    /// body collapses to `self.politicas().validate()`), the future
3144    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3145    /// admission webhook, the future per-`:contratos`-edge `:politicas`
3146    /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
3147    /// which resolves an *effective* per-edge [`MeshPolicy`] and must
3148    /// emit *the same* diagnostic on the same input as `feira build`.
3149    /// Naming the compound gate once on the substrate primitive means
3150    /// every downstream consumer inherits both the per-axis brackets
3151    /// *and* the cross-axis fold through one call, rather than
3152    /// re-inlining the four-per-axis + one-cross-axis cascade in
3153    /// lockstep with `validate_politicas`.
3154    ///
3155    /// Peer of the per-kind compound entry gates lifted at
3156    /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
3157    /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
3158    /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
3159    /// layout axis, and the sibling compound cross-axis fold
3160    /// [`MeshPolicy::first_cross_axis_violation`] on the same
3161    /// `:politicas` axis — extended here onto the per-slot per-axis +
3162    /// cross-axis compound entry gate that folds both surfaces.
3163    pub fn validate(&self) -> Result<(), AplicacaoError> {
3164        if let Some(t) = self.timeout() {
3165            crate::render::require_positive_canonical_bounded_duration(
3166                t,
3167                POLICY_TIMEOUT_MAX,
3168                || AplicacaoError::PolicyTimeoutZero,
3169                AplicacaoError::policy_timeout_not_canonical,
3170                AplicacaoError::policy_timeout_exceeds_cap,
3171            )?;
3172        }
3173        if let Some(r) = self.retries() {
3174            crate::render::require_positive_bounded_u32(
3175                r,
3176                POLICY_RETRIES_MAX,
3177                || AplicacaoError::PolicyRetriesZero,
3178                AplicacaoError::policy_retries_exceeds_cap,
3179            )?;
3180        }
3181        if let Some(cb) = self.circuit_breaker() {
3182            crate::render::require_positive_bounded_u32(
3183                cb.max_failures(),
3184                POLICY_BREAKER_MAX_FAILURES_MAX,
3185                || AplicacaoError::PolicyBreakerZeroFailures,
3186                AplicacaoError::policy_breaker_max_failures_exceeds_cap,
3187            )?;
3188            crate::render::require_positive_canonical_bounded_duration(
3189                cb.window(),
3190                POLICY_BREAKER_WINDOW_MAX,
3191                || AplicacaoError::PolicyBreakerZeroWindow,
3192                AplicacaoError::policy_breaker_window_not_canonical,
3193                AplicacaoError::policy_breaker_window_exceeds_cap,
3194            )?;
3195        }
3196        if let Some(rl) = self.rate_limit() {
3197            crate::render::require_positive_bounded_u32(
3198                rl.rate(),
3199                POLICY_RATE_LIMIT_MAX,
3200                || AplicacaoError::PolicyRateLimitZero,
3201                AplicacaoError::policy_rate_limit_exceeds_cap,
3202            )?;
3203            if rl.canonical_unit().is_none() {
3204                return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
3205                    rl.window(),
3206                ));
3207            }
3208        }
3209        if let Some(err) = self.first_cross_axis_violation() {
3210            return Err(err);
3211        }
3212        Ok(())
3213    }
3214
3215    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
3216    /// per-call-deadline scalar accessor every consumer of the
3217    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
3218    /// returns the author-declared `:politicas :timeout` typed
3219    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
3220    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
3221    /// is `Copy`, so the accessor returns by value; no borrow of
3222    /// `&self` past the call). `None` when the slot is absent (the
3223    /// "cluster default applies — typically the gateway class's
3224    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
3225    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
3226    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
3227    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
3228    /// round-trips to a rendered `HTTPRoute` structurally identical to
3229    /// one that omits the slot).
3230    ///
3231    /// The `:politicas :timeout` slot carries the "no infinite blocking"
3232    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
3233    /// the typed slot's `Option<Duration>` accept-set (zero-floor
3234    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
3235    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
3236    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
3237    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
3238    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
3239    /// Every downstream consumer that reads the per-call cap keys off
3240    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3241    /// renderers key off to decide "emit :politicas overlay" vs "skip
3242    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3243    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
3244    /// fans the deadline into every rule via
3245    /// [`crate::render::single_field_overlay`], the future M4 per-
3246    /// Aplicacao Gateway API reconciler materialization pass, the
3247    /// future per-`:contratos`-edge timeout-override overlay the
3248    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
3249    ///
3250    /// Prior to this lift the `.timeout` field was accessed inline at
3251    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
3252    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
3253    /// …)` call — two open-coded field-accesses that expressed no
3254    /// compile-time link back to the typed slot. A future extension of
3255    /// the `:politicas :timeout` axis to a richer author surface — a
3256    /// per-`:contratos`-edge timeout override the operator pins through
3257    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
3258    /// roadmap acknowledges, a per-cluster timeout-default overlay the
3259    /// M4 CR materializer resolves per-CR, a split of the single
3260    /// per-call `Duration` into a richer `{request, backendRequest}`
3261    /// pair once the Gateway API's per-rule `timeouts` block grows the
3262    /// upstream-facing backendRequest arm alongside the client-facing
3263    /// request arm — would have had to be threaded through both open-
3264    /// coded copies in lockstep or the emptiness predicate and the
3265    /// caixa-mesh emit path would silently disagree on which per-call
3266    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
3267    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
3268    /// == false` while the renderer's overlay-emit path silently read
3269    /// a drifted other value, or vice versa: an author's `:timeout
3270    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
3271    /// the emptiness predicate still classified the policy as non-
3272    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
3273    /// | grep -A2 timeouts` audit would land on a route whose author's
3274    /// typed slot value silently vanished at the renderer layer).
3275    /// Lifting the resolution to a typed method on the substrate
3276    /// primitive means every downstream consumer of the Aplicacao's
3277    /// per-`:politicas` deadline surface reaches for exactly one typed
3278    /// dispatch — the resolver's accept-set migrates as a unit on any
3279    /// future axis addition.
3280    ///
3281    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
3282    /// family (sibling of the peer per-`:politicas`
3283    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
3284    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
3285    /// `Option<bool>` accessor — same "one typed dispatch on the
3286    /// substrate primitive, thin projections at each consumer"
3287    /// discipline extended onto the peer per-`:politicas` typed-
3288    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
3289    /// numeric-Copy-T scalar" projection pattern the sibling
3290    /// `Option<u32>` / `Option<bool>` lifts opened, since every
3291    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
3292    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
3293    /// than a scalar). Named `timeout()` to match the storage field's
3294    /// name; the accessor's identity maps onto the canonical MESH-
3295    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
3296    #[must_use]
3297    pub const fn timeout(&self) -> Option<Duration> {
3298        self.timeout
3299    }
3300
3301    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
3302    /// retry-budget scalar accessor every consumer of the Aplicacao's
3303    /// Gateway API v1.x per-rule retry-cap keys off — returns the
3304    /// author-declared `:politicas :retries` typed `u32` verbatim as an
3305    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
3306    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
3307    /// value; no borrow of `&self` past the call). `None` when the slot
3308    /// is absent (the "cluster default applies — typically 'no retries
3309    /// beyond a single dispatch attempt'" arm the caixa-mesh
3310    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
3311    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
3312    /// this predicate too, so an authored-but-unset `:politicas
3313    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
3314    /// identical to one that omits the slot).
3315    ///
3316    /// The `:politicas :retries` slot carries the "transient failure
3317    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
3318    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
3319    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3320    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
3321    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
3322    /// count scalar the caixa-mesh `retry_overlay` builder writes.
3323    /// Every downstream consumer that reads the retry cap keys off this
3324    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3325    /// renderers key off to decide "emit :politicas overlay" vs "skip
3326    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3327    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
3328    /// the value into every rule via [`crate::render::single_field_overlay`],
3329    /// the future M4 per-Aplicacao Gateway API reconciler
3330    /// materialization pass, the future per-`:contratos`-edge retry-
3331    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
3332    /// acknowledges).
3333    ///
3334    /// Prior to this lift the `.retries` field was accessed inline at
3335    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
3336    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
3337    /// …)` call — two open-coded field-accesses that expressed no
3338    /// compile-time link back to the typed slot. A future extension of
3339    /// the `:politicas :retries` axis to a richer author surface — a
3340    /// per-`:contratos`-edge retry override the operator pins through a
3341    /// future `:contratos :retries` slot, a per-cluster retry-default
3342    /// overlay the M4 CR materializer resolves per-CR, a promotion of
3343    /// the plain `u32` attempt-count to a richer `{attempts, codes,
3344    /// backoff}` sub-block once the Gateway API grows the peer
3345    /// `retry.codes` / `retry.backoff` axes — would have had to be
3346    /// threaded through both open-coded copies in lockstep or the
3347    /// emptiness predicate and the caixa-mesh emit path would silently
3348    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
3349    /// (a `:politicas` block whose only axis is a `Some :retries` would
3350    /// satisfy `is_empty() == false` while the renderer's overlay-emit
3351    /// path silently read a drifted other value, or vice versa: an
3352    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
3353    /// block while the emptiness predicate still classified the policy
3354    /// as non-empty). Lifting the resolution to a typed method on the
3355    /// substrate primitive means every downstream consumer of the
3356    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
3357    /// one typed dispatch — the resolver's accept-set migrates as a
3358    /// unit on any future axis addition.
3359    ///
3360    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
3361    /// family (sibling of the peer per-`:politicas`
3362    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
3363    /// same "one typed dispatch on the substrate primitive, thin
3364    /// projections at each consumer" discipline extended onto the
3365    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
3366    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
3367    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
3368    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
3369    /// fold on). Named `retries()` to match the storage field's name;
3370    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
3371    /// §III.2 vocabulary the slot's docstring already carries.
3372    #[must_use]
3373    pub const fn retries(&self) -> Option<u32> {
3374        self.retries
3375    }
3376
3377    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
3378    /// enforcement-toggle scalar accessor every consumer of the
3379    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
3380    /// — returns the author-declared `:politicas :mtls-required` typed
3381    /// bool verbatim as an `Option<bool>`, copied out of the typed
3382    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
3383    /// the accessor returns by value; no borrow of `&self` past the
3384    /// call). `None` when the slot is absent (the "cluster default
3385    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
3386    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
3387    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
3388    /// this predicate too, so an authored-but-unset `:politicas
3389    /// (:mtls-required ())` round-trips to a rendered
3390    /// `CiliumNetworkPolicy` structurally identical to one that omits
3391    /// the slot).
3392    ///
3393    /// The `:politicas :mtls-required` slot carries the "explicit opt-
3394    /// out only, sandboxing-by-default" mTLS-enforcement toggle
3395    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
3396    /// `{None, Some(true), Some(false)}` accept-set maps onto the
3397    /// Cilium `authentication.mode` bijection through
3398    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
3399    /// handshake enforced), `Some(false) → "disabled"` (handshake
3400    /// skipped — the debug-edge opt-out), `None` → omit the block
3401    /// (cluster default applies). Every downstream consumer that
3402    /// reads the toggle keys off this scalar (the
3403    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3404    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3405    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
3406    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
3407    /// ingress rule via [`crate::render::single_field_overlay`], the
3408    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
3409    /// materialization pass, the future per-`:contratos`-edge mTLS
3410    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3411    ///
3412    /// Prior to this lift the `.mtls_required` field was accessed
3413    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3414    /// `self.mtls_required.is_none()` arm and caixa-mesh's
3415    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
3416    /// two open-coded field-accesses that expressed no compile-time
3417    /// link back to the typed slot. A future extension of the
3418    /// `:politicas :mtls-required` axis to a richer author surface —
3419    /// a per-`:contratos`-edge mTLS override the operator pins through
3420    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
3421    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
3422    /// M4 CR materializer resolves per-CR, a three-valued
3423    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
3424    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
3425    /// would have had to be threaded through both open-coded copies in
3426    /// lockstep or the emptiness predicate and the caixa-mesh emit
3427    /// path would silently disagree on which toggle a given
3428    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
3429    /// axis is a `Some`
3430    /// `:mtls-required` would satisfy `is_empty() == false` while the
3431    /// renderer's overlay-emit path silently read a drifted other
3432    /// value, or vice versa). Lifting the resolution to a typed method
3433    /// on the substrate primitive means every downstream consumer of
3434    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
3435    /// for exactly one typed dispatch — the resolver's accept-set
3436    /// migrates as a unit on any future axis addition.
3437    ///
3438    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
3439    /// family (peer of the sibling per-`:placement`
3440    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
3441    /// same "one typed dispatch on the substrate primitive, thin
3442    /// projections at each consumer" discipline extended onto the
3443    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
3444    /// the "optional per-slot Copy-T scalar" projection pattern the
3445    /// sibling per-`:politicas` `:retries` (Option<u32>) /
3446    /// `:timeout` (Option<Duration>) future lifts fold on). Named
3447    /// `mtls_required()` to match the storage field's name; the
3448    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3449    /// §III.2 vocabulary the slot's docstring already carries.
3450    #[must_use]
3451    pub const fn mtls_required(&self) -> Option<bool> {
3452        self.mtls_required
3453    }
3454
3455    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
3456    /// `local_rate_limit`-mesh token-bucket-declaration scalar
3457    /// accessor every consumer of the Aplicacao's per-`:politicas`
3458    /// per-`(rate, window)` rate-limit surface keys off — returns the
3459    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
3460    /// verbatim as an `Option<RateLimit>`, copied out of the typed
3461    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
3462    /// `Copy`, so the accessor returns by value; no borrow of `&self`
3463    /// past the call). `None` when the slot is absent (the "cluster
3464    /// default applies — typically 'no per-Aplicacao rate declaration,
3465    /// gateway-class per-listener default applies'" arm the future
3466    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
3467    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
3468    /// `rate_limit().is_none()` arm reads this predicate too, so an
3469    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
3470    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
3471    /// identical to one that omits the slot).
3472    ///
3473    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
3474    /// token-bucket rate declaration" contract (MESH-COMPOSITION
3475    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
3476    /// (rate lower-bounded by 1 through
3477    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3478    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
3479    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
3480    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
3481    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
3482    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
3483    /// `:politicas` overlay emits. Every downstream consumer that
3484    /// reads the rate declaration keys off this scalar (the
3485    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3486    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3487    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
3488    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
3489    /// `rl.window` against [`is_canonical_rate_limit_window`], the
3490    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
3491    /// the future per-`:contratos`-edge rate-limit override the
3492    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3493    ///
3494    /// Prior to this lift the `.rate_limit` field was accessed inline
3495    /// at two sites — [`MeshPolicy::is_empty`]'s
3496    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
3497    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
3498    /// field-accesses that expressed no compile-time link back to the
3499    /// typed slot. A future extension of the `:politicas :rate-limit`
3500    /// axis to a richer author surface — a per-`:contratos`-edge
3501    /// rate-limit override the operator pins through a future
3502    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
3503    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
3504    /// the M4 CR materializer resolves per-CR, a promotion of the
3505    /// plain `(rate, window)` scalar pair to a richer
3506    /// `{rate, window, burst, key}` sub-block once Envoy's
3507    /// `local_rate_limit` grows the peer `burst_size` /
3508    /// `descriptor_key` axes — would have had to be threaded through
3509    /// both open-coded copies in lockstep or the emptiness predicate
3510    /// and the validate gate would silently disagree on which rate
3511    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
3512    /// block whose only axis is a `Some :rate-limit` would satisfy
3513    /// `is_empty() == false` while the validate path silently read a
3514    /// drifted other value, or vice versa: an author's
3515    /// `:rate-limit "100/s"` would omit the value-shape gate while the
3516    /// emptiness predicate still classified the policy as non-empty).
3517    /// Lifting the resolution to a typed method on the substrate
3518    /// primitive means every downstream consumer of the Aplicacao's
3519    /// per-`:politicas` rate-limit surface reaches for exactly one
3520    /// typed dispatch — the resolver's accept-set migrates as a unit
3521    /// on any future axis addition.
3522    ///
3523    /// First `Option<Copy-composite-T>`-return accessor on the M3
3524    /// mesh-slot family — closes the last un-lifted per-`:politicas`
3525    /// scalar-value axis. Peer of the sibling per-`:politicas`
3526    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
3527    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
3528    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
3529    /// "one typed dispatch on the substrate primitive, thin
3530    /// projections at each consumer" discipline extended onto the
3531    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
3532    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
3533    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
3534    /// sub-accessors rather than a top-level accessor because
3535    /// consumers reach for the axes not the aggregate). Named
3536    /// `rate_limit()` to match the storage field's name; the
3537    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3538    /// §III.2 vocabulary the slot's docstring already carries.
3539    #[must_use]
3540    pub const fn rate_limit(&self) -> Option<RateLimit> {
3541        self.rate_limit
3542    }
3543
3544    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
3545    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
3546    /// declaration scalar accessor every consumer of the Aplicacao's
3547    /// per-`:politicas` breaker declaration keys off — returns the
3548    /// author-declared `:politicas :circuit-breaker` typed
3549    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
3550    /// copied out of the typed slot's own `Option<CircuitBreaker>`
3551    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
3552    /// by value; no borrow of `&self` past the call). `None` when the
3553    /// slot is absent (the "cluster default applies — typically 'no
3554    /// per-Aplicacao breaker declaration, gateway-class per-listener
3555    /// default applies'" arm the future caixa-mesh
3556    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
3557    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
3558    /// arm reads this predicate too, so an authored-but-unset
3559    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
3560    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
3561    /// that omits the slot).
3562    ///
3563    /// The `:politicas :circuit-breaker` slot carries the
3564    /// "per-Aplicacao consecutive-transient-failure trip declaration"
3565    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3566    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
3567    /// zero-floor rejected through
3568    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3569    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
3570    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
3571    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
3572    /// canonical-form pinned through
3573    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
3574    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
3575    /// bijection the future `CiliumClusterwideEnvoyConfig`
3576    /// per-`:politicas` overlay emits. Every downstream consumer that
3577    /// reads the breaker declaration keys off this scalar (the
3578    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3579    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3580    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
3581    /// that brackets `cb.max_failures()` against
3582    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
3583    /// [`POLICY_BREAKER_WINDOW_MAX`] via
3584    /// [`crate::render::require_positive_canonical_bounded_duration`],
3585    /// the future M4 per-Aplicacao Envoy reconciler materialization
3586    /// pass, the future per-`:contratos`-edge breaker override the
3587    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3588    ///
3589    /// Prior to this lift the `.circuit_breaker` field was accessed
3590    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3591    /// `self.circuit_breaker.is_none()` arm and the
3592    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
3593    /// bind — two open-coded field-accesses that expressed no
3594    /// compile-time link back to the typed slot. A future extension of
3595    /// the `:politicas :circuit-breaker` axis to a richer author
3596    /// surface — a per-`:contratos`-edge breaker override the operator
3597    /// pins through a future `:contratos :circuit-breaker` slot the
3598    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
3599    /// breaker-default overlay the M4 CR materializer resolves per-CR,
3600    /// a promotion of the plain `(max_failures, window)` scalar pair to
3601    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
3602    /// sub-block once Envoy's `outlier_detection` grows the peer
3603    /// ejection-percentage / ejection-time axes — would have had to be
3604    /// threaded through both open-coded copies in lockstep or the
3605    /// emptiness predicate and the validate gate would silently
3606    /// disagree on which breaker declaration a given [`MeshPolicy`]
3607    /// resolves to (a `:politicas` block whose only axis is a
3608    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
3609    /// the validate path silently read a drifted other value, or vice
3610    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
3611    /// "60s"))` would omit the value-shape gate while the emptiness
3612    /// predicate still classified the policy as non-empty). Lifting
3613    /// the resolution to a typed method on the substrate primitive
3614    /// means every downstream consumer of the Aplicacao's
3615    /// per-`:politicas` breaker surface reaches for exactly one typed
3616    /// dispatch — the resolver's accept-set migrates as a unit on any
3617    /// future axis addition.
3618    ///
3619    /// Second `Option<Copy-composite-T>`-return accessor on the M3
3620    /// mesh-slot family (sibling of the peer per-`:politicas`
3621    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
3622    /// on the same composite-Copy shape, and of the sibling per-
3623    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
3624    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
3625    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
3626    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
3627    /// same "one typed dispatch on the substrate primitive, thin
3628    /// projections at each consumer" discipline extended onto the last
3629    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
3630    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
3631    /// match the storage field's name; the accessor's identity maps
3632    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3633    /// docstring already carries. Closes the last unlifted
3634    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
3635    /// reader now routes through a typed dispatch on the substrate
3636    /// primitive.
3637    #[must_use]
3638    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
3639        self.circuit_breaker
3640    }
3641}
3642
3643#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
3644#[serde(rename_all = "camelCase")]
3645pub struct CircuitBreaker {
3646    pub max_failures: u32,
3647    #[serde(with = "supervisor::duration_codec_required")]
3648    pub window: Duration,
3649}
3650
3651impl CircuitBreaker {
3652    /// Substrate-canonical per-`:politicas :circuit-breaker`
3653    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
3654    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3655    /// breaker trip-count keys off — returns the author-declared
3656    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
3657    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
3658    /// so the accessor returns by value; no borrow of `&self` past the
3659    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
3660    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
3661    /// axis; a `CircuitBreaker` past pattern-match is definitionally
3662    /// present, and its `:max-failures` field carries the trip count as a
3663    /// required-axis scalar).
3664    ///
3665    /// The `:politicas :circuit-breaker :max-failures` axis carries the
3666    /// "consecutive-transient-failure trip threshold" contract
3667    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
3668    /// (zero-floor rejected through
3669    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3670    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
3671    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
3672    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
3673    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
3674    /// Every downstream consumer that reads the trip threshold keys off
3675    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3676    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
3677    /// canonical `require_positive_bounded_u32` helper, the future M4
3678    /// per-Aplicacao Envoy config reconciler materialization pass, the
3679    /// future per-`:contratos`-edge breaker-override overlay the
3680    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3681    ///
3682    /// Prior to this lift the `.max_failures` field was accessed inline
3683    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
3684    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
3685    /// open-coded field-access that expressed no compile-time link back
3686    /// to the typed sub-struct axis. A future extension of the
3687    /// `:max-failures` axis to a richer author surface — a
3688    /// per-`:contratos`-edge breaker override the operator pins through a
3689    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3690    /// #3 roadmap acknowledges, a per-cluster max-failures-default
3691    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3692    /// plain `u32` trip count to a richer
3693    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3694    /// tuple once Envoy's `outlier_detection` block's peer axes come into
3695    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3696    /// count arms — would have had to be threaded through every open-
3697    /// coded copy in lockstep or the validate gate and the future M4
3698    /// emit path would silently disagree on which trip threshold a given
3699    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3700    /// would satisfy validate while the emit path silently read a drifted
3701    /// other value, or vice versa: a validated typed slot would land at
3702    /// the emit boundary as a no-op breaker whose trip threshold is
3703    /// structurally never reached). Lifting the resolution to a typed
3704    /// method on the substrate primitive means every downstream consumer
3705    /// of the Aplicacao's per-`:politicas :circuit-breaker`
3706    /// trip-threshold surface reaches for exactly one typed dispatch —
3707    /// the resolver's accept-set migrates as a unit on any future axis
3708    /// addition.
3709    ///
3710    /// First sub-struct scalar accessor on the M3 mesh-slot family
3711    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3712    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3713    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3714    /// closes the last unlifted per-`:politicas` scalar-value axis after
3715    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3716    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3717    /// Same "one typed dispatch on the substrate primitive, thin
3718    /// projections at each consumer" discipline the peer
3719    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3720    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3721    /// [`Membro::versao_requirement`] (a40b0e3),
3722    /// [`Entrada::destination`] (6db982c) accessors carry on their
3723    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3724    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3725    /// match the storage field's name; the accessor's identity maps onto
3726    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3727    /// docstring already carries.
3728    #[must_use]
3729    pub const fn max_failures(&self) -> u32 {
3730        self.max_failures
3731    }
3732
3733    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3734    /// Envoy-outlier-detection rolling-observation-interval scalar
3735    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3736    /// breaker rolling-window duration keys off — returns the
3737    /// author-declared `:politicas :circuit-breaker :window` typed
3738    /// `Duration` verbatim, copied out of the typed slot's own
3739    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3740    /// by value; no borrow of `&self` past the call). Non-optional (the
3741    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3742    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3743    /// `CircuitBreaker` past pattern-match is definitionally present,
3744    /// and its `:window` field carries the rolling-observation interval
3745    /// as a required-axis scalar).
3746    ///
3747    /// The `:politicas :circuit-breaker :window` axis carries the
3748    /// "consecutive-transient-failure rolling-observation interval"
3749    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3750    /// `Duration` accept-set (zero-floor rejected through
3751    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3752    /// residue rejected through
3753    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3754    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3755    /// Envoy `outlier_detection.interval` per-cluster
3756    /// ejection-observation-interval scalar (equivalently the future
3757    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3758    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3759    /// consumer that reads the rolling-observation interval keys off
3760    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3761    /// integer-millisecond canonical-form + cap bracket at
3762    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3763    /// [`crate::render::require_positive_canonical_bounded_duration`]
3764    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3765    /// materialization pass, the future per-`:contratos`-edge
3766    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3767    /// acknowledges).
3768    ///
3769    /// Prior to this lift the `.window` field was accessed inline at
3770    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3771    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3772    /// call — one open-coded field-access that expressed no compile-
3773    /// time link back to the typed sub-struct axis. A future extension
3774    /// of the `:window` axis to a richer author surface — a
3775    /// per-`:contratos`-edge window override the operator pins through
3776    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3777    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3778    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3779    /// `Duration` observation interval to a richer
3780    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3781    /// once Envoy's `outlier_detection` block's peer axes come into
3782    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3783    /// the window arms — would have had to be threaded through every
3784    /// open-coded copy in lockstep or the validate gate and the future
3785    /// M4 emit path would silently disagree on which observation
3786    /// interval a given [`CircuitBreaker`] resolves to (an author's
3787    /// `:window "60s"` would satisfy validate while the emit path
3788    /// silently read a drifted other value, or vice versa: a validated
3789    /// typed slot would land at the emit boundary as a breaker whose
3790    /// observation window is structurally so wide that no realistic
3791    /// failure-rate shape can trip it). Lifting the resolution to a
3792    /// typed method on the substrate primitive means every downstream
3793    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3794    /// observation-window surface reaches for exactly one typed
3795    /// dispatch — the resolver's accept-set migrates as a unit on any
3796    /// future axis addition.
3797    ///
3798    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3799    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3800    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3801    /// required-axis, extended onto the per-sub-struct required-`Duration`
3802    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3803    /// axis. Same "one typed dispatch on the substrate primitive, thin
3804    /// projections at each consumer" discipline the peer
3805    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3806    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3807    /// [`Membro::versao_requirement`] (a40b0e3),
3808    /// [`Entrada::destination`] (6db982c) accessors carry on their
3809    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3810    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3811    /// match the storage field's name; the accessor's identity maps onto
3812    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3813    /// docstring already carries.
3814    #[must_use]
3815    pub const fn window(&self) -> Duration {
3816        self.window
3817    }
3818}
3819
3820#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3821pub struct RateLimit {
3822    /// Requests per window.
3823    pub rate: u32,
3824    /// Window duration.
3825    pub window: Duration,
3826}
3827
3828impl RateLimit {
3829    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3830    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3831    /// every consumer of the Aplicacao's per-`:contratos`-edge
3832    /// rate-limit-bucket capacity keys off — returns the author-declared
3833    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3834    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3835    /// returns by value; no borrow of `&self` past the call). Non-optional
3836    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3837    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3838    /// `RateLimit` past pattern-match is definitionally present, and its
3839    /// `:rate` field carries the token-bucket capacity as a required-axis
3840    /// scalar).
3841    ///
3842    /// The `:politicas :rate-limit` `:rate` axis carries the
3843    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3844    /// the typed slot's `u32` accept-set (zero-floor rejected through
3845    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3846    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3847    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3848    /// token-bucket-capacity scalar (equivalently the future
3849    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3850    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3851    /// consumer that reads the token-bucket capacity keys off this
3852    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3853    /// cap bracket that gates on the canonical
3854    /// [`crate::render::require_positive_bounded_u32`] helper, the
3855    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3856    /// emits the `<n>/<s|m|h>` author surface, the future M4
3857    /// per-Aplicacao Envoy config reconciler materialization pass, the
3858    /// future per-`:contratos`-edge rate-limit-override overlay the
3859    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3860    ///
3861    /// Prior to this lift the `.rate` field was accessed inline at three
3862    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3863    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3864    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3865    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3866    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3867    /// field-accesses that expressed no compile-time link back to the
3868    /// typed sub-struct axis. A future extension of the `:rate` axis
3869    /// to a richer author surface — a per-`:contratos`-edge rate
3870    /// override the operator pins through a future `:contratos :rate`
3871    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3872    /// per-cluster rate-default overlay the M4 CR materializer resolves
3873    /// per-CR, a promotion of the plain `u32` token capacity to a
3874    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3875    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3876    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3877    /// before the token arms — would have had to be threaded through
3878    /// every open-coded copy in lockstep or the validate gate, the
3879    /// codec's render path, and the future M4 emit path would silently
3880    /// disagree on which token capacity a given [`RateLimit`] resolves
3881    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3882    /// while the render / emit paths silently read a drifted other
3883    /// value, or vice versa: a validated typed slot would land at the
3884    /// emit boundary as a no-op limiter whose token capacity is
3885    /// structurally so high that no realistic per-edge traffic shape
3886    /// can drain it). Lifting the resolution to a typed method on the
3887    /// substrate primitive means every downstream consumer of the
3888    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3889    /// reaches for exactly one typed dispatch — the resolver's
3890    /// accept-set migrates as a unit on any future axis addition.
3891    ///
3892    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3893    /// in shape to the peer per-`CircuitBreaker`
3894    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3895    /// on the peer per-sub-struct required-axis, extended onto the
3896    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3897    /// required-axis scalar" projection pattern the sibling
3898    /// [`RateLimit::window`] future lift folds on. Same "one typed
3899    /// dispatch on the substrate primitive, thin projections at each
3900    /// consumer" discipline the peer [`WitContract::source`] /
3901    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3902    /// (0804823), [`Membro::nome`] (4a32abf),
3903    /// [`Membro::versao_requirement`] (a40b0e3),
3904    /// [`Entrada::destination`] (6db982c),
3905    /// [`CircuitBreaker::max_failures`] (3a74062),
3906    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3907    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3908    /// to match the storage field's name; the accessor's identity maps
3909    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3910    /// docstring already carries.
3911    #[must_use]
3912    pub const fn rate(&self) -> u32 {
3913        self.rate
3914    }
3915
3916    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3917    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3918    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3919    /// rate-limit-bucket refill period keys off — returns the
3920    /// author-declared `:politicas :rate-limit` typed `Duration`
3921    /// verbatim, copied out of the typed slot's own `Duration` storage
3922    /// (`Duration` is `Copy`, so the accessor returns by value; no
3923    /// borrow of `&self` past the call). Non-optional (the surrounding
3924    /// `Option<RateLimit>` is the "slot present?" projection at the
3925    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3926    /// pattern-match is definitionally present, and its `:window`
3927    /// field carries the token-bucket refill period as a required-axis
3928    /// scalar).
3929    ///
3930    /// The `:politicas :rate-limit` `:window` axis carries the
3931    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3932    /// — the typed slot's `Duration` accept-set (constrained to the
3933    /// three canonical windows `{1s, 60s, 3600s}` the
3934    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3935    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3936    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3937    /// per-cluster token-bucket-refill-period scalar (equivalently the
3938    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3939    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3940    /// consumer that reads the token-bucket refill period keys off
3941    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3942    /// canonical-window gate that keys off
3943    /// [`is_canonical_rate_limit_window`], the
3944    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3945    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3946    /// [`rate_limit_window_unit`] and non-canonical fallback via
3947    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3948    /// reconciler materialization pass, the future per-`:contratos`-
3949    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3950    /// roadmap acknowledges).
3951    ///
3952    /// Prior to this lift the `.window` field was accessed inline at
3953    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3954    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3955    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3956    /// error-payload construction on refusal, and the two
3957    /// [`rate_limit_codec::render`] arms
3958    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3959    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3960    /// open-coded field-accesses that expressed no compile-time link
3961    /// back to the typed sub-struct axis. A future extension of the
3962    /// `:window` axis to a richer author surface — a per-`:contratos`-
3963    /// edge window override the operator pins through a future
3964    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3965    /// acknowledges, a per-cluster window-default overlay the M4 CR
3966    /// materializer resolves per-CR, a promotion of the plain
3967    /// `Duration` refill period to a richer
3968    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3969    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3970    /// axis comes into scope, an addition of a `"d"` day suffix once
3971    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3972    /// have had to be threaded through every open-coded copy in
3973    /// lockstep or the validate gate, the codec's render path, and
3974    /// the future M4 emit path would silently disagree on which
3975    /// refill period a given [`RateLimit`] resolves to (an author's
3976    /// `:rate-limit "100/s"` would satisfy validate while the render
3977    /// / emit paths silently read a drifted other value, or vice
3978    /// versa: a validated typed slot would land at the emit boundary
3979    /// as a limiter whose refill period is structurally so long that
3980    /// no realistic per-edge traffic shape stays inside the token
3981    /// budget). Lifting the resolution to a typed method on the
3982    /// substrate primitive means every downstream consumer of the
3983    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3984    /// reaches for exactly one typed dispatch — the resolver's
3985    /// accept-set migrates as a unit on any future axis addition.
3986    ///
3987    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3988    /// sibling in shape to the just-landed [`RateLimit::rate`]
3989    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3990    /// required-axis, extended onto the per-sub-struct
3991    /// required-`Duration` axis; closes the last unlifted
3992    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3993    /// per-sub-struct accessor coverage is now complete across both
3994    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3995    /// the substrate primitive, thin projections at each consumer"
3996    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3997    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3998    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3999    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
4000    /// [`Membro::nome`] (4a32abf),
4001    /// [`Membro::versao_requirement`] (a40b0e3),
4002    /// [`Entrada::destination`] (6db982c) accessors carry on their
4003    /// respective per-mesh-slot-atom scalar-value axes. Named
4004    /// `window()` to match the storage field's name; the accessor's
4005    /// identity maps onto the canonical MESH-COMPOSITION §III.2
4006    /// vocabulary the slot's docstring already carries.
4007    #[must_use]
4008    pub const fn window(&self) -> Duration {
4009        self.window
4010    }
4011
4012    /// Recognize this rate-limit's `:window` as a canonical
4013    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
4014    /// exactly matches one of the three closed-set arm-Durations
4015    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
4016    /// non-canonical magnitude the codec's round-trip would break on
4017    /// (sub-second residue, or a second-magnitude outside the set
4018    /// [`RateLimitUnit::ALL`] enumerates).
4019    ///
4020    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
4021    /// returns `Some` here — the validate gate's
4022    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
4023    /// rejects every window this accessor returns `None` on. Downstream
4024    /// consumers past validate (the codec's [`rate_limit_codec::render`]
4025    /// path, the future M4 per-Aplicacao Envoy config reconciler's
4026    /// materialization pass, the future per-`:contratos`-edge rate-limit-
4027    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4028    /// acknowledges) that read the typed unit off a validated slot can
4029    /// pattern-match on the returned `Some` without re-checking
4030    /// canonicality at the consumer layer — the typed enum surface is
4031    /// the load-bearing carrier of the canonicality invariant.
4032    ///
4033    /// Preferred over the free [`is_canonical_rate_limit_window`]
4034    /// module-private helper at any call site that has the typed
4035    /// [`RateLimit`] in hand (the codec's `render` arm at
4036    /// [`rate_limit_codec::render`], the validate gate's canonical-form
4037    /// arm in [`AplicacaoSpec::validate_politicas`], any future
4038    /// per-`:contratos` edge-override overlay resolver): those consumers
4039    /// reach for the typed enum without going through the
4040    /// `.window()` scalar-projection layer, and get the enum value
4041    /// directly (which the codec's render arm can then format via
4042    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
4043    /// "typed sub-struct scalar accessor, one dispatch on the substrate
4044    /// primitive" discipline the sibling [`RateLimit::rate`] and
4045    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
4046    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
4047    /// projection axis (the third scalar accessor on the [`RateLimit`]
4048    /// axis, first typed-enum-return projection).
4049    ///
4050    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
4051    /// the canonical [`RateLimitUnit`] arm now carries the same
4052    /// `const`-eval-surface posture the sibling `pub const fn`
4053    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
4054    /// this typed sub-struct already carry, composing through the
4055    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
4056    /// reverse-resolver in `const` context. Any downstream substrate-
4057    /// side `const`-context consumer of the typed unit (a module-scope
4058    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
4059    /// invariant pin on a typed fixture, a future M4 admission-webhook
4060    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
4061    /// resolver over a typed [`RateLimit`], any future `const fn`
4062    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4063    /// the substrate primitive) now reaches the same typed dispatch on
4064    /// the substrate primitive at const-eval time as at runtime.
4065    ///
4066    /// Pinned load-bearing at the substrate-primitive level by
4067    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
4068    /// eval-surface pin via `const fn` wrapper).
4069    #[must_use]
4070    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
4071        RateLimitUnit::from_window(self.window)
4072    }
4073}
4074
4075/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
4076/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
4077/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
4078///
4079/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
4080/// the `:politicas :rate-limit` unit surface reads from
4081/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
4082/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
4083/// [`is_canonical_rate_limit_window`] predicate the
4084/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
4085/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
4086/// projection) now lives inside this typed enum's `match self` arms — a
4087/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
4088/// `rate_limit_action` grows daily-bucket support) is one new variant
4089/// plus the exhaustiveness arms on the four methods, so every consumer
4090/// picks it up by compile-time construction rather than a runtime
4091/// table-scan miss.
4092///
4093/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
4094/// scanned via `find_map` at every projection call — an untyped runtime
4095/// walk that carried no compile-time link between the parse arm's
4096/// accepted suffixes, the render arm's emitted suffixes, and the
4097/// validate gate's accepted windows. A future rate-limit-unit addition
4098/// that landed one row without threading through the other consumers
4099/// (or a copy-paste flip that collapsed two rows onto one suffix) would
4100/// silently split the accepted-set across the three consumers — the
4101/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
4102/// for a 24h window that parse can't round-trip, the validate gate
4103/// misses one canonical window. Lifting the pairs onto a typed
4104/// closed-set enum with exhaustive `match` arms makes any such
4105/// half-landed extension a caixa-core build error (the compiler enforces
4106/// arm coverage on every method), not a silent per-consumer drift
4107/// surfacing at apply time. Same "closed-set typed-enum discriminator"
4108/// discipline the sibling [`PlacementStrategy`] (cc8f749),
4109/// [`crate::supervisor::RestartStrategy`],
4110/// [`crate::supervisor::RestartPolicy`],
4111/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
4112/// closed-set typed enums carry on their respective closed-set axes —
4113/// extended onto the seventh closed-set typed-enum discriminator axis
4114/// on the caixa typed surface (the `:politicas :rate-limit :window`
4115/// canonical-unit axis).
4116#[derive(
4117    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4118)]
4119pub enum RateLimitUnit {
4120    /// 1-second window — canonical author-surface suffix `"s"`
4121    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4122    /// with a 1s magnitude.
4123    Second,
4124    /// 1-minute window — canonical author-surface suffix `"m"`
4125    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4126    /// with a 60s magnitude.
4127    Minute,
4128    /// 1-hour window — canonical author-surface suffix `"h"`
4129    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4130    /// with a 3600s magnitude.
4131    Hour,
4132}
4133
4134impl RateLimitUnit {
4135    /// Exhaustive iteration surface for every consumer that reads the
4136    /// full canonical-unit set (the byte-parity witness against the
4137    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
4138    /// webhook's accepted-suffix listing in its rejection body, any
4139    /// future round-trip fuzz harness). A future variant addition to
4140    /// [`RateLimitUnit`] extends this slice as a single edit and every
4141    /// consumer picks up the new entry by construction — the compiler-
4142    /// checked exhaustiveness on the sibling method `match` arms is the
4143    /// build-time guarantee that no arm forgets to grow.
4144    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
4145
4146    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
4147    /// string every `<n>/<unit>` rate-limit shape carries after its
4148    /// `/` separator. The single source of truth the codec's parse and
4149    /// render arms both dispatch on: the parse arm matches an incoming
4150    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
4151    /// output; the render arm emits the entry's `as_suffix` verbatim
4152    /// after the rate magnitude.
4153    #[must_use]
4154    pub const fn as_suffix(self) -> &'static str {
4155        match self {
4156            Self::Second => "s",
4157            Self::Minute => "m",
4158            Self::Hour => "h",
4159        }
4160    }
4161
4162    /// Canonical `Duration` for this unit — the token-bucket refill
4163    /// period the [`RateLimit::window`] axis carries when the surrounding
4164    /// slot's `:rate-limit` author surface named this unit.
4165    #[must_use]
4166    pub const fn window(self) -> Duration {
4167        Duration::from_secs(match self {
4168            Self::Second => 1,
4169            Self::Minute => 60,
4170            Self::Hour => 3_600,
4171        })
4172    }
4173
4174    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
4175    /// `None` when `suffix` is outside the closed-set arm-string set
4176    /// [`Self::as_suffix`] emits. The single `str → Self` projection
4177    /// [`rate_limit_codec::parse`] consumes.
4178    #[must_use]
4179    pub fn from_suffix(suffix: &str) -> Option<Self> {
4180        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
4181    }
4182
4183    /// Recognize a canonical rate-limit `Duration` as one of the three
4184    /// arms, or `None` when `window` carries sub-second residue or a
4185    /// second-magnitude outside the closed-set arm-window set
4186    /// [`Self::window`] emits. The single `Duration → Self` projection
4187    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
4188    /// both consume.
4189    ///
4190    /// `pub const fn` — the reverse `Duration → Self` projection now
4191    /// carries the same `const`-eval-surface posture the sibling
4192    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
4193    /// projection accessors on this closed-set typed enum already
4194    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
4195    /// typed-`RateLimit`-projection sibling composes through in `const`
4196    /// context. Routes byte-for-byte through the peer `pub const fn`
4197    /// [`Self::window`] canonical-`Duration` projection so any future
4198    /// arm-magnitude edit on the sibling accessor reaches this reverse
4199    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
4200    /// per-arm probes each dispatch through one `pub const fn` on the
4201    /// substrate primitive rather than a hand-authored per-arm second-
4202    /// magnitude literal that would silently drift on any future
4203    /// [`Self::window`] arm-magnitude edit.
4204    ///
4205    /// Prior to the `const` lift the body dispatched through
4206    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
4207    /// iterator-driven linear scan whose iterator methods
4208    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
4209    /// `PartialEq` dispatch each carry non-`const` bounds on stable
4210    /// Rust 1.94, so any downstream substrate-side `const`-context
4211    /// consumer of the reverse resolver (a module-scope
4212    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
4213    /// invariant pin on a typed fixture, a future M4
4214    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
4215    /// webhook `const fn` per-`:politicas` canonical-window floor over a
4216    /// typed [`RateLimit`] scalar, any future `const fn`
4217    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4218    /// the substrate primitive that wants to fan on the canonical unit
4219    /// at compile time) surfaced as a downstream E0015 far from the
4220    /// resolver's own declaration. The `pub const fn` posture closes
4221    /// the drift structurally at caixa-core build time.
4222    ///
4223    /// Pinned load-bearing at the substrate-primitive level by
4224    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
4225    /// eval-surface pin via `const fn` wrapper) and
4226    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
4227    /// (composition-witness pin against the peer `Self::window` scalar
4228    /// dispatch).
4229    #[must_use]
4230    pub const fn from_window(window: Duration) -> Option<Self> {
4231        if window.subsec_nanos() != 0 {
4232            return None;
4233        }
4234        // Route through the peer `pub const fn` [`Self::window`]
4235        // canonical-`Duration` projection so any future arm-magnitude
4236        // edit on the sibling accessor reaches this reverse resolver by
4237        // construction — the per-arm `secs` comparison keys off
4238        // `Duration::as_secs` (`pub const fn`), not a hand-authored
4239        // per-arm second-magnitude literal that would silently drift.
4240        let secs = window.as_secs();
4241        if secs == Self::Second.window().as_secs() {
4242            Some(Self::Second)
4243        } else if secs == Self::Minute.window().as_secs() {
4244            Some(Self::Minute)
4245        } else if secs == Self::Hour.window().as_secs() {
4246            Some(Self::Hour)
4247        } else {
4248            None
4249        }
4250    }
4251
4252    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
4253    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
4254    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
4255    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
4256    /// consumes.
4257    ///
4258    /// The peer `Duration → &'static str` axis folded onto the substrate
4259    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
4260    /// production consumers ([`rate_limit_codec::render`] and
4261    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
4262    /// migrated (61421a6): the free helper's `Duration → &str` projection
4263    /// is now the two-step composition
4264    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
4265    /// reads through the typed accessor. This lift closes the peer
4266    /// `&str → Duration` axis by folding the vestigial module-private
4267    /// `rate_limit_window_from_unit` delegate onto this associated method
4268    /// — the codec's parse arm and every future wire-side consumer of the
4269    /// `&str → Duration` projection (a future admission-webhook that
4270    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
4271    /// before it's promoted to a validated typed slot, a future
4272    /// `feira lint` shape-probe that reads the author-surface bytes
4273    /// verbatim) now reach for exactly one typed dispatch on the
4274    /// substrate primitive.
4275    ///
4276    /// Same "closed-set typed-enum discriminator with canonical
4277    /// projections per axis" discipline the sibling [`Self::as_suffix`]
4278    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
4279    /// methods carry — this associated method closes the fifth (and last
4280    /// unlifted) projection axis on the arm-table, so the closed-set enum
4281    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
4282    /// consumer of the `:politicas :rate-limit :window` axis reaches
4283    /// through. A future rate-limit-unit addition (a `"d"` day suffix
4284    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
4285    /// `"ms"` sub-second window once high-throughput per-edge policies
4286    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
4287    /// variant plus one arm per method — the compiler enforces
4288    /// exhaustiveness on every consumer's `match self` arms and picks
4289    /// the new unit up by construction across all five projections.
4290    #[must_use]
4291    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
4292        Self::from_suffix(suffix).map(Self::window)
4293    }
4294}
4295
4296/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
4297/// every consumer that formats a canonical rate-limit unit as user-
4298/// facing text (future M4 admission-webhook rejection bodies naming
4299/// the accepted-suffix set, future `feira app graph` per-`:politicas`
4300/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
4301/// codec's parse arm accepts and the render arm emits. Same
4302/// as_str-through-Display convergence discipline the sibling
4303/// [`PlacementStrategy`], [`crate::CaixaKind`],
4304/// [`crate::supervisor::RestartStrategy`], and
4305/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
4306impl std::fmt::Display for RateLimitUnit {
4307    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4308        f.write_str(self.as_suffix())
4309    }
4310}
4311
4312/// Upper-bound ceiling on the `:politicas :timeout` axis — every
4313/// validated [`MeshPolicy::timeout`] past
4314/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
4315/// (inclusive on both ends, integer-millisecond magnitudes by the
4316/// canonical-form gate immediately preceding).
4317///
4318/// The typed field is `Option<Duration>` (the zero-floor arm
4319/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
4320/// `Duration::ZERO`, and the canonical-form arm
4321/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
4322/// sub-millisecond residue), so a programmatic struct literal
4323/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
4324/// 24h) and the equivalent author-surface form
4325/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
4326/// integer-hour magnitude) both round-trip cleanly through serde — a
4327/// structurally unbounded `Duration` ceiling. A `:timeout` value far
4328/// above the documented production-playbook band (Envoy default `15s`,
4329/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
4330/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
4331/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
4332/// at `~3600s`) silently degenerates the mesh-policy contract: the
4333/// per-call deadline is structurally so long that no realistic
4334/// synchronous-`:contratos` traversal can reach it, so the typed slot
4335/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
4336/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
4337/// blocking" degenerates to a nominal-only contract on the
4338/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
4339/// the sibling `:politicas :retries` axis and the
4340/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
4341/// `:politicas :circuit-breaker :max-failures` axis — all three close
4342/// the "structurally unbounded ceiling on a typed `:politicas` axis"
4343/// footgun the prior zero-floor-and-canonical-form-only checks left
4344/// open.
4345///
4346/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4347/// shared duration codec emits (`"<n>h"` for any integer-hour
4348/// magnitude) — every value in the canonical authoring form's
4349/// `<integer><unit>` grammar at or below this cap renders to a clean
4350/// canonical string. The cap sits an order of magnitude above every
4351/// documented production-playbook recommendation band (Envoy default
4352/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
4353/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
4354/// configured maximum (`proxy_read_timeout` typical max `3600s`),
4355/// below the clearly-pathological "effectively no timeout" floor
4356/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
4357/// want for a long-running synchronous workflow, but a hard wall above
4358/// which the mesh-level deadline is structurally a non-deadline.
4359/// Lifted as a typed `pub const` so the bound has exactly one source
4360/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4361/// materializer's admission webhook and the caixa-mesh-side
4362/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4363/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4364/// other typed upper bound in this crate carries
4365/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4366/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4367/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4368/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4369pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
4370
4371/// Upper-bound ceiling on the `:politicas :retries` axis — every
4372/// validated [`MeshPolicy::retries`] past
4373/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
4374///
4375/// The typed slot is `Option<u32>` (`None` = no retries on transient
4376/// failure; `Some(0)` already rejected by the
4377/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
4378/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
4379/// .. }`) and the equivalent author-surface form
4380/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
4381/// serde / the codec — a structurally unbounded `u32` ceiling. The
4382/// runtime substrate that consumes the value (Envoy's
4383/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
4384/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
4385/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
4386/// admission cap is 10) translates a four-billion-retry policy into a
4387/// thundering-herd amplification vector on transient failure — the
4388/// caller's one request fans out to `retries` server-side calls per
4389/// edge per traversal, multiplying load by `(retries+1)^depth` across
4390/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
4391/// invariant "no infinite blocking" pairs with a no-runaway-amplification
4392/// invariant on the retry axis; both belong at the typed-slot layer.
4393///
4394/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
4395/// upstream mesh-policy schema that documents one) and sits above the
4396/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
4397/// every documented production playbook): a value the author can
4398/// plausibly want, but a hard wall above which the policy is
4399/// structurally a footgun. Lifted as a typed `pub const` so the bound
4400/// has exactly one source of truth — a future axis reaching for the
4401/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4402/// materializer's admission webhook, the caixa-mesh-side
4403/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
4404/// one place. Same shape every other typed upper bound in this crate
4405/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4406/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4407/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
4408/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4409pub const POLICY_RETRIES_MAX: u32 = 10;
4410
4411/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
4412/// axis — every validated [`CircuitBreaker::max_failures`] past
4413/// [`AplicacaoSpec::validate_politicas`] lies in
4414/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
4415///
4416/// The typed field is `u32` (the zero-floor arm
4417/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
4418/// `0` — a breaker that trips on the first call), so a programmatic
4419/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
4420/// and the equivalent author-surface form
4421/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
4422/// cleanly through serde — a structurally unbounded `u32` ceiling. A
4423/// `max_failures` value far above the documented production-playbook
4424/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
4425/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
4426/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
4427/// typical 5–50) silently disables the breaker's protection role:
4428/// the threshold is structurally so high that no realistic
4429/// failures-per-`:window` traffic shape can reach it, so the breaker
4430/// never trips and the typed slot becomes a no-op carried on every
4431/// emitted Envoy / Cilium L7 overlay. Pairs with the
4432/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
4433/// axis — both close the "structurally unbounded `u32` ceiling on a
4434/// typed policy axis" footgun the prior zero-floor-only checks left
4435/// open.
4436///
4437/// The `1000` ceiling sits an order of magnitude above every
4438/// documented upstream production-playbook recommendation band (the
4439/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
4440/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
4441/// the clearly-pathological "effectively no protection"
4442/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
4443/// plausibly want at hyperscale, but a hard wall above which the
4444/// policy is structurally a no-op. Lifted as a typed `pub const` so
4445/// the bound has exactly one source of truth — the future M4
4446/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4447/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4448/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4449/// one place. Same shape every other typed upper bound in this crate
4450/// carries ([`POLICY_RETRIES_MAX`],
4451/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4452/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4453/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4454pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
4455
4456/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
4457/// every validated [`CircuitBreaker::window`] past
4458/// [`AplicacaoSpec::validate_politicas`] lies in
4459/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
4460/// integer-millisecond magnitudes by the canonical-form gate
4461/// immediately preceding).
4462///
4463/// The typed field is `Duration` (the zero-floor arm
4464/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
4465/// `Duration::ZERO`, and the canonical-form arm
4466/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
4467/// sub-millisecond residue), so a programmatic struct literal
4468/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
4469/// and the equivalent author-surface form
4470/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
4471/// integer-hour magnitude) both round-trip cleanly through serde — a
4472/// structurally unbounded `Duration` ceiling. A `:window` value far
4473/// above the documented production-playbook band (Hystrix
4474/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
4475/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
4476/// Istio `outlierDetection.interval` default `10s`, Envoy
4477/// `outlier_detection.interval` default `10s`, AWS App Mesh
4478/// circuit-breaker time-window typical `30s..=300s`) degenerates the
4479/// breaker's role: a rolling-window failure counter whose window is
4480/// hours long is operationally a lifetime counter, the breaker's
4481/// "recent failures" memory is structurally so long that transient
4482/// failures are never forgotten, and the typed slot becomes a no-op
4483/// trigger that trips once and stays tripped for the lifetime of the
4484/// component carried on every emitted Envoy / Cilium L7 overlay.
4485///
4486/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4487/// shared duration codec emits (`"<n>h"` for any integer-hour
4488/// magnitude) — every value in the canonical authoring form's
4489/// `<integer><unit>` grammar at or below this cap renders to a clean
4490/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
4491/// cap on the first typed-`Duration` `:politicas` axis: the two
4492/// duration-typed `:politicas` axes now share a single uniform top
4493/// edge so the next typed-slot wiring (the future caixa-mesh
4494/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
4495/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
4496/// admission webhook) reaches for either field knowing the value is
4497/// in `1ms..=1h` without re-validating at the renderer layer. The cap
4498/// sits two orders of magnitude above every documented upstream
4499/// production-playbook recommendation band (Hystrix / resilience4j /
4500/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
4501/// and below the clearly-pathological "rolling window degenerates to
4502/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
4503/// author can plausibly want for a very-low-traffic long-tail
4504/// failure-detection window, but a hard wall above which the breaker's
4505/// rolling-window contract is structurally a lifetime-counter contract.
4506/// Lifted as a typed `pub const` so the bound has exactly one source
4507/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4508/// materializer's admission webhook and the caixa-mesh-side
4509/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4510/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4511/// other typed upper bound in this crate carries
4512/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4513/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4514/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4515/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4516/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4517pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
4518
4519/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
4520/// every validated [`RateLimit::rate`] past
4521/// [`AplicacaoSpec::validate_politicas`] lies in
4522/// `1..=POLICY_RATE_LIMIT_MAX`.
4523///
4524/// The typed field is `u32` (the zero-floor arm
4525/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
4526/// zero-rate limit denies every request, the canonical "I forgot
4527/// that 0 means deny-everything" footgun), so a programmatic struct
4528/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
4529/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
4530/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
4531/// round-trip cleanly through serde — a structurally unbounded `u32`
4532/// ceiling. The runtime substrate consuming the value (Envoy's
4533/// `local_rate_limit.token_bucket.max_tokens`, the future
4534/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4535/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
4536/// rate-limit into a no-op rate-limiter: the bucket capacity is
4537/// structurally so high no realistic per-edge traffic shape can
4538/// drain it, the limiter never trips, and the typed slot becomes a
4539/// "rate-limit declared, no enforcement" footgun — the canonical
4540/// declared-but-inert shape every other `:politicas` cap arm
4541/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
4542/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
4543///
4544/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
4545/// above every documented upstream production-playbook recommendation
4546/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
4547/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
4548/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
4549/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
4550/// `limit_req_zone` typical `1..=1_000` RPS) and below the
4551/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
4552/// `u32::MAX`): a value the author can plausibly want at hyperscale
4553/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
4554/// /h-window arm), but a hard wall above which the policy is
4555/// structurally a no-op carried verbatim on every emitted Envoy /
4556/// Cilium L7 overlay. The cap brackets all three canonical windows
4557/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
4558/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
4559/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
4560/// per-endpoint API band). Lifted as a typed `pub const` so the bound
4561/// has exactly one source of truth — the future M4
4562/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4563/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4564/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4565/// one place. Same shape every other typed upper bound in this crate
4566/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4567/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
4568/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4569/// [`crate::LIMITS_WALL_CLOCK_MAX`],
4570/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4571/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4572pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
4573
4574// `:entrada :host` total-length and per-label cap axes route through
4575// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
4576// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
4577// pair of aplicacao-private aliases the previous `validate_entrada_host`
4578// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
4579// = 63`) were structurally the same K8s Gateway API v1 Hostname
4580// admission-schema bounds — the total-length cap on the OpenAPI
4581// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
4582// same regex — that the peer axes at the caixa-core::render level pin,
4583// so hoisting both readers onto the shared lifted constants closes the
4584// third-occurrence duplication threshold structurally: the M4
4585// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
4586// label validator, the future per-`Certificate` SAN emitter, and every
4587// other per-Gateway-API-Hostname landing site reach the same one place
4588// as the `:entrada :host` gate does — no per-axis alias drift surface
4589// between them, by construction.
4590
4591/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
4592/// extractor expression — the upper bound `validate_placement_shard_key`
4593/// enforces on every well-shaped shard-key past validate. The realistic
4594/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
4595/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
4596/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
4597/// `:placement :affinity` / `:placement :clusters` identifier-shaped
4598/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
4599/// in `:shard-key`" footgun at validate time rather than at the future
4600/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
4601const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
4602
4603/// Reject `:membros :caixa` values the K8s apiserver would refuse at
4604/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4605/// that maps the shared parser-shaped reason into the
4606/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
4607/// is self-locating (the offending `caixa:` is named verbatim) and
4608/// the author can grep their caixa.lisp for `:caixa "<name>"` and
4609/// fix it in one edit. Same diagnostic shape as
4610/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
4611/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
4612fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
4613    // Empty is already gated by `MembroCaixaEmpty` at the call site;
4614    // re-checking here keeps the predicate usable from any future
4615    // call site (the M4 CR materializer) without an empty-check
4616    // footgun. The shared
4617    // [`crate::render::require_valid_dns_1123_label`] helper brackets
4618    // the empty-first + shape cascade every peer name axis
4619    // (`:placement :clusters`, `:placement :affinity`, `:contratos
4620    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
4621    // `:upgrade-from :module`) routes through, so drift between the
4622    // eight axes' accepted DNS-1123-label sets is structurally
4623    // impossible.
4624    crate::render::require_valid_dns_1123_label(
4625        caixa,
4626        || AplicacaoError::MembroCaixaEmpty,
4627        |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
4628    )
4629}
4630
4631/// Reject `:placement :clusters` entries the K8s apiserver would refuse
4632/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4633/// that maps the shared parser-shaped reason into the
4634/// [`AplicacaoError::PlacementClusterInvalid`] variant.
4635///
4636/// Cluster names land in DNS-1123-label territory across every consumer:
4637/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
4638/// the `lareira-fleet-programs` aggregator applies to scope programs to
4639/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
4640/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
4641/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
4642/// cluster identity the M4 CR materializer round-trips. Each apiserver-
4643/// side schema enforces the DNS-1123 label rule on admission; a
4644/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
4645/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
4646/// mistaken-identity slug) silently passes the prior empty-/duplicate-
4647/// only gate and the failure surfaces as a no-match at filter time —
4648/// the workload doesn't land in the named cluster, with no diagnostic
4649/// naming the offending `:clusters` entry. Lifting the gate to caixa-
4650/// build time mirrors the `:membros :caixa` value-shape trajectory
4651/// (3f9d7a0) on the peer name axis.
4652///
4653/// The diagnostic carries the offending `cluster:` verbatim plus a
4654/// parser-shaped `reason:` naming the specific violation, so the
4655/// author can grep their caixa.lisp for `:clusters` and fix it in
4656/// one edit. Same diagnostic shape as
4657/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
4658fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
4659    // Empty is already gated by `PlacementClusterEmpty` at the call
4660    // site; re-checking here keeps the predicate usable from any
4661    // future call site (the M4 CR materializer's per-cluster validator)
4662    // without an empty-check footgun. Routes through the shared
4663    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4664    // name axes each land on.
4665    crate::render::require_valid_dns_1123_label(
4666        cluster,
4667        || AplicacaoError::PlacementClusterEmpty,
4668        |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
4669    )
4670}
4671
4672/// Reject `:placement :affinity` hints whose shape can never legitimately
4673/// land in any downstream selector or label-keyed routing axis. Thin
4674/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4675/// shared parser-shaped reason into the
4676/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
4677/// diagnostic is self-locating (the offending `:affinity` is named
4678/// verbatim) and the author can grep their caixa.lisp for
4679/// `:affinity "<hint>"` and fix it in one edit.
4680///
4681/// The `:affinity` slot carries a placement-engine hint — canonical
4682/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4683/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4684/// compression overlay and the future M4 placement-engine's per-hint
4685/// routing axis. Each downstream consumer (caixa-mesh's
4686/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4687/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4688/// `spec.placement.affinity` admission rule, the future M4 per-hint
4689/// node-affinity / pod-affinity rule generator keying off the same
4690/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4691/// selector) requires the value to be a DNS-1123 label — K8s label
4692/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4693/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4694/// admission rule the apiserver enforces.
4695///
4696/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4697/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4698/// Python-module-name leak), `:affinity "data.locality"` (the
4699/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4700/// `:affinity "data-locality-"` (boundary-hyphen violation),
4701/// `:affinity "data locality"` (paste-from-doc whitespace),
4702/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4703/// 64-byte over-cap slug silently passed the empty-only check and the
4704/// failure surfaced as a no-match at the M3 Adaptive compression
4705/// overlay's filter time (`placement.affinity` carried a malformed
4706/// value, no node matched, the workload landed on the default
4707/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4708/// the empty-:affinity / empty-shard-key / zero-:politicas /
4709/// empty-:contratos-target gates already close on every other
4710/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4711/// gate closes the fifth typed slot on the Aplicacao surface to land
4712/// on the canonical DNS-1123 label floor (after the four Servico-name
4713/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4714/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4715/// b0e8748).
4716///
4717/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4718/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4719/// validated values are guaranteed-accepted by the apiserver without
4720/// re-validation at any downstream renderer or admission layer.
4721fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4722    // Empty is gated separately at the call site for a self-locating
4723    // diagnostic; re-checking here keeps the predicate usable from any
4724    // future call site (the M4 CR materializer's per-affinity
4725    // validator) without an empty-check footgun. Routes through the
4726    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4727    // peer name axes each land on.
4728    crate::render::require_valid_dns_1123_label(
4729        affinity,
4730        || AplicacaoError::PlacementAffinityEmpty,
4731        |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
4732    )
4733}
4734
4735/// Reject `:placement :shard-key` extractor expressions whose shape can
4736/// never legitimately drive the future M4 Akka-style cluster-sharding
4737/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4738/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4739/// diagnostic is self-locating (the offending `:shard-key` value is
4740/// named verbatim alongside the parser-shaped reason) and the author can
4741/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4742/// edit.
4743///
4744/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4745/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4746/// expression naming the message property to hash on. The realistic
4747/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4748/// property name; `$tenantId` — Akka entity-id placeholder;
4749/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4750/// `${tenant}` — interpolation-style template) all sit in the printable
4751/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4752/// multi-line blob landing in `:shard-key`, an embedded space from a
4753/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4754/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4755/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4756/// check and the failure surfaces at the future M4 reconciler's hash
4757/// pass as a runtime extractor-evaluation error far from the source
4758/// `caixa.lisp`, with no field naming which member's `:shard-key`
4759/// carried the offending value.
4760///
4761/// The contract — the printable ASCII single-token intersection-floor
4762/// every Akka-style entity-id extractor implementation admits:
4763///
4764///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4765///     peer DNS-1123-label-shaped `:placement :affinity` /
4766///     `:placement :clusters` identifier axes; realistic shard-keys sit
4767///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4768///     blob footguns at validate time;
4769///   - every byte in the printable ASCII range `0x21..=0x7E` —
4770///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4771///     `"$tenantId\n"` from paste-from-aligned-doc /
4772///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4773///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4774///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4775///     un-Punycode-encoded IDN that round-trips inconsistently across
4776///     NFC/NFD normalization).
4777///
4778/// The accepted set is broader than the DNS-1123 label floor the peer
4779/// `:placement :clusters` / `:placement :affinity` axes use because the
4780/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4781/// landing site; it's an extractor expression the future Akka-style
4782/// reconciler reads as a property reference. The realistic forms
4783/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4784/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4785/// but every Akka-style entity-id extractor parses. The
4786/// printable-ASCII-token floor accepts every shape any such extractor
4787/// would accept while rejecting the cross-implementation footguns
4788/// (whitespace breaks token boundaries; non-ASCII round-trips
4789/// inconsistently across YAML emitters and NFC/NFD normalization;
4790/// control characters silently corrupt the next read).
4791///
4792/// Until this gate landed `validate_placement` only refused the
4793/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4794/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4795/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4796/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4797/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4798/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4799/// control character from paste-from-binary, the 64-byte over-cap
4800/// paste-from-doc multi-line slug) silently passed validate. The future
4801/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4802/// would then surface the malformed value either as a runtime
4803/// extractor-evaluation error (whitespace breaks the extractor's token
4804/// boundary, no match) or as a silently-different shard assignment
4805/// across YAML emitters (non-ASCII normalizes differently between the
4806/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4807/// parser, the same entity ID maps to two distinct shards on a
4808/// re-render). Lifting the shape gate to caixa-build time makes the
4809/// extractor-floor invariant a structural property of every validated
4810/// `Placement`: every `Sharded` placement past `validate_placement` has
4811/// a `:shard-key` the future M4 reconciler can hash without
4812/// re-validating at the runtime layer.
4813///
4814/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4815/// [`AplicacaoError::ContratoSubjectInvalid`] /
4816/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4817/// on the peer `:contratos` payload axes — each lifts the
4818/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4819/// closing the canonical "this passed validate but the runtime parser
4820/// rejected it" surprise.
4821fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4822    // Empty is gated separately at the call site via the more
4823    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4824    // re-checking here keeps the predicate usable from any future call
4825    // site (the M4 CR materializer's per-shard-key validator) without
4826    // an empty-check footgun.
4827    if key.is_empty() {
4828        return Err(AplicacaoError::ShardedKeyEmpty);
4829    }
4830    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4831        return Err(AplicacaoError::shard_key_invalid(
4832            key,
4833            format!(
4834                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4835                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4836                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4837                 well under 32 bytes, this length suggests a paste-from-doc \
4838                 multi-line blob landed in `:shard-key` instead of a single-token \
4839                 extractor expression)",
4840                key.len()
4841            ),
4842        ));
4843    }
4844    for &b in key.as_bytes() {
4845        if (0x21..=0x7E).contains(&b) {
4846            continue;
4847        }
4848        let reason = if b == b' ' {
4849            "contains a space (Akka-style entity-id extractor expressions are \
4850             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4851             whitespace breaks the extractor's token boundary at the runtime layer, \
4852             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4853             a multi-token blob in one `:shard-key` slot)"
4854                .to_string()
4855        } else if b == b'\t' {
4856            "contains a tab character (paste-from-aligned-doc footgun; the \
4857             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4858             reference, embedded whitespace breaks the token boundary at the \
4859             runtime hash-extractor pass)"
4860                .to_string()
4861        } else if b == b'\n' || b == b'\r' {
4862            format!(
4863                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4864                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4865                 extractor reads `:shard-key` as a single-token reference, embedded \
4866                 newlines either truncate the value at the YAML emitter layer or \
4867                 break the token boundary at the runtime hash-extractor pass)"
4868            )
4869        } else if b < 0x20 || b == 0x7F {
4870            format!(
4871                "contains control character 0x{b:02x} (the canonical \
4872                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4873                 control characters silently corrupt round-trip serialization \
4874                 across YAML emitters and break the runtime hash-extractor's \
4875                 single-token parser)"
4876            )
4877        } else {
4878            format!(
4879                "contains non-ASCII byte 0x{b:02x} (the canonical \
4880                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4881                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4882                 across YAML emitter implementations — the same entity ID can \
4883                 silently map to two distinct shards on a re-render. Use a \
4884                 printable-ASCII extractor expression like `tenantId`, \
4885                 `$tenantId`, or `metadata.tenantId`)"
4886            )
4887        };
4888        return Err(AplicacaoError::shard_key_invalid(key, reason));
4889    }
4890    Ok(())
4891}
4892
4893/// Reject `:contratos :de` / `:contratos :para` values whose shape
4894/// can never legitimately match a validated `:membros :caixa`. Thin
4895/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4896/// shared parser-shaped reason into the
4897/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4898/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4899/// the offending value verbatim) and the author can grep their
4900/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4901/// one edit.
4902///
4903/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4904/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4905/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4906/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4907/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4908/// un-Punycode-encoded IDN) silently passed the per-axis check and
4909/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4910/// membership lookup — diagnostic-framed as "this caixa is not in
4911/// `:membros`" when the root cause is "this `:de` value is not a
4912/// well-shaped Servico-name identifier and could never legitimately
4913/// match any validated member". Because every `:membros :caixa` is
4914/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4915/// `names` HashSet structurally never contains an empty / malformed
4916/// string, so the membership lookup arm misframes every empty /
4917/// malformed input. Lifting the shape arm ahead of the lookup
4918/// preserves the legitimate `ContratoMemberMissing` arm (a
4919/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4920/// reference) while routing every structurally-impossible-to-match
4921/// input through the narrower self-locating shape diagnostic.
4922///
4923/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4924/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4925/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4926/// to land on the canonical [`crate::render::is_dns_1123_label`]
4927/// floor. The `slot: &'static str` field carries the kebab-case
4928/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4929/// per-callback-slot diagnostic shape and the
4930/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4931/// (85f102c) cross-list-tag pattern.
4932fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4933    // Routes through the shared
4934    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4935    // name axes each land on. The `slot: &'static str` field flows
4936    // through both error variants so the diagnostic names which
4937    // per-edge axis (`:de` vs `:para`) the offending value came from.
4938    crate::render::require_valid_dns_1123_label(
4939        caixa,
4940        || AplicacaoError::ContratoCaixaEmpty { slot },
4941        |reason| AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
4942    )
4943}
4944
4945/// Reject `:entrada :para` values whose shape can never legitimately
4946/// match a validated `:membros :caixa`. Thin wrapper around
4947/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4948/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4949/// variant, so the diagnostic is self-locating (the offending
4950/// `:entrada :para` value is named verbatim) and the author can grep
4951/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4952///
4953/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4954/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4955/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4956/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4957/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4958/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4959/// silently passed the per-axis check and surfaced as
4960/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4961/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4962/// root cause is "this `:entrada :para` value is not a well-shaped
4963/// Servico-name identifier and could never legitimately match any
4964/// validated member". Because every `:membros :caixa` is shape-
4965/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4966/// `HashSet` structurally never contains an empty / malformed string,
4967/// so the membership lookup arm misframes every empty / malformed
4968/// input. Lifting the shape arm ahead of the lookup preserves the
4969/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4970/// simply isn't in `:membros` — a phantom reference) while routing
4971/// every structurally-impossible-to-match input through the narrower
4972/// self-locating shape diagnostic.
4973///
4974/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4975/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4976/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4977/// fourth and last Aplicacao-level Servico-name reference axis to
4978/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4979/// No `slot: &'static str` field because there is only one axis
4980/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4981/// the simpler shape mirrors [`validate_membro_caixa`] and
4982/// [`validate_placement_cluster`].
4983fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4984    // Empty is gated separately at the call site for a self-locating
4985    // diagnostic; re-checking here keeps the predicate usable from any
4986    // future call site (the M4 CR materializer's per-`:entrada`
4987    // validator) without an empty-check footgun. Routes through the
4988    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4989    // peer name axes each land on.
4990    crate::render::require_valid_dns_1123_label(
4991        para,
4992        || AplicacaoError::EntradaParaEmpty,
4993        |reason| AplicacaoError::entrada_para_invalid(para, reason),
4994    )
4995}
4996
4997/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4998/// would refuse at admission time. The contract — exactly the regex
4999/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
5000/// and `HTTPRoute.spec.hostnames[]`,
5001/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
5002/// (max length 253; per-label max length 63):
5003///
5004///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
5005///     uppercase, no underscore, no Unicode/IDN — IDN must be
5006///     pre-encoded as Punycode `xn--…` by the author);
5007///   - exactly one optional leading wildcard label (`*.`); a wildcard
5008///     in any non-leading label position is rejected;
5009///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
5010///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
5011///   - total length 1..=253 bytes;
5012///   - no IPv4 literal (Gateway API forbids IP literals);
5013///   - no scheme (`https://`, `http://`), no port (`:8080`), no
5014///     whitespace, no path (`/`).
5015///
5016/// Lifted as a typed gate (rather than an inline cascade in
5017/// `validate()`) so the contract lives in one place — every future
5018/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5019/// materializer's host validator, the future per-`:entrada` SAN
5020/// emission for cert-manager Certificates, the multi-`:entrada`
5021/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
5022/// for the same predicate, not its own. Same compounding shape as
5023/// `is_canonical_rate_limit_window` (808017c) and
5024/// [`WitTarget::label`] (previously the free `contrato_target_label`
5025/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
5026/// per-variant label match is compiler-checked-exhaustive).
5027///
5028/// The diagnostic carries the offending `host:` verbatim plus a
5029/// parser-shaped `reason:` naming the specific violation, so the
5030/// author can grep their caixa.lisp for `:host "<host>"` and fix it
5031/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
5032/// (9888b13).
5033fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
5034    // Empty is already gated by `EmptyEntradaHost` at the call site;
5035    // re-checking here keeps the predicate usable from any future
5036    // call site (M4 CR materializer) without an empty-check footgun.
5037    if host.is_empty() {
5038        return Err(AplicacaoError::EmptyEntradaHost);
5039    }
5040    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
5041        return Err(AplicacaoError::entrada_host_invalid(
5042            host,
5043            format!(
5044                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
5045                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
5046                host.len(),
5047                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
5048            ),
5049        ));
5050    }
5051    if host.contains("://") {
5052        return Err(AplicacaoError::entrada_host_invalid(
5053            host,
5054            "must not carry a scheme (drop the `https://` or `http://` prefix; \
5055             Gateway API takes the bare hostname)",
5056        ));
5057    }
5058    if host.contains('/') {
5059        return Err(AplicacaoError::entrada_host_invalid(
5060            host,
5061            "must not carry a path (drop the `/…` suffix; Gateway API path \
5062             matching is in `:entrada :paths`)",
5063        ));
5064    }
5065    // After the `://` scheme-prefix and `/` path arms have ruled out the
5066    // two `:`-bearing shapes the Gateway API actively rejects with
5067    // location-shaped diagnostics, any remaining `:` in the host body is
5068    // either the canonical "I put the port in the `:host` slot"
5069    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
5070    // slot lives one axis away on the same `:entrada` block) or an
5071    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
5072    // Hostname forbids identically to the IPv4-literal arm below. Both
5073    // shapes silently fell through the `://` and `/` arms before this
5074    // lift and surfaced as a deep `label "<rest>:<port>" contains
5075    // invalid character ':'` diagnostic from the per-byte loop near the
5076    // bottom of this predicate, which named the offending byte but not
5077    // the canonical authoring fix — for the port case the author has to
5078    // know the `:entrada` block carries a separate `:port u16` slot
5079    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
5080    // move the value over; for the IPv6 case the author has to know
5081    // Gateway API v1 forbids IP literals across the board. The contract
5082    // doc-comment above already promises "no port (`:8080`)" verbatim
5083    // in the rejected-shape enumeration but the predicate's
5084    // implementation refused the `:` only as a side-effect of the
5085    // per-label `[a-z0-9-]` character-class loop; this arm brings the
5086    // implementation in line with the documented contract by surfacing
5087    // the canonical fix at the top-level shape gate, peer with how the
5088    // `://` arm names the scheme prefix and the `/` arm names the
5089    // `:entrada :paths` axis. Same compounding trajectory the recent
5090    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
5091    // — the typed slot's rejected set matches the apiserver's rejected
5092    // set, structurally, with a self-locating diagnostic at the
5093    // offending axis instead of a deep parser-shape leak.
5094    if host.contains(':') {
5095        return Err(AplicacaoError::entrada_host_invalid(
5096            host,
5097            "must not contain `:` (the port belongs in the `:entrada :port` \
5098             slot — a separate `u16` axis on the same `:entrada` block, \
5099             defaulting to 8080 — not in the host body; drop the `:<port>` \
5100             suffix and author the bare hostname. If you intended an IPv6 \
5101             literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
5102             Hostname forbids IP literals identically to the IPv4-literal \
5103             arm — use a DNS name)",
5104        ));
5105    }
5106    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
5107    // predicate — the same single source of truth every peer
5108    // ASCII-whitespace scan in caixa-core flows through: the four
5109    // typed-magnitude codec sites (`limits::parse_byte_size` backing
5110    // `:limits :memory`, `limits::parse_duration` backing `:limits
5111    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
5112    // `aplicacao::rate_limit_codec::parse` backing `:politicas
5113    // :rate-limit`) and the shared duration codec
5114    // (`supervisor::duration_codec::parse`) backing `:supervisor
5115    // :restart-window` / `:politicas :timeout` / `:politicas
5116    // :circuit-breaker :window`. This landing closes the last string-typed
5117    // slot in caixa-core still calling `.bytes().any(|b|
5118    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
5119    // across every typed slot now shares one predicate, so a future
5120    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
5121    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
5122    // deliberately excluded from the peer non-ASCII predicate) can
5123    // extend at this shared site in one edit rather than seven
5124    // independent scans diverging over time. Naming the offending byte
5125    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
5126    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
5127    // the offending byte verbatim" discipline every peer codec site
5128    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
5129    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
5130    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
5131        return Err(AplicacaoError::entrada_host_invalid(
5132            host,
5133            format!(
5134                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
5135                 Hostname is a single-token DNS name — leading, trailing, \
5136                 or embedded whitespace breaks the K8s apiserver's Hostname \
5137                 regex at admission time; the paste-from-aligned-doc / \
5138                 paste-from-shell-history / paste-from-CSV footgun silently \
5139                 lands a multi-token blob in `:entrada :host`. Strip every \
5140                 whitespace byte and author the bare hostname — space \
5141                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
5142                 refuse identically)"
5143            ),
5144        ));
5145    }
5146    // Peer of the ASCII-whitespace scan above: route the non-ASCII
5147    // subset of Unicode `White_Space` through the shared
5148    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
5149    // single source of truth every peer non-ASCII-whitespace scan in
5150    // caixa-core flows through: `limits::parse_byte_size` (`:limits
5151    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
5152    // `limits::parse_millicores` (`:limits :cpu`),
5153    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
5154    // and `supervisor::duration_codec::parse` (`:supervisor
5155    // :restart-window` / `:politicas :timeout` / `:politicas
5156    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
5157    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
5158    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
5159    // paste-from-web-doc), or an EM-SPACE-split host
5160    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
5161    // survived this predicate's ASCII byte-scan (none of the UTF-8
5162    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
5163    // `u8::is_ascii_whitespace`), then landed on the per-label
5164    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
5165    // predicate with the generic `label "…" must start and end with an
5166    // alphanumeric` diagnostic — a "far from source at build-time"
5167    // leak that names the label-shape violation but not the
5168    // paste-from-typography origin the author actually needs to fix.
5169    // Peer with the four codec sites the 1b75b38 landing pinned: the
5170    // typed slot's diagnostic axis names the offending codepoint
5171    // (`U+XXXX`) verbatim rather than laundering the value through a
5172    // downstream label-shape arm, so the author can grep their
5173    // caixa.lisp for the invisible codepoint at the surfaced position
5174    // rather than eyeball a multi-byte host for embedded NBSP / LINE
5175    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
5176    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
5177    // drift between any two typed-slot sites' non-ASCII-whitespace
5178    // rejection set becomes a single-edit fix at the shared predicate
5179    // rather than N independent inline scans diverging over time, and
5180    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
5181    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
5182    // `char::is_whitespace`" class the peer non-ASCII predicate's
5183    // doc-comment names as the follow-up trajectory) extends at the
5184    // shared predicate in one edit rather than seven.
5185    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
5186        return Err(AplicacaoError::entrada_host_invalid(
5187            host,
5188            format!(
5189                "contains non-ASCII Unicode whitespace character {ch:?} \
5190                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
5191                 single-token DNS name limited to `[a-z0-9-]` labels; \
5192                 the paste-from-typography footgun silently lands an \
5193                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
5194                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
5195                 `U+3000`, and every other member of the Unicode \
5196                 `White_Space` property outside the ASCII byte range) \
5197                 in `:entrada :host`, which the K8s apiserver's \
5198                 Hostname regex refuses at admission time far from the \
5199                 caixa.lisp source line. Strip every non-ASCII \
5200                 whitespace character and author the bare hostname \
5201                 with only ASCII bytes (write \"checkout.quero.cloud\" \
5202                 verbatim)",
5203                codepoint = ch as u32,
5204            ),
5205        ));
5206    }
5207
5208    // Strip the optional single leading wildcard label *before* the
5209    // trailing-dot check so the bare `"*."` form surfaces the more
5210    // self-locating "wildcard without domain" diagnostic instead of
5211    // the generic "trailing dot" one.
5212    let (had_wildcard, rest) = match host.strip_prefix("*.") {
5213        Some(r) => (true, r),
5214        None => (false, host),
5215    };
5216    if had_wildcard && rest.is_empty() {
5217        return Err(AplicacaoError::entrada_host_invalid(
5218            host,
5219            "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
5220        ));
5221    }
5222    if rest.contains('*') {
5223        return Err(AplicacaoError::entrada_host_invalid(
5224            host,
5225            "wildcard `*` is allowed only as the first label (`*.example.com`); \
5226             no inner or trailing `*` labels",
5227        ));
5228    }
5229    if rest.ends_with('.') {
5230        return Err(AplicacaoError::entrada_host_invalid(
5231            host,
5232            "must not have a trailing `.` (Gateway API hostnames are not \
5233             fully-qualified with a root dot; the apiserver regex rejects \
5234             trailing dots)",
5235        ));
5236    }
5237
5238    // Reject pure IPv4 literals: four dot-separated labels, every
5239    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
5240    // literals as Hostnames.
5241    let labels: Vec<&str> = rest.split('.').collect();
5242    if labels.len() == 4
5243        && labels
5244            .iter()
5245            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
5246    {
5247        return Err(AplicacaoError::entrada_host_invalid(
5248            host,
5249            "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
5250             literals; use a DNS name)",
5251        ));
5252    }
5253
5254    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
5255    // hyphen, with non-hyphen at both boundaries.
5256    for label in &labels {
5257        if label.is_empty() {
5258            return Err(AplicacaoError::entrada_host_invalid(
5259                host,
5260                "has an empty label (consecutive `..` or a leading `.`)",
5261            ));
5262        }
5263        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
5264            return Err(AplicacaoError::entrada_host_invalid(
5265                host,
5266                format!(
5267                    "label {label:?} exceeds DNS-1123 label max length of \
5268                     {cap} bytes (got {} bytes)",
5269                    label.len(),
5270                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
5271                ),
5272            ));
5273        }
5274        let bytes = label.as_bytes();
5275        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
5276            return Err(AplicacaoError::entrada_host_invalid(
5277                host,
5278                format!(
5279                    "label {label:?} must start and end with an alphanumeric \
5280                     (no leading or trailing `-`)"
5281                ),
5282            ));
5283        }
5284        for &b in bytes {
5285            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
5286            if !valid {
5287                let msg = if b.is_ascii_uppercase() {
5288                    format!(
5289                        "label {label:?} contains uppercase character {ch:?} \
5290                         (Gateway API hostnames are lowercase-only; use {lower:?})",
5291                        ch = b as char,
5292                        lower = label.to_ascii_lowercase()
5293                    )
5294                } else if b == b'_' {
5295                    format!(
5296                        "label {label:?} contains `_` (Gateway API hostnames \
5297                         allow only `[a-z0-9-]`; use `-` instead)"
5298                    )
5299                } else {
5300                    format!(
5301                        "label {label:?} contains invalid character {ch:?} \
5302                         (Gateway API hostnames allow only `[a-z0-9-]`)",
5303                        ch = b as char
5304                    )
5305                };
5306                return Err(AplicacaoError::entrada_host_invalid(host, msg));
5307            }
5308        }
5309    }
5310    Ok(())
5311}
5312
5313/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
5314/// would refuse at admission time. Thin wrapper around
5315/// [`crate::render::is_gateway_api_http_path`] that maps the shared
5316/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
5317/// variant, preserving the more self-locating
5318/// [`AplicacaoError::EntradaPathEmpty`] /
5319/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
5320/// path fails those narrower invariants first.
5321///
5322/// The contract is the canonical HTTP-path grammar — `1..=
5323/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
5324/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
5325/// whitespace/control/non-ASCII bytes — shared with the
5326/// `:contratos :endpoint` axis through the lifted predicate so drift
5327/// between either landing site and the K8s apiserver-side
5328/// HTTPPathMatch.value OpenAPI schema is a build error visible at
5329/// the predicate, not a per-renderer "this passed validate but failed
5330/// admission" surprise. The diagnostic carries the offending `path:`
5331/// verbatim plus a parser-shaped `reason:` naming the specific
5332/// violation, so the author can grep their caixa.lisp for `:paths`
5333/// and fix it in one edit. Same diagnostic shape as
5334/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
5335/// axis.
5336fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
5337    // Empty and missing-leading-`/` are already gated at the call
5338    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
5339    // checking here keeps the per-axis narrower diagnostics in force
5340    // when the predicate is reached directly (and `is_gateway_api_http_path`
5341    // itself defends against `bytes[0]`-style indexing on empty
5342    // input).
5343    if path.is_empty() {
5344        return Err(AplicacaoError::EntradaPathEmpty);
5345    }
5346    if !path.starts_with('/') {
5347        return Err(AplicacaoError::entrada_path_not_absolute(path));
5348    }
5349    crate::render::is_gateway_api_http_path(path)
5350        .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
5351}
5352
5353mod rate_limit_codec {
5354    // `Duration` is no longer named here — the codec routes through
5355    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5356    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
5357    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
5358    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
5359    // closed-set enum's arm-table rather than through vestigial free-helper
5360    // delegates.
5361    use super::{RateLimit, RateLimitUnit};
5362    use serde::{Deserializer, Serializer};
5363
5364    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
5365        // Route through the canonical [`crate::render::serialize_option_via_str`]
5366        // — the substrate-side single-owner primitive for the forward
5367        // arm of the typed-magnitude codec family. See its docstring
5368        // for the full sibling roster.
5369        crate::render::serialize_option_via_str(v, s, render)
5370    }
5371
5372    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
5373        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5374        // — the substrate-side single-owner primitive for the reverse
5375        // arm of the typed-magnitude codec family. See its docstring
5376        // for the full sibling roster.
5377        crate::render::deserialize_option_via_str(d, parse)
5378    }
5379
5380    fn parse(s: &str) -> Result<RateLimit, String> {
5381        // Paired whitespace-rejection arm — same canonical-form
5382        // render-determinism discipline as the peer
5383        // `limits::parse_byte_size` / `limits::parse_duration` /
5384        // `limits::parse_millicores` /
5385        // `supervisor::duration_codec::parse` sites: the ASCII
5386        // byte-scan closes the WhatWG-conformant whitespace bytes
5387        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5388        // `char::is_whitespace` scan closes the strictly-complementary
5389        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5390        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5391        // codepoints) that `str::trim` at parse entry silently strips.
5392        // Either drift class would round-trip through `render` to a
5393        // *different* canonical form on next emit — breaking the
5394        // THEORY.md Part V render-determinism contract on
5395        // `:politicas :rate-limit`.
5396        //
5397        // Routed through the lifted [`crate::render::reject_whitespace`]
5398        // primitive — the substrate-side single-owner paired-arm gate
5399        // every typed-magnitude codec in caixa-core shares.
5400        crate::render::reject_whitespace::<String, _, _>(
5401            s,
5402            |b| {
5403                format!(
5404                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5405                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
5406                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
5407                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
5408                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
5409                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
5410                 on first serialize — breaking the THEORY.md Part V render-determinism \
5411                 contract every typed slot carries. Strip every whitespace byte (write \
5412                 `\"100/s\"` verbatim)"
5413                )
5414            },
5415            |ch| {
5416                format!(
5417                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
5418                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
5419                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
5420                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
5421                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
5422                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
5423                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
5424                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
5425                 silently strips it at parse entry, and the value round-trips through \
5426                 `render` to a *different* canonical form (`\"100/s\"`) on first \
5427                 serialize — breaking the THEORY.md Part V render-determinism contract \
5428                 every typed slot carries. Strip every non-ASCII whitespace character \
5429                 (write `\"100/s\"` verbatim with only ASCII bytes)",
5430                    cp = ch as u32
5431                )
5432            },
5433        )?;
5434        let s = s.trim();
5435        let (rate_str, unit) = s
5436            .split_once('/')
5437            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
5438        let rate_trim = rate_str.trim();
5439        // The canonical authoring form for `:politicas :rate-limit` is
5440        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
5441        // non-negative integer with no decimal point and no leading
5442        // sign, so the parser's accepted set must match for
5443        // serialize/deserialize to round-trip without canonical-form
5444        // drift. Until this gate landed the parser accepted any
5445        // `u32::from_str`-shaped magnitude — and current Rust
5446        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
5447        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
5448        // serde silently round-tripped to `"100/s"` on the next emit
5449        // (a *different* canonical string) — breaking the THEORY.md
5450        // Part V render-determinism contract on the fifth typed-codec
5451        // surface in caixa-core (peer with the four duration codecs the
5452        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
5453        // already covered: `supervisor::duration_codec` backing three
5454        // typed-duration slots, `limits::parse_duration` backing
5455        // `:limits :wall-clock`, `limits::parse_byte_size` backing
5456        // `:limits :memory`). The fractional / decimal-shaped sibling
5457        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
5458        // existing rejection arm, but the diagnostic is value-laundered
5459        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
5460        // doesn't name the canonical-form remediation or the round-trip
5461        // drift the next emit would produce); this gate lifts the
5462        // fractional arm onto the same canonical-form diagnostic the
5463        // peer codecs carry.
5464        //
5465        // Strict canonical form: every byte of the magnitude is an
5466        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
5467        // inputs the gate distinguishes "non-canonical-but-numeric"
5468        // (parses as f64 or i64 — surfaced with a self-locating
5469        // diagnostic naming the canonical authoring form and the
5470        // round-trip drift the rejected shape would produce on first
5471        // serialize) from "garbage" (parses as neither — surfaced with
5472        // the existing narrower `"not a u32"` wording so its
5473        // diagnostic shape remains stable for the parser-shape footgun
5474        // case).
5475        //
5476        // Routed through the lifted
5477        // [`crate::render::is_digit_only_magnitude`] predicate — the
5478        // same source of truth the four peer typed-magnitude codec
5479        // sites share.
5480        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
5481        if !digit_only {
5482            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
5483            if numeric {
5484                return Err(format!(
5485                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
5486                     canonical authoring form for `:politicas :rate-limit` is \
5487                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5488                     with no decimal point and no leading `+` / `-` sign. A fractional / \
5489                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
5490                     through `render` to a *different* canonical form (`\"1/s\"`, \
5491                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
5492                     THEORY.md Part V render-determinism contract every typed slot \
5493                     carries. Pick an integer rate that fits the desired window \
5494                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
5495                ));
5496            }
5497            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
5498        }
5499        // Leading-zero arm — peer with the prior `"+100/s"` arm above
5500        // (4eeae98's predecessor) on the same canonical-form
5501        // render-determinism axis. The digit-only gate accepts
5502        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
5503        // them losslessly (= 100, 0, 7), but `render` emits the
5504        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
5505        // a *different* canonical string on the next emit, breaking
5506        // the THEORY.md Part V render-determinism contract the same
5507        // way `"+100/s"` did before the leading-`+` arm landed. The
5508        // single-byte magnitude `"0"` itself round-trips losslessly
5509        // through `render` (`render(0)` emits `"0/s"`) — the
5510        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
5511        // what refuses rate-zero authoring, so `"0/s"` stays in the
5512        // accepted set at this codec layer and the diagnostic
5513        // partitioning between canonical-form drift (this arm) and
5514        // semantic-zero (the downstream gate) remains stable.
5515        // Peer with the future leading-zero arms on the three peer
5516        // typed-magnitude codecs the trajectory acknowledges:
5517        // `supervisor::duration_codec`, `limits::parse_duration`,
5518        // `limits::parse_byte_size` — each carries the same
5519        // canonical-form-drift class today; this gate lands the
5520        // discipline on the fourth typed-magnitude codec in
5521        // caixa-core first because the peer `"+100/s"` arm above is
5522        // the closest predecessor on the trajectory.
5523        //
5524        // Routed through the lifted
5525        // [`crate::render::is_leading_zero_padded_magnitude`]
5526        // predicate — the same source of truth the four peer
5527        // typed-magnitude codec sites share.
5528        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
5529            return Err(format!(
5530                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
5531                 canonical authoring form for `:politicas :rate-limit` is \
5532                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5533                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
5534                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
5535                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
5536                 first serialize — breaking the THEORY.md Part V render-determinism \
5537                 contract every typed slot carries. Strip the leading zeros (write \
5538                 `\"100/s\"` instead of `\"0100/s\"`)"
5539            ));
5540        }
5541        // The digit-only gate guarantees every byte is `[0-9]`, and
5542        // the leading-zero arm above guarantees the magnitude is
5543        // either the single byte `"0"` or starts with `[1-9]`, so
5544        // the only way `u32::from_str` can fail here is overflow
5545        // (the magnitude exceeds `u32::MAX`). Surface that with an
5546        // overflow-shaped wording so the diagnostic names the
5547        // offending magnitude verbatim rather than collapsing onto
5548        // the non-canonical arm. Same shape
5549        // `supervisor::duration_codec` (1c55a2a) carries on the peer
5550        // duration-codec axis.
5551        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
5552            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
5553        })?;
5554        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
5555        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
5556        // arm reads the `&str → Duration` projection through the
5557        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5558        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
5559        // with [`super::RateLimitUnit::window`]) rather than the vestigial
5560        // module-private `rate_limit_window_from_unit` free helper the
5561        // predecessor 61421a6 left as the last unlifted delegate on this
5562        // axis. One typed dispatch on the substrate primitive instead of
5563        // one runtime call through the free-helper delegate; the sole
5564        // production consumer of the `&str → Duration` axis (this parse
5565        // arm) now reaches for exactly one typed method on the closed-set
5566        // enum, sibling to the codec's render arm's
5567        // [`super::RateLimit::canonical_unit`] dispatch on the paired
5568        // `Duration → RateLimitUnit` axis and to the validate gate's
5569        // [`super::RateLimit::canonical_unit`] shape-probe on the
5570        // canonical-window axis. A future rate-limit-unit addition (a
5571        // `"d"` day suffix once Envoy's `rate_limit_action` grows
5572        // daily-bucket support, a `"ms"` sub-second window once
5573        // high-throughput per-edge policies come into scope per
5574        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
5575        // on the closed-set enum, and the compiler enforces exhaustiveness
5576        // on every consumer's `match self` arms — this parse arm's
5577        // accepted-suffix set, the render arm's emitted-suffix set, the
5578        // validate gate's canonical-window set, and every future
5579        // per-`:contratos`-edge rate-limit-override overlay all pick it up
5580        // by construction.
5581        let unit = unit.trim();
5582        let window = RateLimitUnit::window_from_suffix(unit)
5583            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
5584        Ok(RateLimit { rate, window })
5585    }
5586
5587    fn render(rl: RateLimit) -> String {
5588        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
5589        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
5590        // this render arm reads the `Duration → RateLimitUnit` projection
5591        // through the substrate primitive [`super::RateLimit::canonical_unit`]
5592        // (returns `None` on every non-canonical window — the sub-second /
5593        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
5594        // formats the returned typed enum through its
5595        // [`std::fmt::Display`] impl (which routes through
5596        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
5597        // the substrate primitive instead of one runtime `find_map`
5598        // walk through the free-helper delegate chain
5599        // [`super::rate_limit_window_unit`] (the vestigial free helper's
5600        // sole production consumer was this arm; every other consumer of
5601        // the `Duration → unit` axis — the validate gate below and the
5602        // future M4 per-Aplicacao Envoy config reconciler — now reads
5603        // the same typed method).
5604        //
5605        // A future rate-limit-unit addition (a `"d"` day suffix once
5606        // Envoy's `rate_limit_action` grows daily-bucket support) is
5607        // one variant + one arm per method on the closed-set enum, and
5608        // the compiler enforces exhaustiveness on every consumer's
5609        // `match self` arms — the codec's `parse` accepted-suffix set,
5610        // this render arm's emitted-suffix set, the validate gate's
5611        // canonical-window set, and every future per-`:contratos`-edge
5612        // rate-limit-override overlay all pick it up by construction.
5613        if let Some(unit) = rl.canonical_unit() {
5614            format!("{}/{unit}", rl.rate())
5615        } else {
5616            // Defensive fallback for non-canonical windows. Note:
5617            // [`AplicacaoSpec::validate_politicas`] rejects any
5618            // non-canonical `:rate-limit :window` via
5619            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5620            // a validated `RateLimit` never reaches this branch. The
5621            // emitted `<n>/<k>s` form is *not* round-trippable through
5622            // [`parse`] (which accepts only the closed-set
5623            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5624            // explicit count) — the validate gate is what makes the
5625            // round-trip a structural property; this branch exists only
5626            // so a programmatic non-validated serialize doesn't panic.
5627            format!("{}/{}s", rl.rate(), rl.window().as_secs())
5628        }
5629    }
5630}
5631
5632// ── placement strategy ───────────────────────────────────────────────
5633
5634/// How the Aplicacao distributes across clusters. Three options:
5635///
5636/// - `SingleNode` — one cluster runs the app at a time; takeover on
5637///   death (Erlang/OTP distributed-app semantics).
5638/// - `Replicated` — every named cluster runs an instance (active-active).
5639/// - `Sharded` — entities distribute by hash key across clusters
5640///   (Akka cluster sharding).
5641#[derive(
5642    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5643)]
5644pub enum PlacementStrategy {
5645    SingleNode,
5646    Replicated,
5647    Sharded,
5648}
5649
5650/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5651/// distribution-strategy default for the `:placement :estrategia` axis —
5652/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5653/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5654/// so every substrate-side consumer that resolves "what
5655/// [`PlacementStrategy`] variant does an author-omitted `:placement
5656/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5657/// primitive [`PlacementStrategy`].
5658///
5659/// The `:placement :estrategia` default axis has three production
5660/// consumers on the substrate side today: the [`Default for
5661/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5662/// impl's struct-literal `estrategia` field, and the serde-side
5663/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5664/// author-omitted `:placement :estrategia` scalar through the [`Default
5665/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5666/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5667/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5668/// consumers, with no compile-time link back to the paired
5669/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5670/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5671/// production consumer that resolves an author-omitted `:placement` slot
5672/// (entirely omitted, not just the `:estrategia` scalar within a declared
5673/// `:placement` block) through [`Placement::default`] which then routes
5674/// through this same discriminator. A future coherent rebrand of the
5675/// `:placement :estrategia` default (a widening to `Sharded` once the
5676/// substrate discovers hash-keyed distribution as the more common
5677/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5678/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5679/// names, a per-cluster overlay the operator pins through a future
5680/// `:placement-overrides` slot) would have had to migrate a lifted
5681/// discriminator on one path and open-coded discriminators on the peers
5682/// in lockstep or the four consumers would silently drift out of
5683/// pairing. Lifting the resolution rule to a typed `pub const` on the
5684/// substrate primitive means the M3-mesh-canonical `:placement
5685/// :estrategia` default migrates as one unit on any future axis change.
5686///
5687/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5688/// §II.2's active-active-across-every-named-cluster arm — the closest
5689/// canonical M3 production reference the substrate carries, matching the
5690/// caixa-mesh default axis every M3 renderer already keys off (a
5691/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5692/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5693/// under the substrate's fleet-programs aggregator without an explicit
5694/// `:placement :estrategia` override). The two alternatives the closed
5695/// [`PlacementStrategy::ALL`] accept-set carries
5696/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5697/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5698/// Akka-style hash-keyed distribution across clusters,
5699/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5700/// postures an author declares explicitly, never a posture an omitted
5701/// slot should silently assume.
5702///
5703/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5704/// exactly one source of truth on the `:placement :estrategia` axis, on
5705/// the same substrate-primitive lift discipline the sibling M2
5706/// per-supervisor default set carries
5707/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5708/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5709/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5710/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5711/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5712/// ([`crate::render::DEFAULT_NAMESPACE`],
5713/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5714/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5715/// the M3 mesh-primitive-defining slot family to converge onto the
5716/// substrate-primitive-lift discipline the M2 supervisor-slot family
5717/// already carries end-to-end.
5718pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5719
5720impl Default for PlacementStrategy {
5721    fn default() -> Self {
5722        // Route the [`Default for PlacementStrategy`] impl through the
5723        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5724        // `pub const` rather than a raw `Self::Replicated` arm — one
5725        // source of truth for the M3-mesh-canonical active-active-
5726        // across-every-named-cluster `:placement :estrategia` default
5727        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5728        // lift discipline the sibling M2 per-supervisor default set
5729        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5730        // paired halves) carries end-to-end. Pinned by
5731        // `placement_strategy_default_routes_through_lifted_default`.
5732        PLACEMENT_ESTRATEGIA_DEFAULT
5733    }
5734}
5735
5736impl PlacementStrategy {
5737    /// Exhaustive iteration surface for every consumer that reads the
5738    /// full closed-set (the future M4 admission-webhook's accepted-
5739    /// strategy listing in its rejection body, a future `feira app
5740    /// placement --list` CLI-side surfacing of the accepted arm-set,
5741    /// any future round-trip fuzz harness). A future variant addition
5742    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5743    /// names as a trajectory item) extends this slice as a single edit
5744    /// and every consumer picks up the new entry by construction — the
5745    /// compiler-checked exhaustiveness on the sibling method `match`
5746    /// arms is the build-time guarantee that no arm forgets to grow.
5747    /// Same shape as the sibling closed-set typed enums'
5748    /// [`RateLimitUnit::ALL`] (6bce03d) and
5749    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5750    /// surfaces — the third closed-set typed enum on the caixa surface
5751    /// to converge onto the same discipline.
5752    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5753
5754    /// Canonical camelCase-schema discriminator scalar this variant
5755    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5756    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5757    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5758    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5759    /// every substrate consumer that dispatches on the strategy (the
5760    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5761    /// reconciler, the M3 Adaptive compression pass) reads the same
5762    /// byte-string the `Serialize` derive emits — the pin test in
5763    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5764    /// asserts the two paths agree.
5765    #[must_use]
5766    pub const fn as_str(self) -> &'static str {
5767        match self {
5768            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5769            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5770            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5771        }
5772    }
5773
5774    /// Substrate-canonical reverse projection on the `:placement
5775    /// :estrategia` closed-set axis — parses the camelCase-schema
5776    /// discriminator scalar back to the typed variant, or `None` when
5777    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5778    /// emits. Dispatches on the same lifted
5779    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5780    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5781    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5782    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5783    /// the round-trip migrate through one caixa-core edit on any future
5784    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5785    /// §II.5 hint names as a trajectory item lands one variant + one
5786    /// arm per method and the compiler enforces exhaustiveness on every
5787    /// consumer's `match self` arms).
5788    ///
5789    /// Prior to this lift the substrate carried only the forward
5790    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5791    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5792    /// derive that emits the same byte-string under
5793    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5794    /// consumer that wanted to parse a wire-form strategy scalar had to
5795    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5796    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5797    /// compile-time link back to the typed variant's canonical lifted
5798    /// constant. A future variant rename or a per-arm serde-attribute
5799    /// drift would silently split the wire byte-string one non-serde
5800    /// consumer parsed from the one the emitter wrote, with the
5801    /// failure surfacing at parse time far from the rebrand commit.
5802    ///
5803    /// Same closed-set-reverse-projection discipline the sibling
5804    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5805    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5806    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5807    /// defining `:placement :estrategia` closed-set axis, the third
5808    /// substrate-side closed-set typed enum to converge on the two-way
5809    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5810    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5811    /// and side-step the [`std::str::FromStr`]-collision clippy
5812    /// (`clippy::should_implement_trait`) the plain `from_str` name
5813    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5814    /// on top by delegating to this canonical arm-dispatch method.
5815    ///
5816    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5817    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5818    /// picks the diagnostic form appropriate for its use site — a
5819    /// future `feira app placement --set` CLI-side arg-parse that wants
5820    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5821    /// Sharded)"` diagnostic builds one on top by iterating
5822    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5823    /// path folds `None` onto its per-CR structured refusal body.
5824    #[must_use]
5825    pub fn from_wire(s: &str) -> Option<Self> {
5826        match s {
5827            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5828            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5829            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5830            _ => None,
5831        }
5832    }
5833
5834    /// Substrate-canonical per-arm predicate naming the cross-slot
5835    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5836    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5837    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5838    /// requires — and is the only strategy that permits — a non-empty
5839    /// `:shard-key` on the paired slot). Today the accept-set is the
5840    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5841    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5842    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5843    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5844    /// across every named cluster) have no hash-keyed routing axis to
5845    /// consume the slot and refuse a declared-but-inert `:shard-key`
5846    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5847    ///
5848    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5849    /// satisfies `placement.shard_key().is_some() ==
5850    /// placement.estrategia().requires_shard_key()` by construction — the
5851    /// cross-slot partition the pin
5852    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5853    /// locks load-bearing, so every downstream consumer that reaches for
5854    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5855    /// CR materializer's per-CR shard-key resolver, the future
5856    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5857    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5858    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5859    /// shard-key requirement probe, a future author-facing tatara-lisp
5860    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5861    /// "tenantId"))` shapes before `feira lint` reaches
5862    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5863    /// the substrate primitive — the predicate names *the cross-slot
5864    /// invariant*, not the arm identity.
5865    ///
5866    /// Prior to this lift the "does this strategy consume `:shard-key`"
5867    /// classification lived under the `gen_platform::IsVariant`-derived
5868    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5869    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5870    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5871    /// } else { None }` cascade, the
5872    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5873    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5874    /// "tenantId".to_string())` cascade, and the
5875    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5876    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5877    /// cascade). Each site conflated two semantically distinct questions:
5878    /// "is the variant `Sharded`?" (arm-identity, what
5879    /// [`Self::is_sharded`] answers) and "does the variant consume
5880    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5881    /// The two questions land on the same three-way answer under today's
5882    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5883    /// future arm addition that consumed `:shard-key` under a different
5884    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5885    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5886    /// pool by client-IP hash rather than an author-declared extractor
5887    /// expression, a hypothetical `WeightedShard` variant that carries a
5888    /// shard-key + per-cluster weight table under a promoted M5
5889    /// adaptive-placement engine) or an addition that did *not* consume
5890    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5891    /// split the two questions. Any consumer that read
5892    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5893    /// silently misclassify the new arm as non-consuming — a fixture
5894    /// builder would omit `:shard-key` where the new arm required one and
5895    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5896    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5897    /// commit, a future M4 CR materializer would fall through the
5898    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5899    /// silently emit an empty extractor at the Akka reconciler layer.
5900    ///
5901    /// Lifting the classification as a substrate-primitive method on the
5902    /// closed-set typed enum names the cross-slot invariant on the
5903    /// primitive that owns the partition: every future arm addition
5904    /// declares its `:shard-key` consumption in one place (this predicate's
5905    /// `match self` arm-set), and every downstream consumer that reaches
5906    /// for the paired shape reads through one typed dispatch. Same
5907    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5908    /// per-arm predicate on the pre-projection WIT-shape axis and the
5909    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5910    /// paired predicate on the post-projection typed-view axis — a
5911    /// per-arm semantic-classification predicate paired with the
5912    /// arm-identity predicate the derive already emits, closing the drift
5913    /// footgun on the cross-slot invariant axis.
5914    ///
5915    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5916    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5917    /// invariant reads as "this strategy *requires* the paired
5918    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5919    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5920    /// merely omit it. The `has_*` framing would read as an accessor
5921    /// (returning the presence of an already-carried value) rather than a
5922    /// requirement (naming the invariant the paired slot must satisfy).
5923    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5924    /// shape as the sibling [`WitContract::is_capability`] /
5925    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5926    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5927    /// as a drop-in replacement for the `.is_sharded()` conflated read
5928    /// without a return-shape migration.
5929    #[must_use]
5930    pub const fn requires_shard_key(self) -> bool {
5931        match self {
5932            Self::Sharded => true,
5933            Self::SingleNode | Self::Replicated => false,
5934        }
5935    }
5936}
5937
5938// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5939// cross-slot-invariant per-arm predicate: the module-scope const-eval
5940// assertions below trip at caixa-core build time (not test time) if a
5941// future edit rewires the predicate's arm-set away from the singleton
5942// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5943// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5944// runtime pin covers the same truth-table with a more descriptive
5945// diagnostic on failure; these const-eval items add a build-time failure
5946// surface strictly stronger than the runtime pin (a downstream renderer's
5947// `const`-context reader that composed against a rebound predicate would
5948// still surface here before the test suite even ran) and side-step the
5949// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5950// would otherwise accumulate on the caixa-core module baseline.
5951const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5952const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5953const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5954
5955/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5956/// the pretty-printed byte-string every consumer that formats the strategy
5957/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5958/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5959/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5960/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5961/// admission-webhook rejection body) reaches for the same lifted
5962/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5963/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5964/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5965/// `Serialize` derive already emits under
5966/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5967/// [`PlacementStrategy::as_str`] helper already returns.
5968///
5969/// Until this lift landed the sibling OTP-shape typed enums —
5970/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5971/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5972/// so [`std::fmt::Display`] routes through the same discriminant string
5973/// the wire format emits) — carried a stable [`std::fmt::Display`]
5974/// surface but [`PlacementStrategy`] did not; every consumer reaching
5975/// for a strategy byte-string past the wire format had to pick between
5976/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5977/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5978/// derive), any two of which a future variant rename or
5979/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5980/// desynchronize — with the failure surfacing as a downstream renderer /
5981/// operator's per-strategy dispatch reading one spelling while the wire
5982/// format emitted another, far from the source rebrand commit and with
5983/// no field naming the drift. Routing `Display` through
5984/// [`PlacementStrategy::as_str`] makes the three paths
5985/// (`Debug` for structural inspection, `Display` for user-facing text,
5986/// `Serialize` for the wire format) converge on the same lifted
5987/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5988/// the diagnostic byte-string, and the pretty-printed byte-string move
5989/// as a single unit through one canonical declaration each, by
5990/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5991/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5992/// closes the third path.
5993///
5994/// Pin tests
5995/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5996/// and
5997/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5998/// assert the three paths agree byte-for-byte on every variant, so a
5999/// future variant rename or per-arm serde attribute drift is a build
6000/// error visible at caixa-core test time, not a silent per-consumer
6001/// dispatch miss at apply / reconcile time.
6002impl std::fmt::Display for PlacementStrategy {
6003    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6004        f.write_str(self.as_str())
6005    }
6006}
6007
6008/// Where the Aplicacao runs.
6009#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6010#[serde(rename_all = "camelCase")]
6011pub struct Placement {
6012    /// Distribution strategy.
6013    #[serde(default)]
6014    pub estrategia: PlacementStrategy,
6015
6016    /// Named clusters that host this Aplicacao. Required for
6017    /// `Replicated` and `SingleNode`; for `Sharded` declares the
6018    /// shard pool.
6019    #[serde(default)]
6020    pub clusters: Vec<String>,
6021
6022    /// Optional hint to the placement engine: `"data-locality"`,
6023    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
6024    #[serde(default, skip_serializing_if = "Option::is_none")]
6025    pub affinity: Option<String>,
6026
6027    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
6028    #[serde(default, skip_serializing_if = "Option::is_none")]
6029    pub shard_key: Option<String>,
6030}
6031
6032impl Placement {
6033    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
6034    /// `:shard-key` extractor-expression scalar accessor every consumer
6035    /// of the Aplicacao's hash-keyed distribution routing keys off —
6036    /// returns the author-declared `:placement :shard-key` byte-string
6037    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
6038    /// own `Option<String>` storage; `None` when the slot is absent
6039    /// (the canonical shape under `:estrategia Replicated` /
6040    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
6041    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
6042    /// partition — `validate` refuses any `Placement` past this call
6043    /// that lands `Some` on a non-`Sharded` strategy or `None` on
6044    /// `Sharded`).
6045    ///
6046    /// The `:placement :shard-key` slot carries the Akka-style
6047    /// cluster-sharding entity-id extractor expression
6048    /// (MESH-COMPOSITION §II.4) — validated by
6049    /// [`validate_placement_shard_key`] to be a non-empty printable-
6050    /// ASCII single-token reference (`tenantId`, `$tenantId`,
6051    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
6052    /// future M4 Akka-style cluster-sharding reconciler hashes without
6053    /// re-validating at the runtime layer), and every downstream
6054    /// consumer that reads the key keys off this scalar (the
6055    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
6056    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6057    /// declared-but-inert refusal diagnostic, the caixa-mesh
6058    /// per-Aplicacao `placement.shardKey` emit path the substrate
6059    /// operator's per-entity hash-routing reader consumes, the future
6060    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6061    /// per-shard-key resolver).
6062    ///
6063    /// Prior to this lift the `.shard_key` field was accessed inline at
6064    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
6065    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
6066    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
6067    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
6068    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
6069    /// — two open-coded field-accesses that expressed no compile-time
6070    /// link back to the typed slot. A future extension of the
6071    /// `:placement :shard-key` axis to a richer author surface — a
6072    /// per-cluster override the operator pins through a future
6073    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
6074    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
6075    /// alias table the M4 CR materializer resolves per-CR, a
6076    /// per-Aplicacao dynamic `:shard-key` derivation the future
6077    /// adaptive placement engine computes from `:affinity` weights —
6078    /// would have had to be threaded through both open-coded copies in
6079    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
6080    /// arm refusal would silently disagree on which extractor
6081    /// expression a given Placement resolves to. Lifting the resolution
6082    /// rule to a typed method on the substrate primitive means every
6083    /// downstream consumer of the Aplicacao's per-`:placement`
6084    /// hash-key surface reaches for exactly one typed dispatch — the
6085    /// resolver's accept-set migrates as a unit on any future axis
6086    /// addition.
6087    ///
6088    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
6089    /// [`WitContract::destination`] / [`WitContract::world_ref`]
6090    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
6091    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
6092    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
6093    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
6094    /// typed dispatch on the substrate primitive, thin projections at
6095    /// each consumer" discipline extended onto the per-`:placement`
6096    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
6097    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
6098    /// — opens the "optional per-slot scalar" projection pattern the
6099    /// sibling per-`:placement` `:affinity`, per-`:politicas`
6100    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
6101    /// match the storage field's name; the accessor's identity name
6102    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
6103    /// slot's docstring already carries.
6104    #[must_use]
6105    pub const fn shard_key(&self) -> Option<&str> {
6106        match &self.shard_key {
6107            Some(s) => Some(s.as_str()),
6108            None => None,
6109        }
6110    }
6111
6112    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
6113    /// compression-hint scalar accessor every weighting-consumer of the
6114    /// Aplicacao's per-hint routing surface keys off — returns the
6115    /// author-declared `:placement :affinity` byte-string verbatim as
6116    /// an `Option<&str>`, borrowed from the typed slot's own
6117    /// `Option<String>` storage; `None` when the slot is absent (the
6118    /// canonical shape of an Aplicacao that leaves the compression
6119    /// weighting up to the placement engine's cluster-default arm — no
6120    /// author-authored `data-locality` / `low-latency` / etc. hint
6121    /// biases the routing).
6122    ///
6123    /// The `:placement :affinity` slot carries the M3 Adaptive-
6124    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
6125    /// by [`validate_placement_affinity`] to be a DNS-1123 label
6126    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
6127    /// K8s-conformant label-selector shape every apiserver-side pod-
6128    /// affinity / node-affinity materializer already gates on
6129    /// admission), and every downstream consumer that reads the hint
6130    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
6131    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
6132    /// `placement.affinity` overlay emit path the substrate operator's
6133    /// per-hint weighting-consumer reads, the future M4
6134    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
6135    /// pod-affinity / node-affinity selector resolver).
6136    ///
6137    /// Prior to this lift the `.affinity` field was accessed inline at
6138    /// the sole caixa-core site — the
6139    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
6140    /// `if let Some(a) = &self.placement.affinity { …
6141    /// validate_placement_affinity(a)? … }` cascade — one open-coded
6142    /// field-access that expressed no compile-time link back to the
6143    /// typed slot. A future extension of the `:placement :affinity`
6144    /// axis to a richer author surface — a per-cluster override the
6145    /// operator pins through a future `:placement :affinity-overrides`
6146    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
6147    /// tenant hint alias table the M4 CR materializer resolves per-CR,
6148    /// a per-Aplicacao dynamic `:affinity` derivation the future
6149    /// adaptive placement engine computes from `:clusters` topology —
6150    /// would have had to be threaded through the open-coded copy in
6151    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
6152    /// materializer reader that landed on the axis, or the per-hint
6153    /// value-shape gate and its downstream weighting consumers would
6154    /// silently disagree on which hint a given Placement resolves to.
6155    /// Lifting the resolution rule to a typed method on the substrate
6156    /// primitive means every downstream consumer of the Aplicacao's
6157    /// per-`:placement` compression-hint surface reaches for exactly
6158    /// one typed dispatch — the resolver's accept-set migrates as a
6159    /// unit on any future axis addition.
6160    ///
6161    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
6162    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
6163    /// optional-scalar axis — same "one typed dispatch on the substrate
6164    /// primitive, thin projections at each consumer" discipline extended
6165    /// onto the per-`:placement` M3-Adaptive-compression-hint
6166    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
6167    /// return accessor on the M3 mesh-slot family; closes the last
6168    /// un-lifted per-`:placement` `Option<String>` axis. Named
6169    /// `affinity()` to match the storage field's name; the accessor's
6170    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
6171    /// vocabulary the slot's docstring already carries.
6172    #[must_use]
6173    pub const fn affinity(&self) -> Option<&str> {
6174        match &self.affinity {
6175            Some(s) => Some(s.as_str()),
6176            None => None,
6177        }
6178    }
6179
6180    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
6181    /// strategy scalar accessor every consumer that dispatches on the
6182    /// Aplicacao's per-cluster distribution shape keys off — returns the
6183    /// author-declared `:placement :estrategia` variant verbatim as a
6184    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
6185    /// `PlacementStrategy` storage.
6186    ///
6187    /// The `:placement :estrategia` slot carries the closed-set
6188    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
6189    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
6190    /// `Replicated` — active-active across every named cluster; `Sharded`
6191    /// — Akka-style hash-keyed entity distribution across the cluster pool
6192    /// per §II.4) that every downstream consumer of the Aplicacao's
6193    /// per-cluster fan-out shape keys off. Validated by
6194    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
6195    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
6196    /// matches!(estrategia, Sharded)` — the cross-slot partition the
6197    /// [`Placement::shard_key`] accessor's docstring pins), and every
6198    /// downstream consumer that reads the strategy keys off this scalar
6199    /// (the [`AplicacaoSpec::validate_placement`]
6200    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
6201    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
6202    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
6203    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6204    /// declared-but-inert refusal's
6205    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
6206    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
6207    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
6208    /// emit path the substrate operator's per-strategy fan-out reader
6209    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6210    /// materializer's per-strategy admission-webhook resolver).
6211    ///
6212    /// Prior to this lift the `.estrategia` field was accessed inline at
6213    /// four sites — the [`AplicacaoSpec::validate_placement`]
6214    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
6215    /// `estrategia: self.placement.estrategia`, the same method's
6216    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
6217    /// partition dispatch, the non-`Sharded`-arm
6218    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
6219    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
6220    /// per-Aplicacao strategy print line at
6221    /// `println!("… {} …", spec.placement.estrategia, …)`
6222    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
6223    /// expressed no compile-time link back to the typed slot. A future
6224    /// extension of the `:placement :estrategia` axis to a richer author
6225    /// surface (a per-cluster override the operator pins through a future
6226    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
6227    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
6228    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
6229    /// derivation the future adaptive placement engine computes from
6230    /// `:affinity` + `:clusters` topology) would have had to be threaded
6231    /// through every open-coded copy in lockstep — one consumer reading
6232    /// the raw variant while a peer read the operator-resolved variant
6233    /// would silently split the `PlacementWithoutClusters` /
6234    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
6235    /// partition-dispatch input, a two-consumer split at the validator
6236    /// far from the source `caixa.lisp` with no field naming the
6237    /// strategy-drift root cause. Lifting the resolution rule to a typed
6238    /// method on the substrate primitive means every downstream consumer
6239    /// of the Aplicacao's per-`:placement` distribution-strategy surface
6240    /// reaches for exactly one typed dispatch — the resolver's accept-set
6241    /// migrates as a unit on any future axis addition.
6242    ///
6243    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
6244    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
6245    /// same "one typed dispatch on the substrate primitive, thin
6246    /// projections at each consumer" discipline extended onto the
6247    /// per-`:placement` distribution-strategy `Copy`-composite-enum
6248    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
6249    /// family; first `Copy`-return accessor on the M3 mesh-slot
6250    /// `Placement` type — companion to the sibling per-`:placement`
6251    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6252    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
6253    /// optional-scalar axes, closing the last unlifted per-`:placement`
6254    /// scalar-value axis (the closed-set `PlacementStrategy`
6255    /// distribution-strategy discriminator) so every downstream
6256    /// per-`:placement` reader now routes through a typed dispatch on
6257    /// the substrate primitive. Named `estrategia()` to match the storage
6258    /// field's name; the accessor's identity name maps onto the
6259    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
6260    /// already carries. Declared `pub const fn` (matching the peer M3
6261    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6262    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6263    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6264    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6265    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6266    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6267    /// [`RateLimit`] — every one a `pub const fn`) so every future
6268    /// substrate-side `const`-context consumer of the resolved
6269    /// distribution-strategy variant (a `const _: () = assert!(…)`
6270    /// module-scope invariant pin on a per-fixture typed [`Placement`],
6271    /// a future M4 admission-webhook `const fn` resolver over a typed
6272    /// [`Placement`], any `const fn` composer that fans on the strategy
6273    /// at compile time) reaches through the same typed dispatch on the
6274    /// substrate primitive at const-eval time as at runtime. Pinned by
6275    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
6276    /// const-eval posture at module scope via `const _:() = …` items so
6277    /// any future accidental downgrade to non-`const` trips at caixa-core
6278    /// build time.
6279    #[must_use]
6280    pub const fn estrategia(&self) -> PlacementStrategy {
6281        self.estrategia
6282    }
6283
6284    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
6285    /// per-cluster distribution-target slice accessor every consumer that
6286    /// walks the Aplicacao's declared cluster-pool keys off — returns the
6287    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
6288    /// `&[String]` slice-view, borrowed from the typed slot's own
6289    /// `Vec<String>` storage (a zero-copy slice-view over the same
6290    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
6291    /// through). Non-optional: the empty slice is the load-bearing
6292    /// pre-validation sentinel every downstream consumer of the paired
6293    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
6294    /// off — every strategy in the closed
6295    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
6296    /// requires a non-empty list (`SingleNode` / `Replicated` use the
6297    /// list as hosting / takeover candidates per Erlang/OTP distributed-
6298    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
6299    /// shard pool per Akka cluster-sharding convention, §II.4), so the
6300    /// `.is_empty()` probe is the shared pre-condition every
6301    /// [`AplicacaoSpec::validate_placement`] arm heads on.
6302    ///
6303    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
6304    /// 1123-label per-cluster distribution-target list — the same
6305    /// set-not-multiset shape the sibling `:membros :caixa` /
6306    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
6307    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
6308    /// pins the shape). Every downstream consumer that fans on the list
6309    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
6310    /// pre-flight `.is_empty()` probe that trips
6311    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
6312    /// per-cluster value-shape + duplicate-detection fan-out loop, the
6313    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
6314    /// that materializes the list verbatim onto every
6315    /// programs.yaml entry the substrate operator's per-cluster
6316    /// `placement.clusters | contains .Values.cluster` filter reads,
6317    /// the `feira app graph` per-Aplicacao cluster print line, the
6318    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6319    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
6320    /// placement engine's cluster-topology reader).
6321    ///
6322    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
6323    /// inline at three production sites — the
6324    /// [`AplicacaoSpec::validate_placement`] pre-flight
6325    /// `self.placement.clusters.is_empty()` refusal probe, the same
6326    /// method's per-cluster validate loop's
6327    /// `for c in &self.placement.clusters` traversal head, and the
6328    /// `feira app graph` per-Aplicacao print line's
6329    /// `spec.placement.clusters` `{:?}` formatter argument
6330    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
6331    /// that expressed no compile-time link back to the typed slot. A
6332    /// future extension of the `:placement :clusters` axis to a richer
6333    /// author surface (a per-tenant cluster-pool overlay the operator
6334    /// pins through a future `:placement :clusters-overrides` slot the
6335    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
6336    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
6337    /// the future M5 adaptive-placement engine computes from
6338    /// `:affinity` weights + live cluster-topology probes, a promotion
6339    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
6340    /// partition once the substrate operator's cluster-membership
6341    /// reconciler comes into typed scope) would have had to be threaded
6342    /// through all three open-coded copies in lockstep or one consumer
6343    /// would silently disagree with the peers on which cluster-pool a
6344    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
6345    /// reading the raw slot while the peer per-cluster validate loop
6346    /// read an operator-resolved slot would silently split the paired
6347    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
6348    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
6349    /// input from the pre-flight input, a three-consumer split at the
6350    /// validator and formatter far from the source `caixa.lisp` with
6351    /// no field naming the cluster-pool-drift root cause. Lifting the
6352    /// resolution rule to a typed method on the substrate primitive
6353    /// means every downstream consumer of the Aplicacao's
6354    /// per-`:placement` cluster-pool surface reaches for exactly one
6355    /// typed dispatch — the resolver's accept-set migrates as a unit
6356    /// on any future axis addition.
6357    ///
6358    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
6359    /// slot — sibling to the seed M2
6360    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
6361    /// slice-return accessor on the peer per-`:supervisor` static-
6362    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
6363    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
6364    /// primitive, thin projections at each consumer" discipline. The
6365    /// three peer `Vec`-carry axes still unlifted at the time of this
6366    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
6367    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
6368    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
6369    /// [`crate::UpgradeFromEntry::instructions`]
6370    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6371    /// — inherit this accessor's discipline as future compounding runs
6372    /// migrate their consumers onto the shared slice-return shape.
6373    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
6374    /// type, sibling to the two `Option<&str>`-return
6375    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6376    /// (74ec2d3) accessors and the `Copy`-return
6377    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
6378    /// unlifted per-`:placement` field axis (the `Vec<String>`
6379    /// distribution-target-list carrier) so every downstream
6380    /// per-`:placement` reader now routes through a typed dispatch on
6381    /// the substrate primitive. Named `clusters()` to match the storage
6382    /// field's name verbatim and the tatara-lisp author-surface term
6383    /// (`:clusters`) the field's own docstring already carries; the
6384    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6385    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
6386    /// for. Returns `&[String]` (not `&Vec<String>`) because every
6387    /// downstream consumer of the cluster list treats it as a read-only
6388    /// sequence — the slice-view is the narrowest borrow that supports
6389    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
6390    /// `.len()`) without leaking the backing `Vec`'s
6391    /// grow/push/reserve surface that no consumer of the typed view
6392    /// reaches for (the storage-side `Vec` remains reachable through
6393    /// the `pub clusters` field for the mutation-carrying serde
6394    /// round-trip and per-test fixture-mutation paths).
6395    #[must_use]
6396    pub const fn clusters(&self) -> &[String] {
6397        self.clusters.as_slice()
6398    }
6399}
6400
6401impl Default for Placement {
6402    fn default() -> Self {
6403        Self {
6404            // Route the struct-literal `estrategia` default arm through
6405            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
6406            // typed `pub const` rather than the transitively-derived
6407            // [`PlacementStrategy::default`] route — one source of truth
6408            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
6409            // active-active-across-every-named-cluster arm
6410            // (MESH-COMPOSITION §II.2) that both this struct-literal
6411            // altitude and the sibling [`Default for PlacementStrategy`]
6412            // impl already key off through the same substrate primitive.
6413            // Pinned by
6414            // `placement_default_estrategia_routes_through_lifted_default`.
6415            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
6416            clusters: Vec::new(),
6417            affinity: None,
6418            shard_key: None,
6419        }
6420    }
6421}
6422
6423// ── external entry point ─────────────────────────────────────────────
6424
6425/// External entry point — what an outside caller sees. Renders to a
6426/// Gateway / Ingress + a route to the named member Servico.
6427#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6428#[serde(rename_all = "camelCase")]
6429pub struct Entrada {
6430    /// Public hostname (e.g. `"checkout.quero.cloud"`).
6431    pub host: String,
6432
6433    /// Member Servico the gateway routes to. Must be in `:membros`.
6434    pub para: String,
6435
6436    /// Optional path filter — if set, only matching paths route to
6437    /// this Aplicacao (the rest fall through to other route rules).
6438    #[serde(default)]
6439    pub paths: Vec<String>,
6440
6441    /// Default port on the destination Servico (the trigger.service.port).
6442    #[serde(default = "default_port")]
6443    pub port: u16,
6444}
6445
6446impl Entrada {
6447    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
6448    /// every HTTPRoute-aware renderer keys off — returns the author-
6449    /// declared `:entrada :paths` list verbatim when non-empty, and the
6450    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
6451    /// all fallback otherwise (so an Aplicacao author who declares an
6452    /// external `:entrada` block but no per-path rule surface still
6453    /// gets a route whose sole `HTTPPathMatch` matches every incoming
6454    /// request under the paired
6455    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
6456    ///
6457    /// Prior to this lift the "if `:entrada :paths` is empty use the
6458    /// substrate catch-all; else return each declared path verbatim"
6459    /// cascade lived inline at
6460    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
6461    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
6462    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
6463    /// substrate ships today, with no typed method on the substrate
6464    /// primitive that named the rule. A future path-resolution axis
6465    /// addition — a per-cluster `:entrada :default-path` override the
6466    /// operator pins through a future `:placement`-scoped slot, an
6467    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6468    /// admission-webhook floor that materializes the catch-all before
6469    /// the CR lands, a future per-`:entrada :paths` overlay from a
6470    /// per-cluster policy the future `feira app deploy` pipeline
6471    /// consumes — would have to be threaded through every renderer's
6472    /// inline copy of the cascade in lockstep or one consumer would
6473    /// silently disagree with the peers on which path list a given
6474    /// `:entrada` block resolves to. Lifting the rule to a typed
6475    /// method on the substrate primitive means every downstream
6476    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
6477    /// per-cluster overlay resolver, every future per-Aplicacao
6478    /// snapshot renderer) reaches for exactly one typed dispatch —
6479    /// the resolver's accept-set moves as a unit on any future axis
6480    /// addition.
6481    ///
6482    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
6483    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
6484    /// per-`:entrada` scalar-value axes — extends the "one typed
6485    /// dispatch on the substrate primitive, thin projections at each
6486    /// consumer" discipline onto the per-`:entrada` path-list
6487    /// resolution axis every HTTPRoute-aware renderer consumes. Same
6488    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
6489    /// sibling `:politicas` primitive — one typed method on the
6490    /// substrate primitive that names the cascade every renderer
6491    /// otherwise re-inlines.
6492    #[must_use]
6493    pub fn resolved_paths(&self) -> Vec<&str> {
6494        // Route the internal cascade-head + per-entry projection reads
6495        // through the lifted [`Self::paths`] slice accessor rather than
6496        // the raw `self.paths` field access — the substrate-primitive
6497        // per-`:entrada` path-list resolver's two internal reads now
6498        // key off the canonical raw-slot surface every downstream
6499        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
6500        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
6501        // entrada summary line's `{:?}` Debug print) routes through, so
6502        // any future rebrand on the typed slot's raw-slot reader lands
6503        // at exactly one place. Same two-consumer coherence discipline
6504        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
6505        // the peer M3 mesh-slot `Vec<String>`-carry axis.
6506        if self.paths().is_empty() {
6507            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
6508        } else {
6509            self.paths().iter().map(String::as_str).collect()
6510        }
6511    }
6512
6513    /// Substrate-canonical per-`:entrada` DNS-hostname singular
6514    /// accessor every Gateway-API `Listener.hostname` reader keys off
6515    /// — returns the author-declared `:entrada :host` byte-string
6516    /// verbatim as a `&str`, borrowed from the typed slot's own
6517    /// [`String`] storage.
6518    ///
6519    /// Named the "singular" half of the DNS-hostname resolver pair on
6520    /// the substrate primitive: the parent-Gateway per-listener
6521    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
6522    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
6523    /// hostname per listener), and this accessor is the typed dispatch
6524    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
6525    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
6526    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
6527    /// per-Aplicacao ingress-hostname surface projects onto.
6528    ///
6529    /// Prior to this lift the `entrada.host.clone()` byte-string was
6530    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
6531    /// per-listener singular `hostname:` axis
6532    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
6533    /// per-HTTPRoute plural `spec.hostnames[]` axis
6534    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
6535    /// consumers read the same `entrada.host` field but the two-site
6536    /// duplication expressed no compile-time contract that the singular
6537    /// Gateway-listener filter and the plural `HTTPRoute` filter list
6538    /// stay in lockstep on future extensions of the `:entrada` slot to
6539    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
6540    /// overlay, a per-cluster SNI fan-out the operator pins through a
6541    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
6542    /// Aplicacao` CR materializer's per-listener virtual-host filter
6543    /// admission-webhook overlay). Any such extension would have to be
6544    /// threaded through every renderer's inline copy of the resolution
6545    /// in lockstep or the Gateway listener's `hostname:` filter would
6546    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
6547    /// — a Gateway-API-conformance divergence whose apply-time symptom
6548    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
6549    /// `NoMatchingParent` — the API server rejects the route because
6550    /// its `hostnames[]` filter doesn't intersect the parent listener's
6551    /// `hostname` filter) is far from the source `caixa.lisp` and never
6552    /// surfaces in the emitted YAML. Lifting the singular and plural
6553    /// resolvers to typed methods on the substrate primitive means
6554    /// every consumer of the Aplicacao's ingress-hostname surface
6555    /// reaches for exactly one typed dispatch, and the pair-invariant
6556    /// `hostnames() == vec![hostname()]` pinned by the sibling
6557    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
6558    /// keeps the two axes in lockstep by construction.
6559    ///
6560    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
6561    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
6562    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
6563    /// the substrate primitive, thin projections at each consumer"
6564    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6565    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6566    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6567    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
6568    /// `:entrada` scalar-value + list-value axes.
6569    #[must_use]
6570    pub const fn hostname(&self) -> &str {
6571        self.host.as_str()
6572    }
6573
6574    /// Substrate-canonical per-`:entrada` DNS-hostname plural
6575    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
6576    /// keys off — returns the singleton `[hostname()]` list under
6577    /// today's single-hostname-per-Aplicacao author surface, and the
6578    /// authoritative multi-hostname list under a future
6579    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
6580    ///
6581    /// Plural half of the DNS-hostname resolver pair — see the
6582    /// companion [`Entrada::hostname`] docstring for the two-consumer
6583    /// lift + pair-invariant discipline (`hostnames() ==
6584    /// vec![hostname()]`, pinned load-bearing by the sibling
6585    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
6586    /// test).
6587    ///
6588    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
6589    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
6590    /// per-rule path-list axis — same `Vec<&str>` shape, same
6591    /// substrate-primitive-owns-the-resolver discipline extended to
6592    /// the per-HTTPRoute virtual-host filter-list axis.
6593    #[must_use]
6594    pub fn hostnames(&self) -> Vec<&str> {
6595        vec![self.hostname()]
6596    }
6597
6598    /// Substrate-canonical per-`:entrada` destination-Servico scalar
6599    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
6600    /// the author-declared `:entrada :para` byte-string verbatim as a
6601    /// `&str`, borrowed from the typed slot's own [`String`] storage.
6602    ///
6603    /// The `:entrada :para` slot names the single member Servico the
6604    /// external Gateway routes to (validated by
6605    /// [`AplicacaoSpec::validate`] to be a
6606    /// [`Membro::caixa`] the Aplicacao declares — a stray
6607    /// `:para` that doesn't name a member is
6608    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
6609    /// backend-attachment miss at cluster-apply time). Under today's
6610    /// single-destination author surface `:entrada :para` is the ingress
6611    /// apex Servico's canonical identity; under a hypothetical
6612    /// future multi-backend author surface (a `:entrada
6613    /// :split :backends` weighted-fan-out overlay for canary /
6614    /// blue-green traffic-split rollouts, per-path override for
6615    /// path-based per-Servico routing beyond the single-apex model,
6616    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6617    /// per-CR admission-webhook that promotes the scalar to a
6618    /// weighted list) this accessor is the substrate primitive's typed
6619    /// dispatch every downstream `HTTPRoute`-aware consumer routes
6620    /// through, so the resolution shape migrates as a unit on one
6621    /// caixa-core edit rather than a coordinated rewrite across every
6622    /// renderer's inline field-access.
6623    ///
6624    /// Prior to this lift the `entrada.para` byte-string was accessed
6625    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6626    /// `metadata.name` composer's per-destination discriminator arg
6627    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6628    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6629    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6630    /// (`entrada.para.clone()`,
6631    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6632    /// consumers read the same `entrada.para` field but the two-site
6633    /// duplication expressed no compile-time contract that the HTTPRoute
6634    /// name-discriminator and the per-rule backend name stay in
6635    /// lockstep on future extensions of the `:entrada` slot to a
6636    /// multi-destination author surface. Any such extension would have
6637    /// to be threaded through every renderer's inline copy of the
6638    /// destination projection in lockstep or the HTTPRoute
6639    /// `metadata.name` would silently reference a different destination
6640    /// than its own `backendRefs[]` — an operator-side
6641    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6642    /// grep-by-name lookup would land on a route whose `backendRefs[]`
6643    /// silently point at a peer Servico, dropping every external
6644    /// `:entrada` flow at the gateway with the destination-drift root
6645    /// cause invisible in the emitted YAML.
6646    ///
6647    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6648    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6649    /// the per-listener singular / per-HTTPRoute plural filter axes and
6650    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6651    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6652    /// typed dispatch on the substrate primitive, thin projections at
6653    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6654    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6655    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6656    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6657    /// sibling per-`:entrada` scalar-value + list-value axes — this
6658    /// accessor closes the last unlifted per-`:entrada` scalar axis
6659    /// (the destination-Servico byte-string) so every downstream
6660    /// per-`:entrada` reader now routes through a typed dispatch on
6661    /// the substrate primitive.
6662    #[must_use]
6663    pub const fn destination(&self) -> &str {
6664        self.para.as_str()
6665    }
6666
6667    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6668    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6669    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6670    /// reader keys off — returns the author-declared `:entrada :port`
6671    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6672    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6673    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6674    /// [`AplicacaoError::EntradaPortZero`], not a silent
6675    /// admission-webhook rejection at cluster-apply time).
6676    ///
6677    /// The `:entrada :port` slot carries the destination Servico's
6678    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6679    /// the `pleme-computeunit` library chart), and every downstream
6680    /// consumer that reads the port keys off this scalar (the
6681    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6682    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6683    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6684    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6685    /// CR materializer's per-Aplicacao gateway port resolver).
6686    ///
6687    /// Prior to this lift the `.port` field was accessed inline at two
6688    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6689    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6690    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6691    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6692    /// open-coded field-accesses that expressed no compile-time link
6693    /// back to the typed slot. A future extension of the `:entrada :port`
6694    /// axis to a richer author surface — a per-cluster override the
6695    /// operator pins through a future `:placement :default-port` slot the
6696    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6697    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6698    /// heterogeneous listener ports, an M4
6699    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6700    /// admission-webhook floor that promotes the scalar to a
6701    /// per-destination map — would have had to be threaded through both
6702    /// open-coded copies in lockstep or the structural-floor validator
6703    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6704    /// silently disagree on which port a given [`Entrada`] resolves to.
6705    /// Lifting the resolution rule to a typed method on the substrate
6706    /// primitive means every downstream consumer of the Aplicacao's
6707    /// per-`:entrada` L4-port surface reaches for exactly one typed
6708    /// dispatch — the resolver's accept-set migrates as a unit on any
6709    /// future axis addition.
6710    ///
6711    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6712    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6713    /// accessors on the per-`:entrada` scalar-value axis — same "one
6714    /// typed dispatch on the substrate primitive, thin projections at
6715    /// each consumer" discipline extended onto the per-`:entrada`
6716    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6717    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6718    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6719    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6720    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6721    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6722    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6723    /// storage field's name; the accessor's identity name maps onto the
6724    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6725    /// already carries. Declared `pub const fn` (matching the peer M3
6726    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6727    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6728    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6729    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6730    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6731    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6732    /// [`RateLimit`], and the sibling per-`:placement`
6733    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6734    /// enum scalar axis — every one a `pub const fn`) so every future
6735    /// substrate-side `const`-context consumer of the resolved
6736    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6737    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6738    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6739    /// admission-webhook `const fn` per-CR gateway-port floor over a
6740    /// typed [`Entrada`], any `const fn` composer that fans on the port
6741    /// at compile time) reaches through the same typed dispatch on the
6742    /// substrate primitive at const-eval time as at runtime. Pinned by
6743    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6744    /// const-eval posture at module scope via `const _:() = …` items so
6745    /// any future accidental downgrade to non-`const` trips at caixa-core
6746    /// build time.
6747    #[must_use]
6748    pub const fn port(&self) -> u16 {
6749        self.port
6750    }
6751
6752    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6753    /// slice accessor every HTTPRoute-aware renderer keys off when it
6754    /// wants the raw author-declared path-list (not the fallback-
6755    /// applied projection [`Self::resolved_paths`] returns) — returns
6756    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6757    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6758    ///
6759    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6760    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6761    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6762    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6763    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6764    /// catch-all; non-empty slot → per-entry verbatim projection); this
6765    /// accessor closes the raw-slot arm every consumer that must see the
6766    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6767    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6768    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6769    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6770    /// external-gateway summary line's `{:?}` Debug print — which must
6771    /// name the author's declaration, not the substrate's fallback, so
6772    /// an author reading their graph output can grep their caixa.lisp
6773    /// for the exact list they authored) routes through.
6774    ///
6775    /// Prior to this lift the `.paths` field was accessed inline at four
6776    /// production sites: the two internal reads in [`Self::resolved_paths`]
6777    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6778    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6779    /// value-shape gate's `for p in &e.paths` traversal head, and the
6780    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6781    /// Debug print — four open-coded field-accesses that expressed no
6782    /// compile-time link back to the typed slot. A future extension of
6783    /// the `:entrada :paths` axis to a richer author surface — a
6784    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6785    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6786    /// spec supports through `matches[].method`), a per-path per-header
6787    /// filter overlay (`matches[].headers[]`), a per-cluster override
6788    /// the operator pins through a future `:placement :path-overlay`
6789    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6790    /// per-CR admission-webhook that normalized the list at admission
6791    /// time — would have had to be threaded through every open-coded
6792    /// copy in lockstep or the validator's per-entry gate would silently
6793    /// disagree with the renderer's per-entry emit on which list a given
6794    /// `:entrada` block resolves to. Lifting the resolution to a typed
6795    /// method on the substrate primitive means every downstream consumer
6796    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6797    /// exactly one typed dispatch — the resolver's accept-set migrates
6798    /// as a unit on any future axis addition.
6799    ///
6800    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6801    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6802    /// carry axis — same "one typed dispatch on the substrate primitive,
6803    /// thin projections at each consumer" discipline extended onto the
6804    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6805    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6806    /// carrier) so every downstream per-`:entrada` reader now routes
6807    /// through a typed dispatch on the substrate primitive. Returns
6808    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6809    /// treats the list as a read-only sequence — the slice-view is the
6810    /// narrowest borrow that supports every present + roadmapped consumer
6811    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6812    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6813    /// view reaches for (the storage-side `Vec` remains reachable through
6814    /// the `pub paths` field for the mutation-carrying serde round-trip
6815    /// and per-test fixture-mutation paths).
6816    #[must_use]
6817    pub const fn paths(&self) -> &[String] {
6818        self.paths.as_slice()
6819    }
6820}
6821
6822/// Canonical default L4 port every typed Servico exposes on its
6823/// in-cluster K8s Service (the `trigger.service.port` axis the
6824/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6825/// surface defaults to when the author omits the slot, and the
6826/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6827/// `:entrada` block matches the per-`:contratos` destination Servico).
6828/// The single source of truth all three typed-port consumers reach for:
6829///
6830///   - [`Entrada::port`]'s serde default (via the
6831///     [`default_port`] helper this constant feeds); the author surface
6832///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6833///     reads back as a typed [`Entrada`] carrying this exact value;
6834///   - the
6835///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6836///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6837///     fallback, fired when the typed `:entrada` block doesn't name
6838///     the per-`:contratos` destination Servico — the typed
6839///     `:contratos` graph carries no per-destination port axis (the
6840///     destination port is the destination Servico's
6841///     `lareira-<nome>` chart's `trigger.service.port`, which the
6842///     Aplicacao-level renderer has no visibility into without a
6843///     resolver round-trip), so the renderer falls back to the
6844///     substrate's canonical Servico-port assumption — by
6845///     construction the same value the destination's own
6846///     `pleme-computeunit` chart emits, the same value the
6847///     destination's own typed `:entrada :port` slot defaults to;
6848///   - every future per-Servico renderer the absorption-roadmap
6849///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6850///     CR materializer's per-edge port resolver, the future
6851///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6852///     emitter's per-route bucket key, the future caixa-otel
6853///     collector-pipeline emitter's per-Servico scrape port).
6854///
6855/// Until this lift landed the value `8080` lived at two production-code
6856/// call-sites: the [`default_port`] helper at
6857/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6858/// and the `.unwrap_or(8080)` literal at
6859/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6860/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6861/// resolver). A future Servico-port rebrand — the substrate moving the
6862/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6863/// gateway grows direct `:80` listeners, to `8443` once the substrate
6864/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6865/// override the operator pins through a future
6866/// `:placement :default-port` slot — without a coordinated edit on
6867/// both sides would silently emit Servicos listening on one port and
6868/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6869/// The CNP's apply-time symptom (the policy is admitted but every L4
6870/// flow on the destination Servico's actual port silently drops because
6871/// it doesn't match the whitelisted port) is far from the rebrand
6872/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6873/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6874/// a shared constant closes the drift footgun structurally — both
6875/// consumers read from the same `u16`, so any rebrand reaches both
6876/// sites by construction.
6877///
6878/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6879/// per-renderer canonical-K8s-axis constant — the namespace string
6880/// and the canonical Servico port both lived as duplicated literals
6881/// across caixa-core / caixa-mesh / caixa-flux before their respective
6882/// lifts. Same "the typed constant lives in one place" discipline the
6883/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6884/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6885/// shared-string axes.
6886///
6887/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6888pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6889
6890/// Structural floor for the typed `:entrada :port` axis — every
6891/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6892/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6893///
6894/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6895/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6896/// interprets as "let the kernel pick a free port at bind time", not a
6897/// well-defined destination the substrate's per-`:entrada` Gateway API
6898/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6899/// carrying `port: 0` degenerates to a nominal-only routing target: the
6900/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6901/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6902/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6903/// at build time rather than at `kubectl apply` time), and the
6904/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6905/// (caixa-mesh/src/lib.rs:2657 through
6906/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6907/// [`Entrada::port`] typed value — silently emits a policy whose
6908/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6909/// actual listener, dropping every L4 flow at the eBPF data plane far
6910/// from the source caixa.lisp with no field naming the port-zero-drift
6911/// root cause.
6912///
6913/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6914/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6915/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6916/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6917/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6918/// well below `u32::MAX` and therefore need explicit typed caps).
6919///
6920/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6921/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6922/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6923/// `:port` inherits through the serde default hook; this constant names
6924/// the accept-set floor every declared port must satisfy. The pair is
6925/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6926/// substrate's default must satisfy its own accept-set floor by
6927/// construction) — a future rebrand that accidentally moved
6928/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6929/// negative-cast typo, a per-cluster override the operator pins through
6930/// a future `:placement :default-port` slot that lands out-of-range)
6931/// would silently invalidate the serde-default emission at every
6932/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6933/// invariant pin
6934/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6935/// closes the drift footgun at caixa-core build time.
6936///
6937/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6938/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6939/// has exactly one source of truth — the future M4
6940/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6941/// gateway resolver, the future per-Servico
6942/// `computeunit.trigger.service.port` renderer's per-CR port-value
6943/// validator, and every downstream test-fixture navigator asserting
6944/// the accept-set floor all read from one place. Same shape every
6945/// other typed bracket-floor / bracket-ceiling in this crate carries
6946/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6947/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6948/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6949/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6950/// [`POLICY_RATE_LIMIT_MAX`]).
6951pub const SERVICO_PORT_MIN: u16 = 1;
6952
6953const fn default_port() -> u16 {
6954    DEFAULT_SERVICO_PORT
6955}
6956
6957// ── the typed view ───────────────────────────────────────────────────
6958
6959/// Typed composition view of the flat Aplicacao slots on
6960/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6961/// validation + downstream renderer consumption.
6962#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6963#[serde(rename_all = "camelCase")]
6964pub struct AplicacaoSpec {
6965    pub membros: Vec<Membro>,
6966    pub contratos: Vec<WitContract>,
6967    pub politicas: MeshPolicy,
6968    pub placement: Placement,
6969    pub entrada: Option<Entrada>,
6970}
6971
6972impl AplicacaoSpec {
6973    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6974    /// per-Aplicacao member-list slice-return accessor every
6975    /// per-Aplicacao member-list reader keys off — returns the author-
6976    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6977    /// over the same backing buffer the raw `self.membros.as_slice()`
6978    /// field access borrows from.
6979    ///
6980    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6981    /// member list — the load-bearing identity of the application graph
6982    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6983    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6984    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6985    /// accessor) with a `:versao` semver-requirement string (through
6986    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6987    /// and every downstream consumer that fans on the member-set keys
6988    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6989    /// membership-lookup `HashSet<&str>` seed's collect input, the
6990    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6991    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6992    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6993    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6994    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6995    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6996    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6997    /// member-count print line and per-member tree traversal,
6998    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6999    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
7000    /// placement engine's per-member weight-topology reader).
7001    ///
7002    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
7003    /// inline at six production sites — the [`AplicacaoSpec::validate`]
7004    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
7005    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
7006    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
7007    /// probe, the same method's per-member `for m in &self.membros`
7008    /// validate-loop traversal head, the
7009    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7010    /// `for m in &self.membros` adjacency-list seed, the
7011    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
7012    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
7013    /// paired with the peer `for m in &spec.membros` per-entry fan-out
7014    /// loop, and the `feira app graph` per-Aplicacao print line's
7015    /// `spec.membros.len()` count formatter argument paired with the
7016    /// peer `for m in &spec.membros` per-member tree traversal — six
7017    /// open-coded field-accesses that expressed no compile-time link
7018    /// back to the typed slot. A future extension of the `:membros`
7019    /// axis to a richer author surface (a per-cluster member-set
7020    /// overlay the operator pins through a future
7021    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
7022    /// roadmap acknowledges, a per-tenant member-alias table the M4
7023    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
7024    /// CR at admission time, a per-Aplicacao dynamic member-set
7025    /// derivation the future adaptive-placement engine computes from
7026    /// weighted membership topology, a promotion of the plain
7027    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
7028    /// Orleans-style virtual-actor dynamic-membership comes into typed
7029    /// scope) would have had to be threaded through all six open-coded
7030    /// copies in lockstep or one consumer would silently disagree with
7031    /// the peers on which member-set a given Aplicacao resolves to —
7032    /// the `HashSet<&str>` name-set seed reading the raw slot while
7033    /// the peer `.is_empty()` refusal probe read an operator-resolved
7034    /// slot would silently split the `:contratos` membership-lookup
7035    /// input from the pre-flight-refusal input, a six-consumer split
7036    /// at the validator + programs.yaml emitter + graph printer far
7037    /// from the source `caixa.lisp` with no field naming the member-
7038    /// set-drift root cause. Lifting the resolution rule to a typed
7039    /// method on the substrate primitive means every downstream
7040    /// consumer of the Aplicacao's per-`:membros` member-list surface
7041    /// reaches for exactly one typed dispatch — the resolver's accept-
7042    /// set migrates as a unit on any future axis addition.
7043    ///
7044    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
7045    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7046    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7047    /// static-child-list `Vec`-carry axis, and to the M3
7048    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7049    /// on the peer per-`:placement` distribution-target-list `Vec`-
7050    /// carry axis. Same "one typed dispatch on the substrate primitive,
7051    /// thin projections at each consumer" discipline. The two peer
7052    /// `Vec`-carry axes still unlifted at the time of this lift —
7053    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
7054    /// WIT-typed edge list) and
7055    /// [`crate::UpgradeFromEntry::instructions`]
7056    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7057    /// — inherit this accessor's discipline as future compounding runs
7058    /// migrate their consumers onto the shared slice-return shape.
7059    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
7060    /// `AplicacaoSpec` type itself, extending the discipline beyond
7061    /// the inner per-slot types ([`crate::Placement`],
7062    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
7063    /// view every renderer consumes. Named `membros()` to match the
7064    /// storage field's name verbatim and the tatara-lisp author-
7065    /// surface term (`:membros`) the field's own docstring already
7066    /// carries; the accessor's identity maps onto the canonical
7067    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
7068    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
7069    /// every downstream consumer of the member list treats it as a
7070    /// read-only sequence — the slice-view is the narrowest borrow
7071    /// that supports every present + roadmapped consumer
7072    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7073    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7074    /// the typed view reaches for (the storage-side `Vec` remains
7075    /// reachable through the `pub membros` field for the mutation-
7076    /// carrying serde round-trip and per-test fixture-mutation paths).
7077    #[must_use]
7078    pub const fn membros(&self) -> &[Membro] {
7079        self.membros.as_slice()
7080    }
7081
7082    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
7083    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
7084    /// accessor every per-Aplicacao contract-list reader keys off —
7085    /// returns the author-declared `:contratos` list verbatim as a
7086    /// `&[WitContract]` slice-view over the same backing buffer the raw
7087    /// `self.contratos.as_slice()` field access borrows from.
7088    ///
7089    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
7090    /// WIT-typed edge list — the load-bearing set of directed edges
7091    /// on the application graph whose nodes are the `:membros` entries
7092    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
7093    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
7094    /// six-tuple is the edge identity every downstream duplicate gate
7095    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
7096    /// Servico caller name + a `:para` destination-Servico callee name
7097    /// (through the lifted [`WitContract::source`] +
7098    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
7099    /// caller/callee-Servico axis) with a `:wit` world-reference
7100    /// (through the lifted [`WitContract::world_ref`] (0804823)
7101    /// accessor) and the target-shape-appropriate payload-carrier
7102    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
7103    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
7104    /// (ed22b66) accessor on the per-target-shape payload-carrier
7105    /// axis). Every downstream consumer that fans on the edge-set
7106    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
7107    /// name-set / self-edge / target-shape / dedup fan-out loop, the
7108    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
7109    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
7110    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
7111    /// grouping loop, the `feira app graph` per-Aplicacao contract-
7112    /// count print line and per-contract tree traversal, every future
7113    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
7114    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
7115    /// mesh-policy overlay resolver's per-contract typed-edge weight
7116    /// reader).
7117    ///
7118    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
7119    /// accessed inline at four production sites — the
7120    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
7121    /// per-edge validate-loop traversal head (which drives every
7122    /// per-edge name-set membership lookup, self-edge check,
7123    /// target-shape dispatch, and dedup `HashSet` insert), the
7124    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7125    /// `for c in &self.contratos` adjacency-list seed head (which
7126    /// drives every per-edge sync-vs-pub-sub partition and per-edge
7127    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
7128    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
7129    /// `BTreeMap` grouping loop head (which drives every per-CNP
7130    /// fan-out emit), and the `feira app graph` per-Aplicacao print
7131    /// line's `spec.contratos.len()` count formatter argument paired
7132    /// with the peer `for c in &spec.contratos` per-contract tree
7133    /// traversal — four open-coded field-accesses that expressed no
7134    /// compile-time link back to the typed slot. A future extension
7135    /// of the `:contratos` axis to a richer author surface (a
7136    /// per-cluster contract overlay the operator pins through a
7137    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
7138    /// federation roadmap acknowledges, a per-tenant edge-policy
7139    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
7140    /// materializer resolves per-CR at admission time, a per-edge
7141    /// weight scalar the future adaptive-placement engine reads to
7142    /// bias sync-subgraph routing, a promotion of the plain
7143    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
7144    /// once virtual-actor-style dynamic-edge composition comes into
7145    /// typed scope) would have had to be threaded through all four
7146    /// open-coded copies in lockstep or one consumer would silently
7147    /// disagree with the peers on which edge-set a given Aplicacao
7148    /// resolves to — the validator's per-edge dedup `HashSet` seed
7149    /// reading the raw slot while the peer sync-cycle adjacency-list
7150    /// seed read an operator-resolved slot would silently split the
7151    /// build-time edge-set gate from the runtime deadlock-detection
7152    /// gate, a four-consumer split at the validator, the cycle
7153    /// detector, the CNP emitter, and the graph printer far from
7154    /// the source `caixa.lisp` with no field naming the edge-set-
7155    /// drift root cause. Lifting the resolution rule to a typed method on the
7156    /// substrate primitive means every downstream consumer of the
7157    /// Aplicacao's per-`:contratos` edge-list surface reaches for
7158    /// exactly one typed dispatch — the resolver's accept-set
7159    /// migrates as a unit on any future axis addition.
7160    ///
7161    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
7162    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7163    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7164    /// static-child-list `Vec`-carry axis, to the M3
7165    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7166    /// on the peer per-`:placement` distribution-target-list `Vec`-
7167    /// carry axis, and to the immediately-adjacent sibling M3
7168    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
7169    /// the peer per-`:membros` node-list `Vec`-carry axis — the
7170    /// per-`:contratos` edge-list accessor is the natural pair of
7171    /// the per-`:membros` node-list accessor (graph edges over graph
7172    /// nodes; every graph-shaped consumer reads both). Same "one
7173    /// typed dispatch on the substrate primitive, thin projections
7174    /// at each consumer" discipline. The last remaining `Vec`-carry
7175    /// axis still unlifted at the time of this lift —
7176    /// [`crate::UpgradeFromEntry::instructions`]
7177    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
7178    /// list) — inherits this accessor's discipline as future
7179    /// compounding runs migrate its consumers onto the shared slice-
7180    /// return shape. Second `&[T]`-return accessor on the top-level
7181    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
7182    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
7183    /// `:contratos` are the two `Vec` fields on the outer typed
7184    /// composition view — `:politicas`, `:placement`, `:entrada` are
7185    /// scalar/option-shaped and already route through their per-slot
7186    /// accessor families). Named `contratos()` to match the storage
7187    /// field's name verbatim and the tatara-lisp author-surface term
7188    /// (`:contratos`) the field's own docstring already carries; the
7189    /// accessor's identity maps onto the canonical MESH-COMPOSITION
7190    /// §III.1 vocabulary the slot's docstring already reaches for.
7191    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
7192    /// every downstream consumer of the contract list treats it as a
7193    /// read-only sequence — the slice-view is the narrowest borrow
7194    /// that supports every present + roadmapped consumer
7195    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7196    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7197    /// the typed view reaches for (the storage-side `Vec` remains
7198    /// reachable through the `pub contratos` field for the mutation-
7199    /// carrying serde round-trip and per-test fixture-mutation paths).
7200    #[must_use]
7201    pub const fn contratos(&self) -> &[WitContract] {
7202        self.contratos.as_slice()
7203    }
7204
7205    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
7206    /// per-Aplicacao mesh-policy composite-reference accessor every
7207    /// per-Aplicacao policy-block reader keys off — returns the author-
7208    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
7209    /// reference over the same backing storage the raw `&self.politicas`
7210    /// field access borrows from.
7211    ///
7212    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
7213    /// mesh-policy composite — the load-bearing container of every
7214    /// mesh-level operational-policy axis every downstream mesh-artifact
7215    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
7216    /// mesh-policy overlay is the single typed surface a
7217    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
7218    /// from). Every per-`:politicas` axis threads through a lifted
7219    /// per-slot accessor on the [`MeshPolicy`] type: the
7220    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
7221    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
7222    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
7223    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
7224    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
7225    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
7226    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
7227    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
7228    /// accessor. Every downstream consumer that reaches for a policy
7229    /// axis first passes through this outer accessor onto the composite
7230    /// and then dispatches onto the per-axis accessor — the two-level
7231    /// dispatch means every per-`:politicas` reader now routes through
7232    /// a typed dispatch on the substrate primitive at both altitudes.
7233    ///
7234    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
7235    /// accessed inline at four production sites — the
7236    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
7237    /// &self.politicas;` traversal seed (which drives every per-axis
7238    /// zero-floor + upper-cap + canonical-form bracket dispatch through
7239    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
7240    /// `p.rate_limit()` on the axis-level lifted accessors), the
7241    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
7242    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
7243    /// chain (which drives every per-`(:de, :para)` CNP
7244    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
7245    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
7246    /// timeout + retry overlay emitter's paired
7247    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
7248    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
7249    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
7250    /// open-coded outer-field accesses that expressed no compile-time
7251    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
7252    /// future extension of the `:politicas` outer axis to a richer
7253    /// author surface (a per-cluster policy overlay the operator pins
7254    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
7255    /// §V federation roadmap acknowledges, a per-tenant policy-alias
7256    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7257    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7258    /// policy-composite derivation the future adaptive-placement engine
7259    /// computes from a per-cluster load-topology reader, a promotion of
7260    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
7261    /// partition once virtual-actor-style dynamic-mesh-policy
7262    /// composition comes into typed scope) would have had to be threaded
7263    /// through all four open-coded copies in lockstep or one consumer
7264    /// would silently disagree with the peers on which mesh-policy
7265    /// composite a given Aplicacao resolves to — the validator's
7266    /// per-axis bracket-dispatch seed reading the raw slot while the
7267    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
7268    /// would silently split the build-time policy-shape gate from the
7269    /// runtime CNP-emission gate, a four-consumer split at the
7270    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
7271    /// the source `caixa.lisp` with no field naming the policy-drift
7272    /// root cause. Lifting the resolution rule to a typed method on the
7273    /// substrate primitive means every downstream consumer of the
7274    /// Aplicacao's per-`:politicas` mesh-policy composite surface
7275    /// reaches for exactly one typed dispatch — the resolver's accept-
7276    /// set migrates as a unit on any future axis addition.
7277    ///
7278    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
7279    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
7280    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7281    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
7282    /// close the two `Vec`-carry axes on the outer typed composition
7283    /// view; the outer `:politicas` composite-reference axis is the
7284    /// natural pair to the paired outer `Vec`-carry accessors on the
7285    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
7286    /// emitter reads all four axes as one unit (graph nodes + graph
7287    /// edges + mesh policy + placement pool). Peer to the same
7288    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
7289    /// slot: every M2 `SupervisorSpec`-scoped composite reader
7290    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
7291    /// `restart_window`, `children`) already routes through the M2
7292    /// `SupervisorSpec` accessor family — this lift extends the same
7293    /// "one typed dispatch on the substrate primitive at the outer
7294    /// composition altitude" discipline to the M3 mesh-slot
7295    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
7296    /// remaining peer outer-composite axes still unlifted at the time
7297    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
7298    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
7299    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
7300    /// inherit this accessor's discipline as future compounding runs
7301    /// migrate their consumers onto the shared reference-return shape.
7302    /// Named `politicas()` to match the storage field's name verbatim
7303    /// and the tatara-lisp author-surface term (`:politicas`) the
7304    /// field's own docstring already carries; the accessor's identity
7305    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
7306    /// slot's docstring already reaches for. Returns `&MeshPolicy`
7307    /// (not the owning composite by copy or clone) because every
7308    /// downstream consumer of the mesh-policy composite treats it as a
7309    /// read-only per-axis dispatch source — the reference-view is the
7310    /// narrowest borrow that supports every present + roadmapped
7311    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
7312    /// emptiness probe) without cloning the composite through every
7313    /// consumer's fast path.
7314    #[must_use]
7315    pub const fn politicas(&self) -> &MeshPolicy {
7316        &self.politicas
7317    }
7318
7319    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
7320    /// per-Aplicacao distribution-composite composite-reference accessor
7321    /// every per-Aplicacao placement-block reader keys off — returns the
7322    /// author-declared `:placement` composite verbatim as a `&Placement`
7323    /// reference over the same backing storage the raw `&self.placement`
7324    /// field access borrows from.
7325    ///
7326    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
7327    /// distribution composite — the load-bearing container of every
7328    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
7329    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
7330    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
7331    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
7332    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
7333    /// `:affinity` hint). Every per-`:placement` axis threads through a
7334    /// lifted per-slot accessor on the [`Placement`] type: the
7335    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
7336    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
7337    /// per-cluster distribution-target slice-return accessor, the
7338    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
7339    /// optional-scalar accessor, and the [`Placement::shard_key`]
7340    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
7341    /// downstream consumer that reaches for a placement axis first passes
7342    /// through this outer accessor onto the composite and then dispatches
7343    /// onto the per-axis accessor — the two-level dispatch means every
7344    /// per-`:placement` reader now routes through a typed dispatch on the
7345    /// substrate primitive at both altitudes.
7346    ///
7347    /// Prior to this lift the `.placement` `Placement` composite was
7348    /// accessed inline at three production sites — the
7349    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
7350    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
7351    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
7352    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
7353    /// cluster `.clusters()` validate-loop traversal head, the per-
7354    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
7355    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
7356    /// paired with the shape-gate cascade's `.shard_key()` /
7357    /// `.estrategia()` diagnostic-carry pair), the
7358    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
7359    /// per-entry placement-block emitter's outer
7360    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
7361    /// seed (which fans onto every per-cluster `programs[]` entry as a
7362    /// self-describing distribution overlay the aggregator filters by),
7363    /// and the `feira app graph` per-Aplicacao print line's paired
7364    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
7365    /// then-inner-accessor chains (which drive the human-readable
7366    /// distribution summary of the typed Aplicacao view) — three open-
7367    /// coded outer-field accesses that expressed no compile-time link
7368    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
7369    /// extension of the `:placement` outer axis to a richer author surface
7370    /// (a per-cluster placement overlay the operator pins through a
7371    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
7372    /// federation roadmap acknowledges, a per-tenant placement-alias
7373    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7374    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7375    /// placement-composite derivation the future M5 adaptive-placement
7376    /// engine computes from a per-cluster load-topology reader, a
7377    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
7378    /// partition once Orleans-style virtual-actor dynamic-placement comes
7379    /// into typed scope) would have had to be threaded through all three
7380    /// open-coded copies in lockstep or one consumer would silently
7381    /// disagree with the peers on which placement composite a given
7382    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
7383    /// seed reading the raw slot while the peer
7384    /// `programs_for_aplicacao` emitter read an operator-resolved slot
7385    /// would silently split the build-time distribution-shape gate from
7386    /// the runtime programs.yaml distribution-annotation gate, a three-
7387    /// consumer split at the validator, the programs.yaml emitter, and
7388    /// the `feira app graph` printer far from the source `caixa.lisp`
7389    /// with no field naming the placement-drift root cause. Lifting the
7390    /// resolution rule to a typed method on the substrate primitive
7391    /// means every downstream consumer of the Aplicacao's per-
7392    /// `:placement` distribution composite surface reaches for exactly
7393    /// one typed dispatch — the resolver's accept-set migrates as a unit
7394    /// on any future axis addition.
7395    ///
7396    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
7397    /// `AplicacaoSpec` type itself — sibling to the seed
7398    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
7399    /// composite-reference accessor on the peer per-`:politicas` outer-
7400    /// composite axis, and to the paired slice-return accessors
7401    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7402    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
7403    /// the two `Vec`-carry axes on the outer typed composition view; the
7404    /// outer `:placement` composite-reference axis is the natural pair
7405    /// to the peer `:politicas` composite-reference axis on the two
7406    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
7407    /// how-to-run policy overlay, `:placement` carries the where-to-run
7408    /// distribution composite — every whole-Aplicacao mesh-artifact
7409    /// emitter reads both as one unit). Same "one typed dispatch on the
7410    /// substrate primitive, thin projections at each consumer"
7411    /// discipline the peer per-`:politicas` composite-reference axis
7412    /// already routes through. The one remaining outer-composite axis
7413    /// still unlifted at the time of this lift —
7414    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
7415    /// external-gateway composite) — inherits this accessor's discipline
7416    /// as the next compounding run migrates its consumers onto the shared
7417    /// reference-return shape, closing the outer-composite altitude on
7418    /// every M3 mesh-slot axis. Named `placement()` to match the storage
7419    /// field's name verbatim and the tatara-lisp author-surface term
7420    /// (`:placement`) the field's own docstring already carries; the
7421    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
7422    /// vocabulary the slot's docstring already reaches for. Returns
7423    /// `&Placement` (not the owning composite by copy or clone) because
7424    /// every downstream consumer of the placement composite treats it as
7425    /// a read-only per-axis dispatch source — the reference-view is the
7426    /// narrowest borrow that supports every present + roadmapped consumer
7427    /// (per-axis accessor dispatch, serde composite-serialization) without
7428    /// cloning the composite through every consumer's fast path.
7429    #[must_use]
7430    pub const fn placement(&self) -> &Placement {
7431        &self.placement
7432    }
7433
7434    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
7435    /// per-Aplicacao external-gateway composite optional-composite-
7436    /// reference accessor every per-Aplicacao gateway-block reader
7437    /// keys off — returns the author-declared `:entrada` composite
7438    /// verbatim as an `Option<&Entrada>` reference over the same
7439    /// backing storage the raw `self.entrada.as_ref()` field access
7440    /// borrows from, with `None` naming the internal-only mesh shape
7441    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
7442    /// gateway_routes emitter treats as "emit nothing" and the peer
7443    /// `feira app graph` printer treats as "internal-only mesh").
7444    ///
7445    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
7446    /// external-gateway composite — the load-bearing container of
7447    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
7448    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
7449    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
7450    /// hostname axis, §III.4 for the `:para` destination-Servico
7451    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
7452    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
7453    /// axis threads through a lifted per-slot accessor on the
7454    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
7455    /// Gateway-API `Listener.hostname` scalar accessor, the paired
7456    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
7457    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
7458    /// backendRefs destination-Servico scalar accessor, the
7459    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
7460    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
7461    /// scalar accessor. Every downstream consumer that reaches for
7462    /// an entrada axis first passes through this outer accessor onto
7463    /// the composite and then dispatches onto the per-axis accessor
7464    /// — the two-level dispatch means every per-`:entrada` reader
7465    /// now routes through a typed dispatch on the substrate primitive
7466    /// at both altitudes.
7467    ///
7468    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
7469    /// was accessed inline at four production sites — the
7470    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
7471    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
7472    /// (which drives every per-axis refusal on the composite: the
7473    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
7474    /// `EntradaMemberMissing` membership lookup against the
7475    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
7476    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
7477    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
7478    /// per-path shape gate on each entry of `e.paths`), the
7479    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
7480    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
7481    /// composite-projection seed (which drives the destination-
7482    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
7483    /// backendRefs port emitter fans on), the
7484    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
7485    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
7486    /// early-return seed (which drives the "no `:entrada` ⇒ no
7487    /// external artifacts" partition on the whole-Aplicacao Gateway-
7488    /// API emitter's fan-out), and the `feira app graph` per-
7489    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
7490    /// external-gateway summary emitter (which drives the human-
7491    /// readable `entrada: host → para (paths=…, port=…)` /
7492    /// `entrada: (internal-only mesh)` partition on the typed
7493    /// Aplicacao view) — four open-coded outer-field accesses that
7494    /// expressed no compile-time link back to the typed slot at the
7495    /// [`AplicacaoSpec`] altitude. A future extension of the
7496    /// `:entrada` outer axis to a richer author surface (a
7497    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
7498    /// at admission time so an Aplicacao can expose a public-web +
7499    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
7500    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
7501    /// operator can pin a per-cluster hostname override without
7502    /// re-authoring the `caixa.lisp`, a promotion of the plain
7503    /// `Option<Entrada>` to a richer `{single, multi}` partition once
7504    /// the multi-`:entrada` roadmap lands) would have had to be
7505    /// threaded through all four open-coded copies in lockstep or one
7506    /// consumer would silently disagree with the peers on which
7507    /// entrada composite a given Aplicacao resolves to — the
7508    /// validator's per-axis bracket-dispatch seed reading the raw
7509    /// slot while the peer `gateway_routes` emitter read an
7510    /// operator-resolved slot would silently split the build-time
7511    /// gateway-shape gate from the runtime Gateway + HTTPRoute
7512    /// emission gate, a four-consumer split at the validator, the
7513    /// `port_for_destination` L4-port resolver, the `gateway_routes`
7514    /// emitter, and the `feira app graph` printer far from the
7515    /// source `caixa.lisp` with no field naming the entrada-drift
7516    /// root cause. Lifting the resolution rule to a typed method on
7517    /// the substrate primitive means every downstream consumer of
7518    /// the Aplicacao's per-`:entrada` external-gateway composite
7519    /// surface reaches for exactly one typed dispatch — the
7520    /// resolver's accept-set migrates as a unit on any future axis
7521    /// addition.
7522    ///
7523    /// Third and final `&Composite`-return accessor on the top-level
7524    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
7525    /// unlifted outer-composite axis on the outer typed composition
7526    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
7527    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
7528    /// accessor on the per-`:politicas` outer-composite axis and to
7529    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
7530    /// distribution-composite composite-reference accessor on the
7531    /// per-`:placement` outer-composite axis; extends the outer-
7532    /// composite reference-return discipline the two peers already
7533    /// route through onto the last unlifted per-`AplicacaoSpec`
7534    /// outer-composite axis. The `:entrada` outer-composite axis is
7535    /// the natural pair to the two peer outer-composite axes on the
7536    /// three operationally-symmetric M3 mesh-slot outer composites
7537    /// (`:politicas` carries the how-to-run policy overlay,
7538    /// `:placement` carries the where-to-run distribution composite,
7539    /// `:entrada` carries the who-can-reach-it external-gateway
7540    /// composite — every whole-Aplicacao mesh-artifact emitter reads
7541    /// all three as one unit). Same "one typed dispatch on the
7542    /// substrate primitive, thin projections at each consumer"
7543    /// discipline the peer outer-composite axes already route through.
7544    /// Named `entrada()` to match the storage field's name verbatim
7545    /// and the tatara-lisp author-surface term (`:entrada`) the
7546    /// field's own docstring already carries; the accessor's
7547    /// identity maps onto the canonical MESH-COMPOSITION §III.4
7548    /// vocabulary the slot's docstring already reaches for. Returns
7549    /// `Option<&Entrada>` (not the owning composite by copy or
7550    /// clone) because every downstream consumer of the entrada
7551    /// composite treats it as a read-only per-axis dispatch source
7552    /// — the reference-view is the narrowest borrow that supports
7553    /// every present + roadmapped consumer (per-axis accessor
7554    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
7555    /// port-fallback projection, early-return partition on the
7556    /// `None` arm) without cloning the composite through every
7557    /// consumer's fast path. The `Option` half of the return-type
7558    /// preserves the load-bearing "author-omitted `:entrada` ⇒
7559    /// internal-only mesh" partition (not a default composite the
7560    /// downstream must reject on emptiness) — the accessor projects
7561    /// the raw `Option<Entrada>` slot's presence bit through the
7562    /// reference-return unchanged.
7563    #[must_use]
7564    pub const fn entrada(&self) -> Option<&Entrada> {
7565        self.entrada.as_ref()
7566    }
7567
7568    /// Validate the typed shape:
7569    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
7570    ///     and a non-empty `:versao`; no two entries share the same
7571    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
7572    ///     not a multiset)
7573    ///   - every `:contratos` :de + :para must be in `:membros`
7574    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
7575    ///     contract is an inter-Servico edge, so a Servico contracting
7576    ///     with itself is a build error under every WIT shape
7577    ///     (MESH-COMPOSITION §III.1)
7578    ///   - no two `:contratos` entries agree on
7579    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
7580    ///     edges are a set, not a multiset (peer of the `:membros` /
7581    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
7582    ///   - `:entrada :para` must be in `:membros`
7583    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
7584    ///     `:placement Replicated`/`SingleNode` must NOT declare
7585    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
7586    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
7587    ///     between strategy and shard-key is symmetric: every validated
7588    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
7589    ///     Sharded`
7590    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
7591    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
7592    ///     the shard pool (MESH-COMPOSITION §III.1)
7593    ///   - every `:clusters` entry is non-empty and unique
7594    ///   - `:placement :affinity`, when set, is non-empty
7595    ///   - the synchronous-`:contratos` subgraph is acyclic
7596    ///     (MESH-COMPOSITION §III.3)
7597    ///   - every declared `:politicas` value is operationally meaningful
7598    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
7599    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
7600    ///     omit the field instead to express "no policy on this axis")
7601    pub fn validate(&self) -> Result<(), AplicacaoError> {
7602        self.validate_membros()?;
7603
7604        // `:contratos` per-slot gate — folds both structural axes on the
7605        // slot into one substrate primitive: the per-entry cascade (shape
7606        // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
7607        // target + whole-edge dedup) and the cross-edge sync-cycle axis
7608        // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
7609        // — pub-sub edges excluded, "acyclic by construction"). Same
7610        // fold-per-axis-plus-cross-axis discipline the sibling
7611        // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
7612        // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
7613        // onto `:contratos` so every future consumer of the slot (the M4
7614        // admission webhook re-checking `:contratos` after a per-edge
7615        // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
7616        // acknowledges) reaches *both* structural axes through one call.
7617        self.validate_contratos()?;
7618
7619        self.validate_entrada()?;
7620
7621        self.validate_placement()?;
7622
7623        self.validate_politicas()?;
7624
7625        Ok(())
7626    }
7627
7628    /// The `:membros` graph-node name set — the membership oracle every
7629    /// per-Aplicacao name-reference axis resolves against.
7630    ///
7631    /// Three per-Aplicacao axes carry a Servico-name *reference* rather
7632    /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
7633    /// :para`, and `:entrada :para`. Each must resolve to a declared
7634    /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
7635    /// the external gateway both address graph nodes, so a reference to
7636    /// a node the graph does not contain is a build error). All three
7637    /// resolve against *this* set, so the set's construction is the one
7638    /// shared substrate primitive underneath the whole reference-
7639    /// resolution surface.
7640    ///
7641    /// Lifted out of [`AplicacaoSpec::validate`]'s inline
7642    /// `self.membros().iter().map(Membro::nome).collect()` builder so
7643    /// the two per-slot gates that consume it — the per-`:contratos`
7644    /// membership arms still inline at `validate` and the lifted
7645    /// [`AplicacaoSpec::validate_entrada`] below — reach the same
7646    /// oracle through one dispatch rather than each open-coding the
7647    /// projection. Every future consumer on the same axis (the M4
7648    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7649    /// reference resolver, the per-`:contratos`-edge `:politicas`
7650    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
7651    /// resolves an edge's endpoints against the same membership set
7652    /// before it can key a per-edge policy off them) inherits the
7653    /// projection through the same call, so a future rebrand of the
7654    /// node-identity axis (a namespace-qualified member name the CR
7655    /// materializer applies per-CR, the `:membros :nome-suffix`
7656    /// overlay §III.2 acknowledges) lands at exactly one place rather
7657    /// than at every reference-resolution site in lockstep. Peer of
7658    /// the sibling per-slot substrate primitives
7659    /// [`MeshPolicy::validate`] (f03a154) and
7660    /// [`WitContract::identity`] on their own axes.
7661    fn membro_names(&self) -> std::collections::HashSet<&str> {
7662        self.membros().iter().map(Membro::nome).collect()
7663    }
7664
7665    /// Reject `:contratos` entries whose endpoints are malformed,
7666    /// reference a Servico outside the graph, self-loop, carry an
7667    /// empty `:wit` shape, duplicate a prior entry on the six-axis
7668    /// identity key, or close a synchronous-edge cycle in the
7669    /// resulting typed graph.
7670    ///
7671    /// The `:contratos` slot is the typed inter-Servico edge set
7672    /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
7673    /// edge whose `:de` / `:para` reference two distinct members and
7674    /// whose `:wit` picks the payload shape the paired L4/L7 renderer
7675    /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
7676    /// per-HTTP `HTTPRoute`) fans out on.
7677    ///
7678    /// Two structural axes on the slot are folded into this per-slot
7679    /// gate: the per-entry axis (six per-edge arms, listed below) and
7680    /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
7681    /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
7682    /// per-entry cascade). Same
7683    /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
7684    /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
7685    /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
7686    /// `:politicas` slot, extended here onto `:contratos`.
7687    ///
7688    /// Six per-entry axes are gated first, in the canonical
7689    /// edge-direction order the paired diagnostics already encode
7690    /// (per-arm value shape before graph-membership lookup; structural
7691    /// self-edge before payload-shape target dispatch; whole-edge dedup
7692    /// last):
7693    ///
7694    ///   - per-arm `:de` / `:para` value shape via
7695    ///     [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
7696    ///     `:de` before `:para`;
7697    ///   - per-edge graph-membership against the
7698    ///     [`AplicacaoSpec::membro_names`] oracle via
7699    ///     [`WitContract::require_endpoints_in`] (folds the twin
7700    ///     `:de` / `:para` arms onto one substrate-primitive
7701    ///     dispatch), `:de` before `:para`;
7702    ///   - structural self-edge via [`WitContract::is_self_loop`]
7703    ///     (caller-equals-callee under any WIT shape);
7704    ///   - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
7705    ///   - WIT shape ↔ target consistency via [`WitContract::target`]
7706    ///     (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
7707    ///     `Capability` — each carry their own required payload field);
7708    ///   - six-axis whole-edge dedup via [`WitContract::identity`]
7709    ///     ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
7710    ///     slot)` tuple).
7711    ///
7712    /// One cross-edge axis is gated last, after the per-entry cascade
7713    /// completes cleanly:
7714    ///
7715    ///   - synchronous-edge cycle detection via
7716    ///     [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
7717    ///     three-coloring over the sync-only subgraph, pub-sub edges
7718    ///     skipped per MESH-COMPOSITION §III.3 —
7719    ///     [`AplicacaoError::ContratoCycle`]). Runs *after* the
7720    ///     per-entry cascade so a per-entry defect surfaces through its
7721    ///     narrower shape/membership/dedup arm before the cross-edge
7722    ///     cycle diagnostic, matching the pre-fold `validate`-side
7723    ///     dispatch ordering (`validate_contratos()? →
7724    ///     detect_sync_cycles()?`).
7725    ///
7726    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
7727    /// seen_contracts = …; for c in self.contratos() { … }` block onto
7728    /// a named per-slot gate, closing the last unlifted per-slot gate
7729    /// on the M3 mesh-slot family. Every peer slot already carries the
7730    /// shape ([`AplicacaoSpec::validate_membros`],
7731    /// [`AplicacaoSpec::validate_entrada`],
7732    /// [`AplicacaoSpec::validate_placement`],
7733    /// [`AplicacaoSpec::validate_politicas`]).
7734    ///
7735    /// Self-contained on `&self` — it resolves its own membership
7736    /// oracle through [`AplicacaoSpec::membro_names`] rather than
7737    /// borrowing one threaded down from `validate`, and runs its own
7738    /// cross-edge cycle probe rather than deferring the axis to an
7739    /// outer dispatch — so a future consumer that re-validates *one*
7740    /// slot against a mutated spec (the M4 admission webhook
7741    /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
7742    /// without re-walking `:membros` / `:entrada` / `:placement` /
7743    /// `:politicas`, or the M4 per-edge policy resolver
7744    /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
7745    /// effective per-edge [`MeshPolicy`] and must re-check the edge's
7746    /// own identity closure *and* the sync-cycle invariant before it
7747    /// can key a per-edge override off the endpoint tuple) reaches
7748    /// *both* structural axes on the slot through one call, exactly as
7749    /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
7750    /// cross-axis surfaces on `:politicas` through
7751    /// [`MeshPolicy::validate`].
7752    fn validate_contratos(&self) -> Result<(), AplicacaoError> {
7753        let names = self.membro_names();
7754
7755        // Identity key for the typed-edge duplicate gate below: every
7756        // field that distinguishes one contract from another. Two
7757        // entries that agree on all six are *the same edge declared
7758        // twice*, the typed-graph analogue of duplicate `:membros` /
7759        // `:placement :clusters` / `:entrada :paths` entries (which
7760        // are already build errors at this layer). Rejecting it at the
7761        // validate gate closes a renderer-side footgun: caixa-mesh's
7762        // `cilium_network_policies` keys each emitted policy by
7763        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
7764        // (de, para) and identical payload would land as two K8s
7765        // objects with colliding `metadata.name`, rejected at apply
7766        // time far from the source caixa.lisp.
7767        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
7768            std::collections::HashSet::new();
7769        for c in self.contratos() {
7770            // Per-axis value-shape gate on every `:contratos` name
7771            // reference, before any graph-membership lookup. Empty +
7772            // DNS-1123-malformed `:de`/`:para` values silently fell
7773            // through to `ContratoMemberMissing` at the lookup arm
7774            // because every `:membros :caixa` is shape-validated
7775            // (3f9d7a0), so the `names` set structurally cannot contain
7776            // an empty / malformed string and the membership-lookup
7777            // diagnostic always misframed the root cause as
7778            // "this caixa is not in `:membros`". The shape gate runs
7779            // ahead of the lookup so structurally-impossible-to-match
7780            // inputs route through the narrower self-locating
7781            // diagnostic, preserving the legitimate "well-shaped
7782            // phantom reference" arm. `:de` runs before `:para` per
7783            // the canonical edge-direction order the existing
7784            // membership lookup, self-edge check, target dispatch,
7785            // and diagnostic strings already use.
7786            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7787            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7788            // Per-edge graph-membership gate on the twin `:de` / `:para`
7789            // arms — folded onto the substrate-primitive dispatch
7790            // [`WitContract::require_endpoints_in`] so every per-edge
7791            // consumer of the endpoint-resolution axis (this per-slot
7792            // gate at build time, the M4 admission webhook re-checking
7793            // one edge after a per-`(:de, :para)` patch, the per-edge
7794            // `:politicas` override MESH-COMPOSITION §III.2 #3
7795            // acknowledges) reaches the axis through one call rather
7796            // than re-inlining the twin `if !names.contains(...)`
7797            // cascade. `:de` fires before `:para` inside the primitive,
7798            // preserving byte-equal diagnostic ordering with the
7799            // pre-lift inline cascade.
7800            c.require_endpoints_in(&names)?;
7801            // A `:contratos` entry is an *inter*-Servico contract
7802            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7803            // typed edge between two distinct graph nodes. An edge whose
7804            // `:de` equals its `:para` is a Servico contracting with
7805            // itself — a degenerate edge under every WIT shape. Firing
7806            // the gate before the `:wit`/`target()` shape checks means
7807            // the structural "this edge can't exist" error precedes the
7808            // narrower payload-shape diagnostics, and shape-agnostically
7809            // covers all four `WitTarget` arms (HTTP / Store / Capability
7810            // / PubSub) at one point. Peer of the duplicate-`:contratos`
7811            // / duplicate-`:membros` set gates: both reject a structurally
7812            // ill-formed graph at the typed surface, before the renderer
7813            // emits a K8s object that fails or no-ops far from the source
7814            // caixa.lisp.
7815            if c.is_self_loop() {
7816                return Err(AplicacaoError::contrato_self_loop(c));
7817            }
7818            if c.world_ref().is_empty() {
7819                return Err(AplicacaoError::empty_wit(c.edge_pair()));
7820            }
7821            // Shape ↔ target consistency — surfaces "HTTP wit without
7822            // :endpoint", "NATS wit with :endpoint set", etc. as named
7823            // build errors instead of silent renderer drops. Threaded
7824            // through the duplicate-edge diagnostic below (via
7825            // [`WitTarget::label`]) so the "which typed target arm did
7826            // the duplicate carry" question is answered by the typed
7827            // enum's variant discriminator, not by re-probing the raw
7828            // `Option<String>` payload fields.
7829            let target_view = c.target()?;
7830            // Contract identity: (de, para, wit, endpoint, subject, slot).
7831            // Two contracts that match on all six are the same typed edge
7832            // declared twice — author error, not a legitimate variant of
7833            // "same caller-callee pair, different payload" (e.g.
7834            // cart→catalog at /products vs /search), which keeps distinct
7835            // identity keys via the differing endpoint payloads.
7836            let key = c.identity();
7837            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7838                let (de, para, wit) = c.edge_triple();
7839                AplicacaoError::ContratoDuplicate {
7840                    de,
7841                    para,
7842                    wit,
7843                    target: target_view.label(),
7844                }
7845            })?;
7846        }
7847
7848        // Cross-edge cycle axis on the `:contratos` slot — folded into
7849        // the per-slot gate so the two structural axes on `:contratos`
7850        // (per-entry shape + membership + dedup above; cross-edge sync-
7851        // cycle detection here) reach every consumer through one call.
7852        // Same discipline the sibling per-slot compound gate
7853        // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
7854        // — one named per-slot gate that folds *both* per-axis and
7855        // cross-axis surfaces on the same slot onto one substrate
7856        // primitive — extended here onto `:contratos`, closing the last
7857        // per-slot-axis-family that lived split across `validate` (the
7858        // per-entry `validate_contratos` half here and the cross-edge
7859        // `detect_sync_cycles` call the sibling below at `validate`
7860        // dispatched separately).
7861        //
7862        // Runs after the per-entry cascade so a per-entry defect (empty
7863        // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
7864        // target inconsistency, whole-edge duplicate) surfaces first
7865        // through its narrower [`AplicacaoError`] arm before the cross-
7866        // edge cycle diagnostic. This matches the pre-lift ordering the
7867        // `validate`-side dispatch used verbatim (`self.validate_contratos()?
7868        // → self.detect_sync_cycles()?`) — the cycle detector was
7869        // already the second `:contratos`-axis gate in the dispatch,
7870        // just at the outer altitude; the fold moves it under the same
7871        // named per-slot gate without reshaping the diagnostic order.
7872        self.detect_sync_cycles()?;
7873
7874        Ok(())
7875    }
7876
7877    /// Reject `:entrada` values that are operationally meaningless,
7878    /// structurally malformed, or reference a Servico outside the
7879    /// graph.
7880    ///
7881    /// The `:entrada` slot is the Aplicacao's single external ingress
7882    /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
7883    /// Gateway API v1 `Listener`, `:paths` become the paired
7884    /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
7885    /// the member the route forwards to. Omitting the slot entirely is
7886    /// the internal-only-mesh partition — an Aplicacao with no external
7887    /// surface — so the `None` arm is a clean pass, not a refusal.
7888    ///
7889    /// Five axes are gated here, in the canonical order the paired
7890    /// diagnostics already encode (reference-resolution before value
7891    /// shape, per-axis emptiness before per-axis grammar):
7892    ///
7893    ///   - `:para` — DNS-1123 value shape, then membership against the
7894    ///     [`AplicacaoSpec::membro_names`] oracle;
7895    ///   - `:host` — emptiness, then the Gateway API hostname grammar;
7896    ///   - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
7897    ///   - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
7898    ///     path grammar, and set-not-multiset uniqueness.
7899    ///
7900    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
7901    /// Some(e) = self.entrada() { … }` block onto a named per-slot
7902    /// gate, the shape the three peer M3 mesh slots already carry
7903    /// ([`AplicacaoSpec::validate_membros`],
7904    /// [`AplicacaoSpec::validate_placement`],
7905    /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
7906    /// `&self` — it resolves its own membership oracle through
7907    /// [`AplicacaoSpec::membro_names`] rather than borrowing one
7908    /// threaded down from `validate` — so a future consumer that
7909    /// re-validates *one* slot against a mutated spec (the M4 admission
7910    /// webhook re-checking `:entrada` after a gateway-host patch
7911    /// without re-walking the whole `:contratos` graph) reaches the
7912    /// axis through one call, exactly as `detect_sync_cycles` is
7913    /// already self-contained for the M4 per-edge policy resolver.
7914    fn validate_entrada(&self) -> Result<(), AplicacaoError> {
7915        let names = self.membro_names();
7916        if let Some(e) = self.entrada() {
7917            // Route the per-`:entrada` composite-reference read
7918            // through the lifted [`AplicacaoSpec::entrada`] accessor
7919            // rather than the raw `&self.entrada` field access — the
7920            // shape-and-membership gate's traversal head is now the
7921            // canonical read-side surface every per-Aplicacao entrada
7922            // consumer routes through, closing the fourth of four
7923            // open-coded outer-field accesses on the per-`:entrada`
7924            // outer-composite axis.
7925            //
7926            // Shape gate on `:entrada :para` runs ahead of the
7927            // membership lookup. Every `:membros :caixa` past
7928            // `validate_membro_caixa` is a valid DNS-1123 label
7929            // (3f9d7a0), so the `names` set structurally cannot
7930            // contain an empty / malformed string and the membership-
7931            // lookup diagnostic always misframed the root cause as
7932            // "this caixa is not in `:membros`". The shape gate
7933            // routes structurally-impossible-to-match inputs through
7934            // the narrower self-locating diagnostic, preserving the
7935            // legitimate "well-shaped phantom reference" arm — the
7936            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7937            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7938            // / `:para` (8d5af6b) axes already follow. This closes
7939            // the fourth and last Aplicacao-level Servico-name
7940            // reference axis on the canonical DNS-1123 floor.
7941            // Route the per-`:entrada :para` byte-string reads through
7942            // the lifted [`Entrada::destination`] accessor rather than
7943            // the raw `e.para` field access — the three
7944            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7945            // (shape-gate `validate_entrada_para` arg, membership
7946            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7947            // off exactly one typed dispatch on the substrate
7948            // primitive, closing the last unlifted per-`:entrada :para`
7949            // raw-field-access axis on the M3 mesh-slot validator.
7950            // The `.destination().to_string()` at the diagnostic site
7951            // is byte-identical to `.para.clone()` — pinned by the
7952            // sibling `destination_returns_entrada_para_byte_equal` +
7953            // `destination_borrows_from_entrada_para_storage` accessor
7954            // tests — so a future rebrand of the underlying `:para`
7955            // storage (a lift from `String` to a typed
7956            // `ServicoName(String)` newtype, a per-Aplicacao interning
7957            // arena the M4 CR materializer authors, a
7958            // `smol_str::SmolStr` inline-buffer swap) flows through
7959            // the accessor's one body without a coordinated
7960            // per-consumer rewrite across the M3 mesh validator.
7961            validate_entrada_para(e.destination())?;
7962            if !names.contains(e.destination()) {
7963                return Err(AplicacaoError::entrada_member_missing(e));
7964            }
7965            // Route the per-`:entrada :host` byte-string reads through
7966            // the lifted [`Entrada::hostname`] accessor rather than
7967            // the raw `e.host` field access — the emptiness gate and
7968            // the shape-gate `validate_entrada_host` arg now key off
7969            // exactly one typed dispatch on the substrate primitive,
7970            // closing the last unlifted per-`:entrada :host` raw-
7971            // field-access axis on the M3 mesh-slot validator. Peer
7972            // of the sibling per-`:entrada :para` convergence above
7973            // and pinned by the existing
7974            // `hostname_returns_entrada_host_byte_equal` +
7975            // `hostnames_returns_singleton_of_hostname_accessor`
7976            // accessor tests, so any future
7977            // Gateway-API-shaped host renormalization (a wildcard-
7978            // label lift, a trailing-`.` FQDN substitution, an IDNA
7979            // Punycode round-trip the SNI fan-out overlay authors)
7980            // flows through the accessor's one body without a
7981            // coordinated per-consumer rewrite across the M3 mesh
7982            // validator.
7983            if e.hostname().is_empty() {
7984                return Err(AplicacaoError::EmptyEntradaHost);
7985            }
7986            // The `:host` lands verbatim as a K8s Gateway API v1
7987            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7988            // both apiserver-validated against the same restrictive
7989            // pattern: lowercase RFC 1123 DNS subdomain, optional
7990            // single leading wildcard label (`*.`), max length 253,
7991            // per-label max length 63, no IP literals, no scheme,
7992            // no port. Until this gate landed `validate()` only
7993            // refused the empty string (`EmptyEntradaHost`); a
7994            // structurally invalid hostname (`"https://example.com"`,
7995            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7996            // `"_underscored.example.com"`, `"FOO.example.com"`,
7997            // `"checkout.quero.cloud."`) silently passed validate
7998            // and the apiserver `field is invalid` error surfaced at
7999            // `kubectl apply` time, far from the source caixa.lisp.
8000            // Lifting the gate to caixa-build time mirrors the
8001            // `:entrada :paths` value-shape trajectory (eb3456d) and
8002            // closes the last unstructured `:entrada` axis.
8003            validate_entrada_host(e.hostname())?;
8004            // Structural-floor gate on `:entrada :port`: every
8005            // validated `Entrada::port` past this gate lies in
8006            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
8007            // type-inferred ceiling closes the top edge, so no companion
8008            // upper-cap arm is needed here — unlike the peer capped-
8009            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
8010            // `require_positive_bounded_u32` bracket covers both edges).
8011            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
8012            // accept-set-floor const rather than the prior inline
8013            // `if e.port == 0` byte-check so a future rebrand of the
8014            // accept-set floor (a hypothetical unprivileged-only
8015            // migration lifting the floor to `1024`, a per-cluster
8016            // scoping the operator pins through a future
8017            // `:placement :port-floor` slot as the M4 typed-slot
8018            // trajectory adds it, the future
8019            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8020            // per-Aplicacao gateway resolver reaching for the same
8021            // floor) is a one-line edit on the canonical
8022            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
8023            // rewrite across the emit site + the pin test + every
8024            // future per-target renderer the substrate adds.
8025            if e.port() < SERVICO_PORT_MIN {
8026                return Err(AplicacaoError::EntradaPortZero);
8027            }
8028            // Each `:entrada :paths` entry becomes a K8s Gateway API
8029            // HTTPRoute `matches[].path.value`. The Gateway API rejects
8030            // values that don't start with `/` for `type: PathPrefix`,
8031            // and an empty value is meaningless. Surface those as build
8032            // errors (MESH-COMPOSITION §III.3) rather than apply-time
8033            // failures. Empty `:paths` itself is fine — caixa-mesh
8034            // falls back to a single `/` catch-all.
8035            let mut seen = std::collections::HashSet::new();
8036            // Route the per-entry value-shape gate's traversal head
8037            // through the lifted [`Entrada::paths`] slice accessor
8038            // rather than the raw `&e.paths` field access — the
8039            // per-Aplicacao `:entrada :paths` validate loop now keys
8040            // off the canonical raw-slot surface every downstream
8041            // per-`:entrada` path-list consumer (the sibling
8042            // [`Entrada::resolved_paths`] fallback-applying resolver
8043            // internal reads, `feira app graph`'s per-Aplicacao entrada
8044            // summary line's `{:?}` Debug print) routes through, so any
8045            // future rebrand on the typed slot's raw-slot reader lands
8046            // at exactly one place. Same convergence discipline as the
8047            // sibling [`Placement::clusters`] (a6e18d7) reader-site
8048            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
8049            // axis.
8050            for p in e.paths() {
8051                if p.is_empty() {
8052                    return Err(AplicacaoError::EntradaPathEmpty);
8053                }
8054                if !p.starts_with('/') {
8055                    return Err(AplicacaoError::entrada_path_not_absolute(p));
8056                }
8057                // Per-entry value-shape gate: the path lands verbatim
8058                // as a K8s Gateway API HTTPRoute `matches[].path.value`
8059                // (caixa-mesh/src/lib.rs:498), apiserver-validated
8060                // against `maxLength: 1024` + the Gateway API webhook's
8061                // path-grammar rules (no `//`, no `/./`, no `/../`, no
8062                // query/fragment separators, no whitespace, no control
8063                // characters, no non-ASCII bytes). Until this gate
8064                // landed `validate` only refused the empty string and
8065                // missing-leading-slash (eb3456d); a structurally
8066                // invalid path (`"/api?q=1"`, `"/api#frag"`,
8067                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
8068                // 1025-byte URL-shaped slug) silently passed validate
8069                // and the failure surfaced at `kubectl apply` time as
8070                // a Gateway API webhook rejection, far from the source
8071                // caixa.lisp, with no field naming the offending
8072                // `:paths` entry. Lifting the gate to caixa-build time
8073                // mirrors the `:entrada :host` value-shape trajectory
8074                // (c7d05ec) on the sibling axis — every author surface
8075                // that emits a Gateway API field now matches the
8076                // apiserver's accepted set at validate time.
8077                validate_entrada_path(p)?;
8078                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
8079                    AplicacaoError::entrada_path_duplicate(p)
8080                })?;
8081            }
8082        }
8083
8084        Ok(())
8085    }
8086
8087    /// Reject `:membros` values that are operationally meaningless. The
8088    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
8089    /// every entry names a Servico that participates in the Aplicacao,
8090    /// and the rendered programs.yaml fan-out emits one entry per
8091    /// `:membros`. Three authoring footguns are closed here:
8092    ///
8093    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
8094    ///     a `programs:` entry whose `name:` is the empty string, which
8095    ///     downstream `lareira-fleet-programs` rejects at template time
8096    ///     with a non-localized error;
8097    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
8098    ///     an empty semver constraint, so the failure surfaces far from
8099    ///     the source caixa.lisp;
8100    ///   - duplicate `:caixa` names — two entries with the same name
8101    ///     produce duplicate programs.yaml entries (one silently
8102    ///     overwrites the other in the cluster's HelmRelease values), and
8103    ///     contract membership lookups against `:contratos` collapse the
8104    ///     two onto one node, masking authoring mistakes.
8105    ///
8106    /// Same value-shape discipline as `:placement :clusters` (where empty
8107    /// + duplicate cluster names are rejected) and `:entrada :paths`
8108    /// (where empty + duplicate path entries are rejected). Lifting these
8109    /// invariants to the typed surface mirrors the MESH-COMPOSITION
8110    /// §III.3 promise that the `:membros` set — the load-bearing identity
8111    /// of the application graph — is well-formed by construction.
8112    fn validate_membros(&self) -> Result<(), AplicacaoError> {
8113        if self.membros().is_empty() {
8114            return Err(AplicacaoError::NoMembros);
8115        }
8116        let mut seen = std::collections::HashSet::new();
8117        for m in self.membros() {
8118            // Every emitted cluster artifact's `metadata.name` derives
8119            // from a `:membros :caixa` value verbatim — the rendered
8120            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
8121            // the [`crate::LABEL_PROGRAM`] label value on every CNP
8122            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
8123            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
8124            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
8125            // `metadata.name` when the member is the `:entrada :para`
8126            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
8127            // schema enforces the DNS-1123 label rule on admission;
8128            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
8129            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
8130            // mistaken-identity slug) silently passes the prior empty-/
8131            // duplicate-only gate and the failure surfaces at `kubectl
8132            // apply` time as a `metadata.name: Invalid value` rejection,
8133            // far from the source caixa.lisp, with no field naming the
8134            // offending `:membros` entry. Lifting the gate to caixa-build
8135            // time mirrors the `:entrada :host` value-shape trajectory
8136            // (c7d05ec) on the peer axis — every author surface that
8137            // emits a K8s name now matches the apiserver's accepted set
8138            // at validate time.
8139            validate_membro_caixa(m.nome())?;
8140            // The author surface for `:versao` is the same Cargo-shaped
8141            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
8142            // `"*"`) every `:deps` entry carries — and the lacre pipeline
8143            // resolves both axes through the same
8144            // [`crate::version::parse_requirement`] entry-point. The
8145            // shared [`crate::render::require_valid_versao_requirement`]
8146            // helper brackets the empty-first + parse cascade both peer
8147            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
8148            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
8149            // route through, so drift between the three axes' accepted
8150            // requirement sets is structurally impossible and the parse-
8151            // side no-op the empty-first arm closes (semver's empty
8152            // parse yields an implicit `*`) lives in exactly one
8153            // predicate.
8154            crate::render::require_valid_versao_requirement(
8155                m.versao_requirement(),
8156                || AplicacaoError::membro_versao_empty(m.nome()),
8157                |reason| {
8158                    AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
8159                },
8160            )?;
8161            crate::render::insert_first_seen(&mut seen, m.nome(), || {
8162                AplicacaoError::membro_duplicate(m.nome())
8163            })?;
8164        }
8165        Ok(())
8166    }
8167
8168    /// Reject `:placement` values that are operationally meaningless or
8169    /// internally contradictory. Each strategy variant has the same
8170    /// invariants on `:clusters` (non-empty list, non-empty unique
8171    /// entries) — the §III.1 author surface is uniform on this axis,
8172    /// even though the *meaning* of the list differs by strategy
8173    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
8174    /// shard pool).
8175    ///
8176    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
8177    /// are the same authoring footgun closed for `:politicas` zero
8178    /// values and `:entrada` empty paths: the field is *declared* but
8179    /// carries no meaning, so downstream renderers either skip it
8180    /// silently (cluster-fanout drops the empty entry, no diagnostic)
8181    /// or apply it literally and fail at admission time. Lifting both
8182    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
8183    /// violation is a build error" promise.
8184    ///
8185    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
8186    /// is required exactly when `:estrategia Sharded` (hash-keyed
8187    /// distribution, Akka cluster-sharding convention, §II.4) and
8188    /// refused on `:estrategia Replicated`/`SingleNode` (where no
8189    /// hash-keyed routing axis consumes it). The partition closes the
8190    /// "I think I configured sharding" footgun where an author writes
8191    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
8192    /// the typed slot's value silently vanishes at the renderer layer
8193    /// — every validated `Placement` past this call satisfies
8194    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
8195    fn validate_placement(&self) -> Result<(), AplicacaoError> {
8196        // Every strategy needs at least one named cluster: `Replicated`
8197        // and `SingleNode` use the list as hosting/takeover candidates
8198        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
8199        // §II.1), while `Sharded` uses it as the shard pool
8200        // (Akka cluster-sharding convention — §II.4). An empty list is
8201        // meaningless under any of the three.
8202        //
8203        // Route the paired pre-flight `.is_empty()` refusal probe and
8204        // the per-cluster validate loop's traversal head through the
8205        // lifted [`Placement::clusters`] slice-return accessor rather
8206        // than the raw `self.placement.clusters` field access — the
8207        // two production consumers of the per-`:placement` cluster-
8208        // pool `Vec`-carry now key off exactly one typed dispatch on
8209        // the substrate primitive, so any future rebrand on the axis
8210        // (a per-tenant cluster-pool overlay the operator pins through
8211        // a future `:placement :clusters-overrides` slot, a per-
8212        // Aplicacao dynamic cluster-pool derivation the future M5
8213        // adaptive-placement engine computes from `:affinity` weights)
8214        // migrates as a single caixa-core edit rather than a
8215        // coordinated rewrite of the paired arms — sibling of the
8216        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
8217        // arm migration on the per-`:supervisor` static-child-list
8218        // `Vec`-carry axis.
8219        //
8220        // Route the per-`:placement` outer-composite reference read
8221        // through the lifted [`AplicacaoSpec::placement`] outer accessor
8222        // rather than the raw `&self.placement` field access — the
8223        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
8224        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
8225        // axis-level lifted accessor family) now routes through the
8226        // substrate-primitive typed dispatch at the outer composition
8227        // altitude, the same shape the peer caixa-mesh
8228        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
8229        // and the sibling `feira app graph` per-Aplicacao print line
8230        // now key off after this accessor lift.
8231        let p = self.placement();
8232        if p.clusters().is_empty() {
8233            // Route the per-`:placement` empty-clusters diagnostic
8234            // through the substrate-primitive
8235            // [`AplicacaoError::placement_without_clusters`] ctor rather
8236            // than the pre-lift three-line open-coded
8237            // `AplicacaoError::PlacementWithoutClusters { estrategia:
8238            // p.estrategia() }` struct-literal — folds the sole in-crate
8239            // wire-up on this variant onto one dispatch matching the
8240            // sibling per-`:placement :clusters` dedup /
8241            // per-`:contratos` self-edge / per-`:upgrade-from :from`
8242            // duplicate substrate-primitive-projection ctors on the
8243            // same `AplicacaoError` / `UpgradeError` envelopes.
8244            return Err(AplicacaoError::placement_without_clusters(p));
8245        }
8246        let mut seen = std::collections::HashSet::new();
8247        for c in p.clusters() {
8248            // Per-entry value-shape gate: the cluster name lands in
8249            // every K8s context / `lareira-fleet-programs` aggregator
8250            // filter / future M4 CR materializer's per-cluster axis
8251            // a validated `:clusters` entry passes through, each
8252            // enforcing the DNS-1123 label rule on admission. Same
8253            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
8254            // on the peer name axis — both axes' validated values
8255            // are guaranteed-accepted by the apiserver without
8256            // re-validation at any downstream renderer or admission
8257            // layer.
8258            validate_placement_cluster(c)?;
8259            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
8260                // Route the per-`:placement :clusters` dedup diagnostic
8261                // through the substrate-primitive
8262                // [`AplicacaoError::placement_cluster_duplicate`] ctor
8263                // rather than the pre-lift three-line open-coded
8264                // `AplicacaoError::PlacementClusterDuplicate { cluster:
8265                // c.clone() }` struct-literal — folds the sole in-crate
8266                // wire-up on this variant onto one dispatch matching the
8267                // sibling per-`:membros :caixa` / per-`:entrada :paths` /
8268                // per-`:politicas <scalar>` single-slot ctor families on
8269                // the same [`AplicacaoError`] envelope.
8270                AplicacaoError::placement_cluster_duplicate(c)
8271            })?;
8272        }
8273        // Route the per-`:placement :affinity` per-hint value-shape
8274        // gate through the typed [`Placement::affinity`] accessor rather
8275        // than the raw `&self.placement.affinity` field access — the
8276        // sole open-coded field-access site on the per-`:placement`
8277        // M3-Adaptive-compression-hint axis the accessor lift now owns.
8278        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
8279        // the accessor's `Option<&str>` return type;
8280        // [`validate_placement_affinity`]'s `&str` parameter accepts
8281        // the narrower borrow without a re-allocation, so the routing
8282        // change is byte-for-byte in the pass arm and remains
8283        // byte-for-byte in every failure diagnostic
8284        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
8285        // String` field is populated inside
8286        // [`validate_placement_affinity`] via the peer `.to_string()`
8287        // path on the same borrowed slice). Peer of the sibling
8288        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
8289        // routing through [`Placement::shard_key`] at the caixa-core
8290        // site above — extends the "read `:placement` optional-scalars
8291        // through the typed accessor" discipline to the second
8292        // `Option<String>`-shape slot on the M3 mesh-slot family.
8293        //
8294        // Per-hint value-shape gate: the `:affinity` value lands
8295        // verbatim in the M3 Adaptive compression overlay
8296        // (caixa-mesh's `placement.affinity` emission) and every
8297        // future M4 placement-engine routing axis keying off the
8298        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
8299        // selector — each enforces the DNS-1123 label rule on
8300        // admission. Same typed-shape trajectory as `:placement
8301        // :clusters` (6c8c00b) on the sibling slot and the four
8302        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
8303        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
8304        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
8305        // on the Aplicacao surface to land on the canonical
8306        // [`crate::render::is_dns_1123_label`] floor.
8307        if let Some(a) = p.affinity() {
8308            validate_placement_affinity(a)?;
8309        }
8310        match p.estrategia() {
8311            // Route the `Sharded`-arm shape-gate cascade through the
8312            // typed [`Placement::shard_key`] accessor rather than the
8313            // raw `&self.placement.shard_key` field access — one of the
8314            // two open-coded field-access sites on the per-`:placement`
8315            // Akka-cluster-sharding-key axis the accessor lift now
8316            // owns. The `Some(k)`-bound `k` narrows from `&String` to
8317            // `&str` under the accessor's `Option<&str>` return type;
8318            // `str::is_empty` and [`validate_placement_shard_key`]'s
8319            // `&str` parameter both accept the narrower borrow without
8320            // a re-allocation.
8321            PlacementStrategy::Sharded => match p.shard_key() {
8322                None => return Err(AplicacaoError::ShardedWithoutKey),
8323                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
8324                // Per-axis value-shape gate on the Akka-cluster-sharding
8325                // `:shard-key` extractor expression. The shape gate runs
8326                // after the more self-locating `ShardedKeyEmpty` arm so
8327                // a `:shard-key ""` surfaces the narrower empty
8328                // diagnostic first; every non-empty `:shard-key` past
8329                // this call is guaranteed to be a printable-ASCII
8330                // single-token reference the future M4 Akka-style
8331                // cluster-sharding reconciler can hash without
8332                // re-validating at the runtime layer. Mirrors the
8333                // payload-axis shape gates on the peer `:contratos`
8334                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
8335                // 63e18a0 / c4213a4) — each lifts the runtime parser's
8336                // intersection-floor to a caixa-build-time gate.
8337                Some(k) => validate_placement_shard_key(k)?,
8338            },
8339            // `:shard-key` is the Akka-cluster-sharding axis
8340            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
8341            // across the cluster pool. `Replicated` (active-active across
8342            // every named cluster) and `SingleNode` (Erlang/OTP
8343            // distributed-app takeover/failover, §II.1) have no hash-keyed
8344            // routing axis to consume the slot; downstream renderers
8345            // (caixa-mesh's `placement.shardKey` overlay at
8346            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
8347            // sharding reconciler) ignore `:shard-key` outside the
8348            // `Sharded` arm by construction. Until this gate landed an
8349            // author who wrote `:placement (:estrategia Replicated
8350            // :shard-key "tenantId")` (an off-by-one strategy typo, a
8351            // copy-paste from a Sharded sibling caixa, the "I think I
8352            // configured sharding" footgun) silently passed validate and
8353            // the typed slot's value vanished at the renderer layer with
8354            // no diagnostic — the canonical "declared-but-inert" footgun
8355            // the empty-:affinity / empty-shard-key / zero-:politicas /
8356            // empty-:contratos-target gates already close on every other
8357            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
8358            // Lifting the rejection to a build-time gate closes the
8359            // Sharded ↔ non-Sharded partition over the typed
8360            // `:placement` slot: every validated `Placement` past this
8361            // call has `shard_key.is_some()` iff `estrategia ==
8362            // Sharded`, structurally — the future Akka reconciler can
8363            // reach for `placement.shard_key` knowing it's `Some` exactly
8364            // when the strategy consumes it, without re-deriving the
8365            // partition from inline strategy probes.
8366            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
8367                // Route the non-`Sharded`-arm declared-but-inert refusal
8368                // through the typed [`Placement::shard_key`] accessor —
8369                // the second of the two open-coded field-access sites the
8370                // accessor lift now owns. The `Some(k)`-bound `k` narrows
8371                // from `&String` to `&str`; the `AplicacaoError::
8372                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
8373                // materializes the owned `String` via `k.to_string()`
8374                // (peer to the sibling per-Membro `String`-carry sites
8375                // 4127bb6 routed through `m.nome().to_string()` /
8376                // `m.versao_requirement().to_string()`), so the whole
8377                // `Sharded` ↔ non-`Sharded` partition on the
8378                // `:shard-key` axis now flows through the same typed
8379                // dispatch as the sibling `Sharded`-arm shape gate.
8380                if let Some(k) = p.shard_key() {
8381                    return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
8382                }
8383            }
8384        }
8385        Ok(())
8386    }
8387
8388    /// Reject `:politicas` values that are operationally meaningless.
8389    /// Each axis is optional — omitting it expresses "no policy on this
8390    /// axis". Carrying a *zero* value for a declared axis is the bug
8391    /// this function rejects: zero is either
8392    ///
8393    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
8394    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
8395    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
8396    ///     "every Aplicacao declares :politicas :timeout (no infinite
8397    ///     blocking)", or
8398    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
8399    ///     first call; a 0-rate rate-limit denies every request).
8400    ///
8401    /// Lifting these "0 means the opposite of what you think" idioms to
8402    /// the typed Aplicacao surface as build errors mirrors the §III.3
8403    /// promise that contract drift, capability leaks, and cycles are all
8404    /// build errors — not runtime surprises.
8405    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
8406        // Route the whole per-axis + cross-axis `:politicas` cascade
8407        // through the substrate primitive [`MeshPolicy::validate`],
8408        // which folds all six per-axis brackets (`:timeout`,
8409        // `:retries`, `:circuit-breaker :max-failures`,
8410        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
8411        // window-canonical-form) plus the compound cross-axis fold
8412        // [`MeshPolicy::first_cross_axis_violation`] into one
8413        // `Result<(), AplicacaoError>` return. The whole per-axis-
8414        // brackets + cross-axis-fold cascade collapses to one call, and
8415        // every future [`MeshPolicy`] consumer (the future M4
8416        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8417        // admission webhook, the per-`:contratos`-edge `:politicas`
8418        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
8419        // of which resolves an *effective* per-edge [`MeshPolicy`] and
8420        // must emit *the same* diagnostic on the same input as `feira
8421        // build`) reaches through the same substrate-primitive dispatch
8422        // rather than re-inlining the four-per-axis + one-cross-axis
8423        // cascade in lockstep with this validate gate. Same trajectory
8424        // the peer per-kind compound entry gates
8425        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
8426        // [`crate::render::require_supervisor_view`] (8d8a5c3),
8427        // [`crate::render::require_v0_servico_shape`] (per-Caixa
8428        // layout axis) and the sibling compound cross-axis fold
8429        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
8430        // extended here onto the per-slot compound entry gate that
8431        // folds both per-axis + cross-axis surfaces on the M3
8432        // mesh-slot family.
8433        self.politicas().validate()
8434    }
8435
8436    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8437    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8438    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8439    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8440    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8441    /// block on its subscribers, so they can never close a sync loop.
8442    ///
8443    /// Iterative DFS with three-coloring; the reported cycle is the
8444    /// path of caixa names traversed from the back-edge target around
8445    /// to itself, in declaration order. Adjacency lists and DFS roots
8446    /// are visited in `BTreeMap` key order so the diagnostic is
8447    /// deterministic across runs.
8448    ///
8449    /// Now the cross-edge axis of the per-slot compound gate
8450    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
8451    /// the per-entry cascade rather than at the outer
8452    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
8453    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
8454    /// sync-cycle) reach every consumer through one call. Kept
8455    /// standalone (rather than inlined) so consumers that want only the
8456    /// cross-edge axis (the M4 per-edge policy resolver
8457    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
8458    /// mutates one `:contratos` entry and needs to re-probe *just* the
8459    /// cycle invariant against the post-patch adjacency without
8460    /// re-running the per-entry shape/membership/dedup cascade the
8461    /// per-entry-only [M4 admission] fast path already covered) still
8462    /// have a self-contained entry point on the cycle axis.
8463    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8464        use std::collections::{BTreeMap, BTreeSet};
8465
8466        #[derive(Clone, Copy, PartialEq, Eq)]
8467        enum Mark {
8468            White,
8469            Gray,
8470            Black,
8471        }
8472
8473        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8474        for m in self.membros() {
8475            adj.entry(m.nome()).or_default();
8476        }
8477        for c in self.contratos() {
8478            // target() was already called by validate(); re-running here
8479            // keeps detect_sync_cycles self-contained for callers that
8480            // reuse it (M4 per-edge policy resolver) without revalidating.
8481            //
8482            // The pub-sub-arm check routes through the lifted
8483            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8484            // arm-discriminator predicate rather than a raw `matches!(…,
8485            // WitTarget::PubSub { .. })` on the variant so a future
8486            // rebrand on the axis (an M4 per-edge WIT registry split of
8487            // [`WitTarget::PubSub`] into shape-specific peers, a
8488            // per-consumer rename that the accept-set already carries)
8489            // reaches this call site through the derive rather than a
8490            // scattered per-arm `matches!` rewrite — same
8491            // `IsVariant`-derived-arm-discriminator discipline the
8492            // peer closed-set typed enums ([`crate::CaixaKind`] via
8493            // f5bba80, [`PlacementStrategy`] via 766ec63,
8494            // [`crate::supervisor::RestartStrategy`] +
8495            // [`crate::supervisor::RestartPolicy`],
8496            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8497            // already route through on the substrate's other typed-enum
8498            // arm-discriminator axes.
8499            if c.target()?.is_pubsub() {
8500                continue;
8501            }
8502            adj.entry(c.source()).or_default().insert(c.destination());
8503        }
8504
8505        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8506        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8507
8508        // Stable DFS root order — BTreeMap iteration is sorted by key.
8509        let roots: Vec<&str> = adj.keys().copied().collect();
8510
8511        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8512        for root in roots {
8513            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8514                continue;
8515            }
8516            let root_neighbors: Vec<&str> = adj
8517                .get(root)
8518                .map(|s| s.iter().copied().collect())
8519                .unwrap_or_default();
8520            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8521            color.insert(root, Mark::Gray);
8522
8523            loop {
8524                // Read+advance the top frame in one borrow scope so we
8525                // can later mutate the stack (push/pop) without holding
8526                // a borrow across.
8527                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8528                    let node = top.0;
8529                    if top.2 >= top.1.len() {
8530                        (node, None)
8531                    } else {
8532                        let nxt = top.1[top.2];
8533                        top.2 += 1;
8534                        (node, Some(nxt))
8535                    }
8536                });
8537                let Some((node, nxt_opt)) = step else { break };
8538                let Some(nxt) = nxt_opt else {
8539                    color.insert(node, Mark::Black);
8540                    stack.pop();
8541                    continue;
8542                };
8543                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8544                match nxt_color {
8545                    Mark::Gray => {
8546                        // Reconstruct the cycle from `node` back through
8547                        // the parent chain to `nxt`, then close.
8548                        let mut cycle = Vec::new();
8549                        let mut cur = node;
8550                        cycle.push(cur.to_string());
8551                        while cur != nxt {
8552                            match parent.get(cur).copied() {
8553                                Some(p) => {
8554                                    cur = p;
8555                                    cycle.push(cur.to_string());
8556                                }
8557                                None => break,
8558                            }
8559                        }
8560                        cycle.reverse();
8561                        cycle.push(nxt.to_string());
8562                        return Err(AplicacaoError::contrato_cycle(cycle));
8563                    }
8564                    Mark::White => {
8565                        parent.insert(nxt, node);
8566                        color.insert(nxt, Mark::Gray);
8567                        let nxt_neighbors: Vec<&str> = adj
8568                            .get(nxt)
8569                            .map(|s| s.iter().copied().collect())
8570                            .unwrap_or_default();
8571                        stack.push((nxt, nxt_neighbors, 0));
8572                    }
8573                    Mark::Black => {}
8574                }
8575            }
8576        }
8577        Ok(())
8578    }
8579
8580    /// Substrate-canonical destination-facing TCP port every emitted
8581    /// per-Aplicacao artifact must key `destination`-shaped port axes
8582    /// off. Returns the typed `:entrada :port` scalar when this
8583    /// Aplicacao's `:entrada` block names `destination` under its
8584    /// `:para` axis (the destination Servico *is* the ingress apex, so
8585    /// the substrate honors the author-declared listener port
8586    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8587    /// fallback otherwise (every non-apex destination — the internal
8588    /// mesh Servicos `:contratos` reach across, the future per-edge
8589    /// policy resolver's per-destination probe targets, the
8590    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8591    /// L4 port resolver — reads the same substrate-canonical port floor
8592    /// by construction).
8593    ///
8594    /// Prior to this lift the "if :entrada matches this destination use
8595    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8596    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8597    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8598    /// prior to this lift), with no typed method on the substrate primitive
8599    /// that named the rule. A future per-destination port axis addition
8600    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8601    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8602    /// per-Servico listener ports land, a per-cluster override the operator
8603    /// pins through a future `:placement :default-port` slot — would have
8604    /// to be threaded through every renderer's inline cascade in lockstep
8605    /// or one consumer would silently disagree on which port a given
8606    /// destination Servico's ingress lands at. Lifting the rule to a
8607    /// typed method on the substrate primitive means the M4 CR
8608    /// materializer, the future per-edge policy resolver, and every
8609    /// downstream test-fixture navigator reach for exactly one typed
8610    /// dispatch — the resolver's accept-set moves as a unit on any
8611    /// future axis addition.
8612    ///
8613    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8614    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8615    /// the typed primitive, thin projections at each consumer"
8616    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8617    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8618    /// destination-facing port-resolution axis every per-Aplicacao
8619    /// L4-fallback renderer consumes.
8620    #[must_use]
8621    pub fn port_for_destination(&self, destination: &str) -> u16 {
8622        // Route the per-`:entrada` composite-reference read through
8623        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8624        // the raw `self.entrada.as_ref()` field access — the
8625        // per-destination L4-port fallback resolver's composite-
8626        // projection seed is now the canonical read-side surface
8627        // every per-Aplicacao entrada consumer routes through, peer
8628        // of the sibling `validate` per-`:entrada` shape-and-
8629        // membership gate migration on the same outer-composite
8630        // axis.
8631        // Route the per-`:entrada` apex-destination membership probe
8632        // through the lifted [`Entrada::destination`] accessor rather
8633        // than the raw `e.para == destination` field access — the last
8634        // un-lifted `.para` production-code read site on the per-
8635        // `:entrada` `:para` axis, sibling to the four caixa-core
8636        // consumer sites the peer 15ddd8c converge already routed
8637        // through the accessor (the three
8638        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8639        // membership gate sites: the `validate_entrada_para` DNS-1123
8640        // shape gate, the per-`:membros` membership lookup, and the
8641        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8642        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8643        // `entrada.para`-projection converge at
8644        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8645        // route-name projection site). Prior to this converge the
8646        // `port_for_destination` resolver was the solitary consumer
8647        // bypassing the typed dispatch on the `.para` axis — the two
8648        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8649        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8650        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8651        // reach through the same accessor family compose with this
8652        // resolver at the emit boundary via the apex-identity
8653        // invariant `spec.port_for_destination(entrada.destination())
8654        // == entrada.port` the sibling
8655        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8656        // pin pins across four permutations. A future extension of the
8657        // `:entrada :para` axis to a richer author surface (a per-
8658        // cluster alias overlay the operator pins through a future
8659        // `:placement`-scoped slot, a namespace-qualified rewrite the
8660        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8661        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8662        // §III.2 acknowledges) that lands on the accessor would silently
8663        // disagree between this resolver and the two `caixa-mesh` emit
8664        // sites — an author-declared `:para "cart"` value the accessor
8665        // rewrote to `"cart-v2"` under a future canary arm would leave
8666        // the resolver's membership arm falling through to
8667        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8668        // `.para`) while the peer emit-site consumers landed on the
8669        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8670        // silently disagreed on which destination port a given typed
8671        // `:entrada` resolves to at cluster-apply time. Pinned by the
8672        // drift-detection test
8673        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8674        // below.
8675        self.entrada()
8676            .filter(|e| e.destination() == destination)
8677            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8678    }
8679}
8680
8681/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8682/// entry may name the Aplicacao's own `:nome`.
8683///
8684/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8685/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8686/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8687/// Servicos that compose the app; an Aplicacao is never its own constituent),
8688/// and the lacre pipeline's closure-resolution would otherwise be handed a
8689/// node that is its own parent: a one-node cycle it either rejects far from
8690/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8691/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8692/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8693/// label + lacre closure root), a member whose `:caixa` equals the
8694/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8695/// peer.
8696///
8697/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8698/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8699/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8700/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8701/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8702/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8703/// (the Aplicacao :membros set; the supervision-tree :children list was the
8704/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8705/// every validated Supervisor's children are distinct from its `:nome`,
8706/// every validated Aplicacao's membros are distinct from its `:nome`. The
8707/// transitive consequence is that `:entrada :para` and `:contratos`
8708/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8709/// name the Aplicacao itself, without re-deriving the partition.
8710pub fn validate_no_self_membership(
8711    membros: &[Membro],
8712    parent_nome: &str,
8713) -> Result<(), AplicacaoError> {
8714    for m in membros {
8715        if m.nome() == parent_nome {
8716            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
8717        }
8718    }
8719    Ok(())
8720}
8721
8722#[derive(Debug, Error, PartialEq, Eq)]
8723pub enum AplicacaoError {
8724    #[error("Aplicacao must declare at least one :membros entry")]
8725    NoMembros,
8726    #[error(
8727        ":membros entry has empty :caixa (every member must name a Servico; \
8728         omit the entry instead of carrying an empty name)"
8729    )]
8730    MembroCaixaEmpty,
8731    #[error(
8732        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8733         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8734         name / label value the member name lands in; use a lowercase \
8735         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8736    )]
8737    MembroCaixaInvalid { caixa: String, reason: String },
8738    #[error(
8739        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8740         semver constraint that resolves through the lacre pipeline)"
8741    )]
8742    MembroVersaoEmpty { caixa: String },
8743    #[error(
8744        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8745         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8746         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8747         carries; the lacre pipeline resolves both through the same parser)"
8748    )]
8749    MembroVersaoInvalid {
8750        caixa: String,
8751        versao: String,
8752        reason: String,
8753    },
8754    #[error(
8755        ":membros entry {caixa:?} appears more than once (the graph node set \
8756         is a set, not a multiset; duplicate members produce duplicate \
8757         programs.yaml entries and ambiguous :contratos membership lookups)"
8758    )]
8759    MembroDuplicate { caixa: String },
8760    #[error(
8761        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8762         never its own constituent Servico (the application graph is a DAG rooted \
8763         at the Aplicacao; :membros names the *other* caixas that compose the \
8764         app, not the app itself). Since every :nome is a globally-unique \
8765         substrate identity, a member naming the Aplicacao's own :nome is a \
8766         one-node lacre-closure recursion, not a coincidentally-named peer; \
8767         drop the self-referential :membros entry or rename it to the actual \
8768         constituent caixa."
8769    )]
8770    MembroIsSelfAplicacao { caixa: String },
8771    #[error(
8772        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8773         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8774         member name)"
8775    )]
8776    ContratoCaixaEmpty { slot: &'static str },
8777    #[error(
8778        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8779         :contratos {slot} value names a member of :membros, which is itself a \
8780         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8781         object the member name lands in — Service, Pod, identity-based Cilium \
8782         selector; use a lowercase alphanumeric + hyphen identifier like \
8783         `\"checkout\"` or `\"cart-v2\"`)"
8784    )]
8785    ContratoCaixaInvalid {
8786        slot: &'static str,
8787        caixa: String,
8788        reason: String,
8789    },
8790    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8791    ContratoMemberMissing { caixa: String },
8792    #[error(
8793        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8794         entry is an inter-Servico contract whose :de and :para must name distinct \
8795         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8796         the contract, or point :para at the member it actually calls)"
8797    )]
8798    ContratoSelfLoop { caixa: String, wit: String },
8799    #[error("contrato {de:?} → {para:?} has empty :wit")]
8800    EmptyWit { de: String, para: String },
8801    #[error(
8802        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8803         {reason} (the substrate dispatches `:wit` values on the canonical \
8804         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8805         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8806         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8807         kebab-case identifier per segment)"
8808    )]
8809    ContratoWitInvalid {
8810        de: String,
8811        para: String,
8812        wit: String,
8813        reason: String,
8814    },
8815    #[error(
8816        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8817         :membros; fill the :para field with a member name)"
8818    )]
8819    EntradaParaEmpty,
8820    #[error(
8821        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8822         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8823         label per the K8s apiserver's `metadata.name` rule on every object the \
8824         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8825         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8826         `\"checkout\"` or `\"cart-v2\"`)"
8827    )]
8828    EntradaParaInvalid { para: String, reason: String },
8829    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8830    EntradaMemberMissing { para: String },
8831    #[error(":entrada must declare a non-empty :host")]
8832    EmptyEntradaHost,
8833    #[error(
8834        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8835         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8836         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8837         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8838    )]
8839    EntradaHostInvalid { host: String, reason: String },
8840    #[error(":entrada :port must be in 1..=65535, got 0")]
8841    EntradaPortZero,
8842    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8843    EntradaPathEmpty,
8844    #[error(
8845        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8846    )]
8847    EntradaPathNotAbsolute { path: String },
8848    #[error(
8849        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8850         value: {reason} (the K8s apiserver enforces the same shape on \
8851         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8852         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8853         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8854    )]
8855    EntradaPathInvalid { path: String, reason: String },
8856    #[error(":entrada :paths entry {path:?} appears more than once")]
8857    EntradaPathDuplicate { path: String },
8858    #[error(
8859        ":placement {estrategia} requires at least one :clusters entry \
8860         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8861    )]
8862    PlacementWithoutClusters { estrategia: PlacementStrategy },
8863    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8864    PlacementClusterEmpty,
8865    #[error(
8866        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8867         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8868         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8869         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8870         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8871         identifier like `\"rio\"` or `\"mar-east\"`)"
8872    )]
8873    PlacementClusterInvalid { cluster: String, reason: String },
8874    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8875    PlacementClusterDuplicate { cluster: String },
8876    #[error(
8877        ":placement :affinity must be non-empty when set (omit :affinity to express \
8878         `no placement hint`)"
8879    )]
8880    PlacementAffinityEmpty,
8881    #[error(
8882        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8883         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8884         `placement.affinity` field and in every future M4 placement-engine routing \
8885         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8886         selector — both enforce the DNS-1123 label rule on admission; use a \
8887         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8888         `\"low-latency\"`, or `\"anti-affinity\"`)"
8889    )]
8890    PlacementAffinityInvalid { affinity: String, reason: String },
8891    #[error(":placement Sharded requires :shard-key")]
8892    ShardedWithoutKey,
8893    #[error(
8894        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8895         hashes every entity onto the same shard, defeating sharding entirely)"
8896    )]
8897    ShardedKeyEmpty,
8898    #[error(
8899        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8900         entity-id extractor expression: {reason} (the future M4 Akka-style \
8901         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8902         as a single-token property reference and hashes the extracted entity ID \
8903         to compute shard placement; use a printable-ASCII extractor expression \
8904         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8905         `\"${{tenant}}\"`)"
8906    )]
8907    ShardKeyInvalid { shard_key: String, reason: String },
8908    #[error(
8909        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8910         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8911         convention); :estrategia Replicated runs every cluster active-active and \
8912         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8913         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8914         to :estrategia Sharded if hash-keyed routing is the intent"
8915    )]
8916    ShardKeyOnNonSharded {
8917        estrategia: PlacementStrategy,
8918        shard_key: String,
8919    },
8920    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8921    ContratoMissingTarget {
8922        de: String,
8923        para: String,
8924        wit: String,
8925        expected: &'static str,
8926    },
8927    #[error(
8928        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8929         expected `:{expected}` only"
8930    )]
8931    ContratoWrongTarget {
8932        de: String,
8933        para: String,
8934        wit: String,
8935        expected: &'static str,
8936    },
8937    #[error(
8938        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8939         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8940         that matches no traffic and silently drops every request)"
8941    )]
8942    ContratoEndpointEmpty { de: String, para: String },
8943    #[error(
8944        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8945         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8946         :entrada :paths)"
8947    )]
8948    ContratoEndpointNotAbsolute {
8949        de: String,
8950        para: String,
8951        endpoint: String,
8952    },
8953    #[error(
8954        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8955         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8956         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8957         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8958         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8959         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8960         and whitespace)"
8961    )]
8962    ContratoEndpointInvalid {
8963        de: String,
8964        para: String,
8965        endpoint: String,
8966        reason: String,
8967    },
8968    #[error(
8969        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8970         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8971         pub-sub-shaped)"
8972    )]
8973    ContratoSubjectEmpty { de: String, para: String },
8974    #[error(
8975        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8976         NATS subject: {reason} (the NATS server's subject parser enforces the \
8977         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8978         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8979         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8980         `\"orders.*.completed\"` — a malformed subject silently drops every \
8981         message at runtime far from the source caixa.lisp)"
8982    )]
8983    ContratoSubjectInvalid {
8984        de: String,
8985        para: String,
8986        subject: String,
8987        reason: String,
8988    },
8989    #[error(
8990        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8991         addresses the bucket root, defeating the per-key isolation the slot exists \
8992         for; omit :slot only if the WIT world is not store-shaped)"
8993    )]
8994    ContratoSlotEmpty { de: String, para: String },
8995    #[error(
8996        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8997         WASI keyvalue store slot template: {reason} (the substrate enforces \
8998         the printable-ASCII intersection-floor every kv backend admits — \
8999         use a single-token path / template expression like `\"checkout/$orderId\"`, \
9000         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
9001         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
9002         slot either gets rejected on write by strict backends or silently \
9003         corrupts the next read on permissive ones, far from the source caixa.lisp)"
9004    )]
9005    ContratoSlotInvalid {
9006        de: String,
9007        para: String,
9008        slot: String,
9009        reason: String,
9010    },
9011    #[error(
9012        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
9013         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
9014        cycle.join(" → ")
9015    )]
9016    ContratoCycle { cycle: Vec<String> },
9017    #[error(
9018        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
9019         than once (the typed graph edges are a set, not a multiset; duplicate \
9020         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
9021         values that K8s admission rejects far from the source caixa.lisp)"
9022    )]
9023    ContratoDuplicate {
9024        de: String,
9025        para: String,
9026        wit: String,
9027        target: String,
9028    },
9029    #[error(
9030        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
9031         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
9032         express `no per-call deadline on this axis`"
9033    )]
9034    PolicyTimeoutZero,
9035    #[error(
9036        ":politicas :retries must be > 0 when set; omit :retries to express \
9037         `no retries on transient failure`"
9038    )]
9039    PolicyRetriesZero,
9040    #[error(
9041        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
9042         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
9043         retry policy into a thundering-herd amplification vector on transient \
9044         failure (one caller request fans out to `(retries+1)^depth` server-side \
9045         calls across the synchronous-:contratos subgraph), exactly the failure \
9046         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
9047         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
9048         or omit :retries to disable retries entirely"
9049    )]
9050    PolicyRetriesExceedsCap { retries: u32 },
9051    #[error(
9052        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
9053         breaker trips on the first call); omit :circuit-breaker to disable it"
9054    )]
9055    PolicyBreakerZeroFailures,
9056    #[error(
9057        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
9058         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
9059         above this cap turns the typed breaker policy into a no-op: the trip \
9060         threshold is structurally so high that no realistic failures-per-:window \
9061         traffic shape can reach it, so the breaker never trips and every typed-slot \
9062         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
9063         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
9064         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
9065         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
9066         omit :circuit-breaker to disable the breaker entirely"
9067    )]
9068    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
9069    #[error(
9070        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
9071         tracks no failures); omit :circuit-breaker to disable it"
9072    )]
9073    PolicyBreakerZeroWindow,
9074    #[error(
9075        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
9076         request); omit :rate-limit to disable rate limiting"
9077    )]
9078    PolicyRateLimitZero,
9079    #[error(
9080        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
9081         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
9082         rate-limit policy into a no-op limiter: the token-bucket capacity is \
9083         structurally so high that no realistic per-edge traffic shape can drain it, \
9084         so the limiter never trips and every typed-slot consumer (the future \
9085         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9086         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
9087         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
9088         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
9089         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
9090         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
9091         to disable rate limiting entirely"
9092    )]
9093    PolicyRateLimitExceedsCap { rate: u32 },
9094    #[error(
9095        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
9096         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
9097         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
9098         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
9099         three canonical windows)"
9100    )]
9101    PolicyRateLimitWindowNotCanonical { window: Duration },
9102    #[error(
9103        ":politicas :timeout must be an integer number of milliseconds — the canonical \
9104         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
9105         duration codec round-trips losslessly; got {timeout:?} which carries a \
9106         sub-millisecond residue that either truncates to a different `Duration` on \
9107         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
9108         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
9109         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
9110         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
9111    )]
9112    PolicyTimeoutNotCanonical { timeout: Duration },
9113    #[error(
9114        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
9115         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
9116         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
9117         overlays carry a deadline so long no realistic synchronous-:contratos \
9118         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
9119         CSE invariant degenerates to enforcement only at the per-Servico \
9120         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
9121         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
9122         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
9123         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
9124         maxes out at the same `3600s` ceiling) or omit :timeout to express \
9125         `no per-call deadline on this axis` (the synchronous-call deadline then \
9126         relies entirely on the per-Servico `:limits :wall-clock` axis)"
9127    )]
9128    PolicyTimeoutExceedsCap { timeout: Duration },
9129    #[error(
9130        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
9131         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
9132         the shared duration codec round-trips losslessly; got {window:?} which carries a \
9133         sub-millisecond residue that either truncates to a different `Duration` on \
9134         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
9135         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
9136    )]
9137    PolicyBreakerWindowNotCanonical { window: Duration },
9138    #[error(
9139        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
9140         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
9141         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
9142         is structurally so long that transient failures are never forgotten, the breaker \
9143         trips once and stays tripped for the lifetime of the component, and every typed-slot \
9144         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9145         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
9146         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
9147         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
9148         the breaker entirely"
9149    )]
9150    PolicyBreakerWindowExceedsCap { window: Duration },
9151    #[error(
9152        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
9153         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
9154         a single timing-out call can be declared failed, so the dominant failure mode \
9155         the breaker exists to catch is structurally never counted: a call dispatched at \
9156         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
9157         open at dispatch has already rolled, and every typed-slot consumer (the future \
9158         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9159         outlier_detection.interval paired against the per-route request timeout) emits a \
9160         breaker that cannot trip on timeouts however high the call volume. Pin :window \
9161         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
9162         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
9163         same shape), lower :timeout, or omit one of the two axes"
9164    )]
9165    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
9166    #[error(
9167        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
9168         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
9169         :window ({cb_window:?}) — the token-bucket dispatches at most \
9170         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
9171         structurally below the trip threshold, so the breaker cannot trip even under \
9172         100% failure and every typed-slot consumer (the future \
9173         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9174         outlier_detection.consecutive_5xx paired against \
9175         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
9176         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
9177         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
9178    )]
9179    PolicyBreakerCannotTripUnderRateLimit {
9180        rate: u32,
9181        rl_window: Duration,
9182        max_failures: u32,
9183        cb_window: Duration,
9184    },
9185    #[error(
9186        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
9187         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
9188         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
9189         at or before the last retry, so the breaker opens with declared retries still \
9190         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
9191         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
9192         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
9193         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
9194         Envoy / resilience4j production playbooks recommend the breaker's trip \
9195         threshold be observably larger than any single client's retry budget so the \
9196         breaker distinguishes one persistently-failing client from sustained \
9197         multi-client failure), lower :retries, or omit one of the two axes"
9198    )]
9199    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
9200    #[error(
9201        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
9202         ({retries}) plus the initial attempt — one client's declared retry sequence is \
9203         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
9204         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
9205         retry policy is silently truncated by the same rate limiter it feeds through and \
9206         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
9207         overlay, Envoy's retry_policy.num_retries paired against \
9208         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
9209         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
9210         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
9211         bucket capacity be observably larger than any single client's retry budget so the \
9212         limiter distinguishes one client's declared retries from sustained multi-client \
9213         load), lower :retries, or omit one of the two axes"
9214    )]
9215    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
9216}
9217
9218// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
9219// ctor `entrada_host_invalid` is folded onto the sibling
9220// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
9221// `{ <field>: String, reason: String }` variants
9222// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
9223// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
9224// `ShardKeyInvalid`), so every variant on the uniform two-slot
9225// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
9226// reads through one substrate-primitive family rather than one macro
9227// closing six sites plus a hand-written seventh ctor closing the
9228// paired site alone. Prior separate-ctor rationale (17dd504) migrates
9229// verbatim to the macro's outer doc block.
9230
9231// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
9232// wit, expected }` wire-up sites at [`WitContract::target`] onto one
9233// substrate-primitive family per typed variant — the paired sibling on
9234// [`AplicacaoError`] of the four `LayoutError` constructor families
9235// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
9236// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
9237// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
9238// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
9239// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
9240// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
9241// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
9242// HTTP with subject/slot, PubSub with endpoint/slot, Store with
9243// endpoint/subject, Capability with any payload; three
9244// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
9245// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
9246// opened the identical six-line
9247// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
9248// WitTarget::<label> }` struct-literal against the local `edge()` closure
9249// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
9250// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
9251// on the same altitude the peer four `LayoutError` constructor families
9252// each closed on their sibling envelopes.
9253//
9254// The macro below generates one `#[must_use]` inherent constructor per
9255// variant of shape `fn <ctor>(edge: (String, String, String), expected:
9256// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
9257// dispatch per arm: `return
9258// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
9259// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
9260// the pre-lift struct-literal on the same edge fixture. The uniform four-
9261// field construction (`de, para, wit` triple-destructure onto same-named
9262// fields + `expected` verbatim) is spelled once — inside the macro —
9263// rather than at every wire-up site. `#[must_use]` fires a compile warning
9264// at any wire-up that mistakenly discards the constructed error.
9265//
9266// Every future consumer that wants to construct one of these two variants
9267// outside [`WitContract::target`] (a deferred
9268// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9269// admission validator raising wrong-target / missing-target diagnostics
9270// on unrecognized shapes, a future `feira validate --contratos` per-caixa
9271// admission verb, a per-`WitContract` payload-axis pre-emitter probing
9272// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
9273// slots) reaches the variant through one call rather than re-inlining the
9274// six-line struct-literal block in lockstep with the seven in-crate
9275// wire-up sites.
9276macro_rules! contrato_target_ctors {
9277    ($($ctor:ident => $variant:ident),* $(,)?) => {
9278        impl AplicacaoError {
9279            $(
9280                #[doc = concat!(
9281                    "Construct an [`AplicacaoError::",
9282                    stringify!($variant),
9283                    "`] naming the offending edge `(de, para, wit)` triple ",
9284                    "under the given `expected` payload-field-name label. ",
9285                    "Folds the uniform `{ de, para, wit, expected }` four-",
9286                    "slot struct-literal onto one substrate primitive so ",
9287                    "every [`WitContract::target`] wire-up on this variant ",
9288                    "reads through one dispatch rather than the pre-lift ",
9289                    "six-line open-coded block. The `edge` triple threads ",
9290                    "verbatim from [`WitContract::edge_triple`] via the ",
9291                    "local `edge()` closure at the call site."
9292                )]
9293                #[must_use]
9294                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
9295                    let (de, para, wit) = edge;
9296                    Self::$variant { de, para, wit, expected }
9297                }
9298            )*
9299        }
9300    };
9301}
9302
9303contrato_target_ctors! {
9304    contrato_wrong_target => ContratoWrongTarget,
9305    contrato_missing_target => ContratoMissingTarget,
9306}
9307
9308// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
9309// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
9310// onto one substrate-primitive family per typed variant — the paired
9311// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
9312// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
9313// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9314// `ContratoMissingTarget`) and of the two-slot
9315// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
9316// on the sibling per-`:entrada :host` envelope. Every one of the four
9317// wire-up sites — three under [`WitContract::target`] (the empty
9318// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
9319// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
9320// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
9321// value-shape gate fires ahead of) — opened the identical two-line
9322// `let (de, para) = <contract>.edge_pair(); return Err(
9323// AplicacaoError::<Variant> { de, para });` block against the local
9324// [`WitContract::edge_pair`] composite-projection accessor, the exact
9325// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9326// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
9327// and [`AplicacaoError::entrada_host_invalid`] each closed on their
9328// sibling envelopes.
9329//
9330// The macro below generates one `#[must_use]` inherent constructor per
9331// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
9332// collapsing the four sites onto one dispatch per arm:
9333// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
9334// equal to the pre-lift struct-literal on the same edge pair. The
9335// uniform two-field construction (`de, para` pair-destructure onto
9336// same-named fields) is spelled once — inside the macro — rather than
9337// at every wire-up site. `#[must_use]` fires a compile warning at any
9338// wire-up that mistakenly discards the constructed error.
9339//
9340// Every future consumer that wants to construct one of these four
9341// variants outside the two in-crate wire-up sites (a deferred
9342// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9343// admission validator raising empty-payload / empty-`:wit` diagnostics,
9344// a future `feira validate --contratos` per-caixa admission verb, an
9345// M4 typed WIT-registry-driven per-arm pre-emitter probing the
9346// [`WitContract`] payload slot against a canonical per-arm requirement
9347// table) reaches the variant through one call rather than re-inlining
9348// the two-line pair-destructure block in lockstep with the four
9349// in-crate wire-up sites.
9350macro_rules! contrato_empty_pair_ctors {
9351    ($($ctor:ident => $variant:ident),* $(,)?) => {
9352        impl AplicacaoError {
9353            $(
9354                #[doc = concat!(
9355                    "Construct an [`AplicacaoError::",
9356                    stringify!($variant),
9357                    "`] naming the offending edge `(de, para)` pair. ",
9358                    "Folds the uniform `{ de, para }` two-slot struct-",
9359                    "literal onto one substrate primitive so every ",
9360                    "wire-up on this variant reads through one dispatch ",
9361                    "rather than the pre-lift two-line open-coded ",
9362                    "`let (de, para) = <contract>.edge_pair(); return ",
9363                    "Err(<Variant> { de, para });` block. The `edge` ",
9364                    "pair threads verbatim from [`WitContract::edge_pair`] ",
9365                    "at the call site."
9366                )]
9367                #[must_use]
9368                pub fn $ctor(edge: (String, String)) -> Self {
9369                    let (de, para) = edge;
9370                    Self::$variant { de, para }
9371                }
9372            )*
9373        }
9374    };
9375}
9376
9377contrato_empty_pair_ctors! {
9378    empty_wit => EmptyWit,
9379    contrato_endpoint_empty => ContratoEndpointEmpty,
9380    contrato_subject_empty => ContratoSubjectEmpty,
9381    contrato_slot_empty => ContratoSlotEmpty,
9382}
9383
9384// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
9385// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
9386// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
9387// onto one substrate primitive on [`AplicacaoError`] — sibling on the
9388// `{ de: String, para: String, <field>: String }` three-slot envelope of
9389// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
9390// variants on the paired `{ de, para }` two-slot envelope carrying the
9391// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
9392// { de, para });` pair-destructure prelude), the peer four-slot
9393// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
9394// the paired `{ de, para, <field>: String, reason: String }` envelope
9395// carrying the parser-shaped `reason` trailer), and the peer four-slot
9396// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
9397// `{ de, para, wit, expected: &'static str }` envelope carrying the
9398// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
9399// variant is the sole occupant of the three-slot `{ de, para, <field>:
9400// String }` shape on [`AplicacaoError`] (no sibling
9401// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
9402// and `:slot` axes carry no "must start with /" invariant, since the
9403// NATS subject grammar and the WASI keyvalue slot template grammar don't
9404// share the Gateway-API-HTTPPathMatch leading-slash prelude the
9405// `:endpoint` axis does), so a full macro isn't warranted; a single
9406// `#[must_use]` inherent ctor matching the ambient
9407// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
9408// peer per-`:contratos` ctor families each carry closes the last
9409// open-coded three-slot struct-literal on the envelope, matching the
9410// same standalone-ctor discipline the sibling
9411// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
9412// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
9413// [`crate::SupervisorError::child_caixa_invalid`] /
9414// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
9415// `{ caixa: String, [versao: String,] reason: String }` two- and three-
9416// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
9417// one variant on the `{ host: String, reason: String }` two-slot
9418// envelope) apply on their sibling one-off variants.
9419//
9420// The one wire-up site on this variant — [`WitContract::target`]'s
9421// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
9422// six per-`:contratos` value-shape gates inside the same method body,
9423// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
9424// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
9425// `ContratoWitInvalid`) each already reach through one of the three
9426// peer macro-generated ctor families above — opened the same five-line
9427// `let (de, para) = self.edge_pair(); return
9428// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
9429// ep.to_string() });` struct-literal against the local
9430// [`WitContract::edge_pair`] composite-projection accessor and the
9431// caller-side `&str` endpoint — the exact "same block re-inlined at
9432// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9433// altitude the six peer `AplicacaoError` constructor families each
9434// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
9435// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
9436// becomes a caixa-build error, not a Cilium L7 policy-side path-match
9437// silent traffic drop far from the source caixa.lisp) now routes through
9438// one substrate primitive on the envelope.
9439//
9440// The ctor below folds the site onto one dispatch:
9441// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
9442// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
9443// on the same `(edge_pair, endpoint)` pair. The uniform three-field
9444// construction (`de, para` pair-destructure onto same-named fields +
9445// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
9446// body — rather than at the wire-up site. `#[must_use]` fires a compile
9447// warning at any future wire-up that mistakenly discards the constructed
9448// error.
9449//
9450// Every future consumer that wants to construct this variant outside
9451// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
9452// CR materializer's per-`:contratos` admission validator raising the
9453// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
9454// `feira validate --contratos` per-caixa admission verb re-running the
9455// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
9456// probing each declared `:endpoint` against the same shared
9457// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
9458// resolver rejecting a leading-slash-missing `:endpoint` against a
9459// cluster-local Cilium snapshot the M4 CR materializer projects) now
9460// reaches this variant through one call rather than re-inlining the
9461// five-line pair-destructure + struct-literal block in lockstep with
9462// the sole in-crate wire-up site.
9463impl AplicacaoError {
9464    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
9465    /// naming the offending edge `(de, para)` pair and the per-payload
9466    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
9467    /// endpoint.to_string() }` three-slot struct-literal onto one
9468    /// substrate primitive so every wire-up on this variant reads
9469    /// through one dispatch rather than the pre-lift five-line
9470    /// pair-destructure + struct-literal block. The `edge` pair threads
9471    /// verbatim from [`WitContract::edge_pair`] at the call site,
9472    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
9473    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
9474    /// paired two-slot and four-slot per-`:contratos :endpoint`
9475    /// envelopes on the same [`AplicacaoError`] type.
9476    #[must_use]
9477    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
9478        let (de, para) = edge;
9479        Self::ContratoEndpointNotAbsolute {
9480            de,
9481            para,
9482            endpoint: endpoint.to_string(),
9483        }
9484    }
9485
9486    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
9487    /// offending self-edge's owning `caixa` and its `:wit` world
9488    /// reference, projecting both slots through the [`WitContract`]'s
9489    /// own [`WitContract::source`] and [`WitContract::world_ref`]
9490    /// scalar accessors on the substrate primitive.
9491    ///
9492    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
9493    /// contract.world_ref().to_string() }` two-slot struct-literal onto
9494    /// one substrate primitive so every wire-up on this variant reads
9495    /// through one dispatch rather than the pre-lift four-line
9496    /// twin-`.to_string()` struct-literal block. The `contract` borrow
9497    /// threads verbatim from the caller-side `for c in
9498    /// self.contratos()` iteration at the sole in-crate wire-up site
9499    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
9500    /// per-`:contratos` `WitContract`-projection ctor discipline the
9501    /// peer [`AplicacaoError::empty_wit`] /
9502    /// [`AplicacaoError::contrato_endpoint_empty`] /
9503    /// [`AplicacaoError::contrato_subject_empty`] /
9504    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
9505    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
9506    /// envelope.
9507    ///
9508    /// The `caixa` slot is projected through [`WitContract::source`]
9509    /// rather than [`WitContract::destination`] to preserve byte-equal
9510    /// diagnostic ordering with the pre-lift open-coded body — a
9511    /// [`WitContract::is_self_loop`]-gated call site has
9512    /// `source() == destination()` by that predicate's own contract, so
9513    /// the two accessors are exchange-symmetric at this call site, but
9514    /// naming `source` at the ctor definition matches the pre-lift
9515    /// site's field selection and pins the discipline for any future
9516    /// consumer that constructs the variant against a not-yet-gated
9517    /// candidate contract (e.g. an M4
9518    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9519    /// webhook re-checking a per-`(:de, :para)` patched contract, a
9520    /// future `feira validate --contratos` per-caixa verb re-running
9521    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
9522    /// overlay resolver rejecting a self-edge introduced by a
9523    /// cluster-local `:contratos` override the M4 CR materializer
9524    /// projects).
9525    ///
9526    /// Peer of the sibling `WitContract`-projection ctors on the
9527    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
9528    /// same "one typed dispatch on the substrate primitive, projecting
9529    /// through the paired [`WitContract`] accessors, thin projections
9530    /// at each consumer" discipline extended here onto the last unlifted
9531    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
9532    /// inside [`AplicacaoSpec::validate_contratos`].
9533    #[must_use]
9534    pub fn contrato_self_loop(contract: &WitContract) -> Self {
9535        Self::ContratoSelfLoop {
9536            caixa: contract.source().to_string(),
9537            wit: contract.world_ref().to_string(),
9538        }
9539    }
9540
9541    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
9542    /// offending `:membros :caixa` and its `:versao` requirement under
9543    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
9544    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
9545    /// reason.into() }` three-slot struct-literal onto one substrate
9546    /// primitive so every wire-up on this variant reads through one
9547    /// dispatch, matching the peer
9548    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
9549    /// shape verbatim on the sibling `SupervisorError { caixa: String,
9550    /// versao: String, reason: String }` envelope's per-`:children :versao`
9551    /// axis. `reason` accepts both `&str` literals and `format!(…)`
9552    /// outputs through the `impl Into<String>` bound so the sole
9553    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
9554    /// requirement-cascade closure (routing the shared
9555    /// [`crate::render::require_valid_versao_requirement`]-delivered
9556    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
9557    /// transformation on the caller-side `reason` axis. The
9558    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
9559    /// routing the sole wire-up already threads through remains verbatim
9560    /// — the ctor's two `&str` parameters accept the two accessors'
9561    /// returns as-is with no re-allocation at the call site.
9562    #[must_use]
9563    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
9564        Self::MembroVersaoInvalid {
9565            caixa: caixa.to_string(),
9566            versao: versao.to_string(),
9567            reason: reason.into(),
9568        }
9569    }
9570
9571    /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
9572    /// the offending `:placement :clusters` entry.
9573    ///
9574    /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
9575    /// cluster.to_string() }` one-field struct-literal onto one substrate
9576    /// primitive so every wire-up on this variant reads through one
9577    /// dispatch rather than the pre-lift three-line open-coded
9578    /// struct-literal block. The `cluster` slot threads verbatim from the
9579    /// caller-side `for c in p.clusters()` iteration at the sole in-crate
9580    /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
9581    /// per-entry dedup closure passed to
9582    /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
9583    /// bracket accepts the free function pointer as-is.
9584    ///
9585    /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
9586    /// per-`:politicas <scalar>` single-slot ctor families
9587    /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
9588    /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
9589    /// `{ path: String }` at the peer per-gateway envelope,
9590    /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
9591    /// at the peer per-`:politicas` cap-scalar envelope) on the same
9592    /// [`AplicacaoError`] type — extends the "one typed dispatch per
9593    /// substrate primitive on every single-slot per-M3-slot envelope"
9594    /// discipline onto the last unlifted `{ cluster: String }` one-slot
9595    /// per-`:placement :clusters` dedup-envelope inside
9596    /// [`AplicacaoSpec::validate_placement_shape`].
9597    ///
9598    /// Every future consumer that wants to construct this variant outside
9599    /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
9600    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9601    /// webhook re-checking a `:placement :clusters` overlay against a
9602    /// per-tenant cluster-topology snapshot, a future `feira validate
9603    /// --placement` per-caixa admission verb re-running the dedup check
9604    /// on demand, an M4 per-cluster placement resolver rejecting a
9605    /// duplicate cluster-name entry introduced by a fleet-local overlay
9606    /// the M4 CR materializer projects — now reaches this variant through
9607    /// one call rather than re-inlining the three-line struct-literal.
9608    #[must_use]
9609    pub fn placement_cluster_duplicate(cluster: &str) -> Self {
9610        Self::PlacementClusterDuplicate {
9611            cluster: cluster.to_string(),
9612        }
9613    }
9614
9615    /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
9616    /// the offending `:placement :estrategia` scalar the empty `:clusters`
9617    /// list was declared against, projecting through the paired
9618    /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
9619    /// primitive.
9620    ///
9621    /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
9622    /// placement.estrategia() }` one-field struct-literal onto one
9623    /// substrate primitive so every wire-up on this variant reads through
9624    /// one dispatch rather than the pre-lift three-line open-coded
9625    /// `AplicacaoError::PlacementWithoutClusters { estrategia:
9626    /// p.estrategia() }` block inside
9627    /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
9628    /// projection posture as the sibling
9629    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
9630    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
9631    /// per-`:contratos` self-edge envelope) and the peer
9632    /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
9633    /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
9634    /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
9635    /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
9636    /// per-`:placement` empty-clusters envelope inside
9637    /// [`AplicacaoSpec::validate_placement`].
9638    ///
9639    /// `#[must_use]` and `const fn` alike: the ctor threads the paired
9640    /// [`Placement::estrategia`] `Copy`-scalar return through one
9641    /// zero-runtime-work construction — no allocation, no owned-string
9642    /// materialization — so the pre-lift `Copy`-pass-through property the
9643    /// open-coded `p.estrategia()` field expression carried survives
9644    /// verbatim through the substrate primitive. The sibling
9645    /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
9646    /// carries the paired `.to_string()`-owned-String allocation on the
9647    /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
9648    /// preserves the zero-alloc posture at the substrate-primitive
9649    /// dispatch, matching the peer
9650    /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
9651    /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
9652    /// per-`:politicas` cap-scalar envelopes.
9653    ///
9654    /// Every future consumer that wants to construct this variant outside
9655    /// [`AplicacaoSpec::validate_placement`] — a deferred
9656    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9657    /// webhook re-checking a `:placement :clusters` overlay against a
9658    /// per-tenant cluster-topology snapshot when the overlay resolves to
9659    /// an empty list, a future `feira validate --placement` per-caixa
9660    /// admission verb re-running the empty-clusters check on demand, an
9661    /// M4 per-cluster placement resolver rejecting an empty cluster pool
9662    /// after a fleet-local overlay strips every declared cluster — now
9663    /// reaches this variant through one call rather than re-inlining the
9664    /// three-line struct-literal in lockstep with the one in-crate
9665    /// wire-up site.
9666    #[must_use]
9667    pub const fn placement_without_clusters(placement: &Placement) -> Self {
9668        Self::PlacementWithoutClusters {
9669            estrategia: placement.estrategia(),
9670        }
9671    }
9672
9673    /// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
9674    /// offending `:placement :estrategia` scalar and the declared-but-
9675    /// inert `:shard-key` value the non-`Sharded` arm refused, projecting
9676    /// the strategy through the paired [`Placement::estrategia`]
9677    /// `Copy`-scalar accessor on the substrate primitive.
9678    ///
9679    /// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
9680    /// placement.estrategia(), shard_key: shard_key.to_string() }`
9681    /// two-slot struct-literal onto one substrate primitive so every
9682    /// wire-up on this variant reads through one dispatch rather than
9683    /// the pre-lift four-line open-coded struct-literal block inside
9684    /// [`AplicacaoSpec::validate_placement`]'s
9685    /// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
9686    /// arm. Same substrate-primitive-projection posture as the sibling
9687    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
9688    /// projecting through [`Placement::estrategia`] on the peer
9689    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
9690    /// empty-clusters envelope) and the peer
9691    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
9692    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
9693    /// the paired per-`:contratos` self-edge envelope) ctors — extended
9694    /// here onto the last unlifted `{ estrategia: PlacementStrategy,
9695    /// shard_key: String }` two-slot per-`:placement :shard-key`
9696    /// declared-but-inert envelope on the sibling non-`Sharded`-arm
9697    /// partition.
9698    ///
9699    /// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
9700    /// `&str` from the sole in-crate wire-up site (narrowed from
9701    /// `Option<&str>` via [`Placement::shard_key`]) and any future
9702    /// `&String` deref from a downstream consumer that reaches for the
9703    /// slot through the paired accessor, materializing the owned
9704    /// [`String`] via one `.to_string()` at the substrate primitive so
9705    /// no per-arm `.to_string()` allocation lives at the caller. The
9706    /// `estrategia` slot threads through [`Placement::estrategia`]'s
9707    /// `Copy`-scalar return rather than accepting a bare
9708    /// [`PlacementStrategy`] argument, matching the peer
9709    /// [`AplicacaoError::placement_without_clusters`] discipline —
9710    /// carrying the [`Placement`] borrow through one accessor call at
9711    /// the substrate primitive is strictly stronger than accepting the
9712    /// scalar as a separate argument (a future caller that constructs
9713    /// the error against a candidate [`Placement`] whose
9714    /// [`Placement::estrategia`] value the caller re-derives from
9715    /// another source can silently disagree with the storage the
9716    /// [`Placement`] carries; the accessor-projected primitive cannot).
9717    ///
9718    /// Peer of the sibling per-`:placement` single-slot / two-slot ctor
9719    /// families on the same [`AplicacaoError`] type — same "one typed
9720    /// dispatch on the substrate primitive, projecting through the
9721    /// paired [`Placement`] accessors, thin projections at each
9722    /// consumer" discipline extended here onto the last unlifted
9723    /// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
9724    /// [`AplicacaoSpec::validate_placement`].
9725    ///
9726    /// Every future consumer that wants to construct this variant
9727    /// outside [`AplicacaoSpec::validate_placement`] — a deferred
9728    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9729    /// webhook re-checking a `:placement (:estrategia Replicated
9730    /// :shard-key …)` overlay against a per-tenant cluster-topology
9731    /// snapshot, a future `feira validate --placement` per-caixa
9732    /// admission verb re-running the non-`Sharded`-arm refusal on
9733    /// demand, an M4 per-cluster placement resolver rejecting a
9734    /// declared-but-inert `:shard-key` introduced by a fleet-local
9735    /// overlay the M4 CR materializer projects — now reaches this
9736    /// variant through one call rather than re-inlining the four-line
9737    /// struct-literal in lockstep with the one in-crate wire-up site.
9738    #[must_use]
9739    pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
9740        Self::ShardKeyOnNonSharded {
9741            estrategia: placement.estrategia(),
9742            shard_key: shard_key.to_string(),
9743        }
9744    }
9745
9746    /// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
9747    /// offending `:entrada :para` value the membership lookup against the
9748    /// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
9749    /// slot through the paired [`Entrada::destination`] byte-string
9750    /// accessor on the substrate primitive.
9751    ///
9752    /// Folds the uniform `Self::EntradaMemberMissing { para:
9753    /// entrada.destination().to_string() }` one-field struct-literal onto
9754    /// one substrate primitive so every wire-up on this variant reads
9755    /// through one dispatch rather than the pre-lift three-line
9756    /// open-coded `AplicacaoError::EntradaMemberMissing { para:
9757    /// e.destination().to_string() }` block inside
9758    /// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
9759    /// projection posture as the sibling
9760    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
9761    /// projecting through [`Placement::estrategia`] on the peer
9762    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
9763    /// empty-clusters envelope) and the sibling
9764    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
9765    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
9766    /// the paired per-`:contratos` self-edge envelope) ctors — extended
9767    /// here onto the last unlifted `{ para: String }` one-slot
9768    /// per-`:entrada :para` phantom-reference envelope on the sibling
9769    /// per-`:entrada` slot.
9770    ///
9771    /// The `entrada: &Entrada` parameter threads verbatim from the
9772    /// caller-side `if let Some(e) = self.entrada() { … }` traversal at
9773    /// the sole in-crate wire-up site
9774    /// [`AplicacaoSpec::validate_entrada`], matching the sibling
9775    /// per-`:entrada` byte-string reads that already route through
9776    /// [`Entrada::destination`] one accessor call earlier in the same
9777    /// gate (`validate_entrada_para(e.destination())?;` +
9778    /// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
9779    /// borrow through one accessor call at the substrate primitive is
9780    /// strictly stronger than accepting the bare `&str` as a separate
9781    /// argument — a future consumer that constructs the error against a
9782    /// candidate [`Entrada`] whose [`Entrada::destination`] value the
9783    /// caller re-derives from another source (a raw `e.para` field
9784    /// access that skipped the accessor, a stale snapshot of the
9785    /// pre-normalization storage) can silently disagree with the
9786    /// storage the [`Entrada`] carries; the accessor-projected primitive
9787    /// cannot. Matches the peer
9788    /// [`AplicacaoError::placement_without_clusters`] and
9789    /// [`AplicacaoError::shard_key_on_non_sharded`]
9790    /// [`Placement`]-borrow-projection discipline on the sibling
9791    /// per-`:placement` envelope, and matches the peer
9792    /// [`AplicacaoError::contrato_self_loop`] and
9793    /// [`AplicacaoError::contrato_endpoint_not_absolute`]
9794    /// [`WitContract`]-borrow-projection discipline on the sibling
9795    /// per-`:contratos` envelope.
9796    ///
9797    /// Every future consumer that wants to construct this variant
9798    /// outside [`AplicacaoSpec::validate_entrada`] — a deferred
9799    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9800    /// webhook re-checking a `:entrada :para` overlay against a
9801    /// per-tenant `:membros` snapshot after a fleet-local overlay
9802    /// renames a member, a future `feira validate --entrada` per-caixa
9803    /// admission verb re-running the phantom-reference lookup on
9804    /// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
9805    /// `:entrada :para` whose target Servico was stripped from the
9806    /// cluster-local `:membros` overlay, a future authoring-surface
9807    /// widening the field into a `(String, Vec<Suggestion>)` pair
9808    /// carrying a "did-you-mean-<nearest-member>" hint — now reaches
9809    /// this variant through one call rather than re-inlining the
9810    /// three-line struct-literal in lockstep with the one in-crate
9811    /// wire-up site.
9812    #[must_use]
9813    pub fn entrada_member_missing(entrada: &Entrada) -> Self {
9814        Self::EntradaMemberMissing {
9815            para: entrada.destination().to_string(),
9816        }
9817    }
9818
9819    /// Construct an [`AplicacaoError::ContratoCycle`] naming the
9820    /// synchronous-`:contratos` cycle path the DFS-with-three-coloring
9821    /// sync-only-subgraph gate at
9822    /// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
9823    /// gray-arm's back-edge target through the parent chain, folding the
9824    /// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
9825    /// onto one substrate primitive so every wire-up on this variant
9826    /// reads through one dispatch rather than the pre-lift open-coded
9827    /// `AplicacaoError::ContratoCycle { cycle }` block at the sole
9828    /// in-crate wire-up site inside
9829    /// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
9830    /// return. Same substrate-primitive-projection posture as the
9831    /// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
9832    /// projecting through [`Entrada::destination`] on the peer `{ para:
9833    /// String }` one-slot per-`:entrada :para` phantom-reference
9834    /// envelope) and [`AplicacaoError::placement_without_clusters`]
9835    /// (b0d24ba, projecting through [`Placement::estrategia`] on the
9836    /// sibling `{ estrategia: PlacementStrategy }` one-slot
9837    /// per-`:placement` empty-clusters envelope) ctors — extended here
9838    /// onto the last unlifted `{ cycle: Vec<String> }` one-slot
9839    /// per-`:contratos` cross-edge sync-cycle envelope on the same
9840    /// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
9841    /// struct-literal wire-up under
9842    /// [`AplicacaoSpec::detect_sync_cycles`].
9843    ///
9844    /// The `cycle: Vec<String>` parameter threads verbatim from the
9845    /// caller-side DFS traversal's reconstructed cycle path (built up by
9846    /// walking `parent` from the gray-back-edge's source node back to
9847    /// its target, reversing, then appending the target once more so the
9848    /// first and last elements coincide by construction and the
9849    /// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
9850    /// `cycle.join(" → ")` formatter reads as a closed loop), matching
9851    /// the pre-lift open-coded body's field selection exactly. Taking
9852    /// the owned [`Vec<String>`] rather than a borrowed slice + collect
9853    /// on the ctor side keeps the pre-lift wire-up byte-identical (the
9854    /// caller already owns the reconstructed [`Vec<String>`] at the
9855    /// gray-arm return, so no per-arm re-allocation lands on the ctor
9856    /// path).
9857    ///
9858    /// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
9859    /// families on the same [`AplicacaoError`] type — same "one typed
9860    /// dispatch on the substrate primitive, thin projections at each
9861    /// consumer" discipline extended here onto the last unlifted
9862    /// per-`:contratos` cross-edge cycle envelope inside
9863    /// [`AplicacaoSpec::detect_sync_cycles`].
9864    ///
9865    /// Every future consumer that wants to construct this variant
9866    /// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
9867    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9868    /// webhook re-checking a per-tenant `:contratos` overlay's
9869    /// sync-cycle invariant after a fleet-local overlay adds or removes
9870    /// a synchronous edge, a future `feira validate --contratos`
9871    /// per-caixa admission verb re-running the cross-edge cycle detector
9872    /// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
9873    /// #3 acknowledges (whose per-edge patch mutates one `:contratos`
9874    /// entry and needs to re-probe *just* the cycle invariant against
9875    /// the post-patch adjacency), a future authoring-surface widening
9876    /// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
9877    /// the per-hop WIT shape for a richer "break here" hint — now
9878    /// reaches this variant through one call rather than re-inlining the
9879    /// open-coded struct-literal in lockstep with the one in-crate
9880    /// wire-up site.
9881    #[must_use]
9882    pub fn contrato_cycle(cycle: Vec<String>) -> Self {
9883        Self::ContratoCycle { cycle }
9884    }
9885
9886    /// Construct an [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
9887    /// naming the offending `:politicas :circuit-breaker :window` and
9888    /// the paired `:politicas :timeout` scalars under the first-firing
9889    /// cross-axis-violation gate at
9890    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
9891    /// `window` slot through the [`CircuitBreaker::window`] scalar
9892    /// accessor on the substrate primitive.
9893    ///
9894    /// Folds the uniform `{ window: cb.window(), timeout: t }`
9895    /// two-slot `Copy`-`Duration` struct-literal onto one substrate
9896    /// primitive so every wire-up on this variant reads through one
9897    /// dispatch rather than the pre-lift four-line struct-literal
9898    /// block. The `cb` borrow threads verbatim from the caller-side
9899    /// `if let (Some(t), Some(cb)) = (self.timeout(),
9900    /// self.circuit_breaker())` pair-destructure at the sole in-crate
9901    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
9902    /// window-below-timeout arm; `timeout` threads verbatim from the
9903    /// paired [`MeshPolicy::timeout`] accessor return already
9904    /// destructured out of the same `if let` pair. `const fn`
9905    /// preserves the pre-lift `Copy`-pass-through's zero-runtime-work
9906    /// property verbatim (both fields are [`Duration`], the
9907    /// [`CircuitBreaker::window`] accessor is itself `const fn`, and
9908    /// no `.to_string()` / `.into()` allocation lands on the ctor
9909    /// path).
9910    ///
9911    /// The `window` slot is projected through [`CircuitBreaker::window`]
9912    /// (not spelled out as a bare `Duration` parameter) so a future
9913    /// widening of the `:circuit-breaker :window` axis — a
9914    /// per-`:contratos`-edge `:circuit-breaker :window` override the
9915    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a promotion of
9916    /// the plain [`Duration`] window to a richer per-status-class
9917    /// window tuple once Envoy's `outlier_detection.interval` peers
9918    /// come into scope — reaches the diagnostic through one accessor
9919    /// swap rather than every wire-up in lockstep, matching the peer
9920    /// substrate-primitive-projection posture of
9921    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
9922    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
9923    /// the sibling `{ caixa: String, wit: String }` two-slot
9924    /// per-`:contratos` self-edge envelope),
9925    /// [`AplicacaoError::entrada_member_missing`] (deeae5c, projecting
9926    /// through [`Entrada::destination`] on the sibling `{ para: String }`
9927    /// one-slot per-`:entrada :para` phantom-reference envelope), and
9928    /// [`AplicacaoError::shard_key_on_non_sharded`] (14bafca, projecting
9929    /// through [`Placement::estrategia`] on the sibling `{ estrategia:
9930    /// PlacementStrategy, shard_key: String }` two-slot per-`:placement`
9931    /// envelope) ctors carry on the sibling `:contratos` / `:entrada`
9932    /// / `:placement` envelopes.
9933    ///
9934    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
9935    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
9936    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
9937    /// [`MeshPolicy::validate`] gate — extended here onto the
9938    /// first-firing cross-axis compound variant, whose multi-slot
9939    /// `{ window: Duration, timeout: Duration }` shape does not fit
9940    /// that macro's one-`Copy`-scalar-per-variant arity. The three
9941    /// remaining cross-axis variants
9942    /// ([`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] on
9943    /// the four-slot `{ rate, rl_window, max_failures, cb_window }`
9944    /// envelope, [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
9945    /// on the two-slot `{ retries, max_failures }` envelope, and
9946    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
9947    /// two-slot `{ retries, rate }` envelope) each carry a distinct
9948    /// substrate-primitive-projection shape and are folded on their
9949    /// own axis by their own per-variant ctors as those wire-ups are
9950    /// lifted.
9951    ///
9952    /// Every future consumer that wants to construct this variant
9953    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
9954    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9955    /// webhook re-checking a per-tenant `:politicas` overlay's
9956    /// window-vs-timeout cross-axis invariant after a cluster-local
9957    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
9958    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
9959    /// future per-`:contratos`-edge `:politicas` override the M4 CR
9960    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
9961    /// projecting a per-tenant per-axis ceiling into the same
9962    /// diagnostic shape — now reaches this variant through one call
9963    /// rather than re-inlining the open-coded struct-literal in
9964    /// lockstep with the one in-crate wire-up site.
9965    #[must_use]
9966    pub const fn policy_breaker_window_below_timeout(
9967        cb: &CircuitBreaker,
9968        timeout: Duration,
9969    ) -> Self {
9970        Self::PolicyBreakerWindowBelowTimeout {
9971            window: cb.window(),
9972            timeout,
9973        }
9974    }
9975
9976    /// Construct an [`AplicacaoError::ContratoCaixaInvalid`] naming the
9977    /// offending `:contratos <slot>` (`:de` / `:para`) and the value
9978    /// that broke the shared DNS-1123-label floor under the given
9979    /// `reason`. Folds the uniform `Self::ContratoCaixaInvalid { slot,
9980    /// caixa: caixa.to_string(), reason: reason.into() }` three-slot
9981    /// struct-literal onto one substrate primitive so every wire-up on
9982    /// this variant reads through one dispatch rather than the pre-lift
9983    /// six-line struct-literal block inside
9984    /// [`validate_contrato_caixa`]'s
9985    /// [`crate::render::require_valid_dns_1123_label`]
9986    /// `|reason| …` closure.
9987    ///
9988    /// Sibling of the per-axis [`aplicacao_field_reason_ctors!`]
9989    /// (981060b) macro-generated ctor family
9990    /// ([`AplicacaoError::membro_caixa_invalid`],
9991    /// [`AplicacaoError::entrada_para_invalid`],
9992    /// [`AplicacaoError::entrada_host_invalid`],
9993    /// [`AplicacaoError::entrada_path_invalid`],
9994    /// [`AplicacaoError::placement_cluster_invalid`],
9995    /// [`AplicacaoError::placement_affinity_invalid`],
9996    /// [`AplicacaoError::shard_key_invalid`]) — extends the "one typed
9997    /// dispatch per substrate primitive on every `{ <field>: String,
9998    /// reason: String }` per-axis parser-shaped envelope" discipline
9999    /// onto the sole unlifted three-slot `{ slot: &'static str, caixa:
10000    /// String, reason: String }` sibling whose extra `slot: &'static
10001    /// str` axis-tag distinguishes the two-arm `:de` / `:para` cascade
10002    /// on the per-`:contratos`-edge value axis and so does not fit the
10003    /// two-slot macro's arity.
10004    ///
10005    /// `slot` carries the kebab-case `:de` / `:para` tag verbatim
10006    /// (`&'static str` is `Copy`, no allocation), matching the caller-
10007    /// side [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
10008    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
10009    /// sole in-crate wire-up threads through. `reason: impl
10010    /// Into<String>` accepts both `&str` literals and the shared
10011    /// [`crate::render::require_valid_dns_1123_label`]-delivered
10012    /// owned-`String` return verbatim so the closure picks the ctor up
10013    /// without a per-arm wrapper transformation, matching the peer
10014    /// [`aplicacao_field_reason_ctors!`] family's `reason: impl
10015    /// Into<String>` bound. `#[must_use]` fires a compile warning at
10016    /// any wire-up that mistakenly discards the constructed error
10017    /// rather than routing it through `return Err(…)` / `.map_err(…)`
10018    /// / a closure return.
10019    ///
10020    /// Every future consumer that wants to construct this variant
10021    /// outside the current in-crate wire-up (the deferred
10022    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
10023    /// per-`:contratos`-edge admission validator projecting the same
10024    /// diagnostic through the caller-facing `slot: &'static str` tag,
10025    /// a future `feira validate --contratos` per-caixa admission verb,
10026    /// an M4 per-`:contratos`-edge pre-emitter running the same
10027    /// DNS-1123-label floor against a caller-supplied `:de` / `:para`
10028    /// pair before hitting the apiserver-side selector, an M4
10029    /// per-cluster contrato-cap resolver rejecting a cross-tenant
10030    /// selector projection into the same diagnostic shape) — now
10031    /// reaches this variant through one call rather than re-inlining
10032    /// the six-line struct-literal block in lockstep with the one
10033    /// in-crate wire-up site.
10034    #[must_use]
10035    pub fn contrato_caixa_invalid(
10036        slot: &'static str,
10037        caixa: &str,
10038        reason: impl Into<String>,
10039    ) -> Self {
10040        Self::ContratoCaixaInvalid {
10041            slot,
10042            caixa: caixa.to_string(),
10043            reason: reason.into(),
10044        }
10045    }
10046}
10047
10048// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
10049// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
10050// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
10051// substrate-primitive family per typed variant — the paired
10052// `{ <field>: String, reason: String }` two-slot sibling on
10053// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
10054// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
10055// `ContratoMissingTarget`) and the peer two-slot
10056// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
10057// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
10058// on the sibling per-`:contratos` envelopes, plus the peer four-family
10059// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
10060// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
10061// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
10062// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
10063// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
10064// sibling layout-side envelope.
10065//
10066// Every one of the seven wire-up sites — six under the per-axis
10067// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
10068// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
10069// on `EntradaParaInvalid`, `validate_placement_cluster` on
10070// `PlacementClusterInvalid`, `validate_placement_affinity` on
10071// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
10072// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
10073// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
10074// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
10075// sites at [`validate_entrada_host`] (17dd504 already folded onto the
10076// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
10077// the macro-generated ctor of the same name), opened the identical
10078// four-line `AplicacaoError::<Variant>Invalid
10079// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
10080// the local `<field>: &str` argument — the exact "same block re-inlined
10081// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
10082// same altitude the peer three `AplicacaoError` constructor families
10083// and the four peer `LayoutError` constructor families each closed on
10084// their sibling envelopes.
10085//
10086// The macro below generates one `#[must_use]` inherent constructor per
10087// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
10088// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
10089// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
10090// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
10091// pre-lift struct-literal on the same `(<field>, reason)` pair. The
10092// uniform two-field construction (`<field>: <val>.to_string()`,
10093// `reason: reason.into()`) is spelled once — inside the macro — rather
10094// than at every wire-up site. The `reason: impl Into<String>` bound
10095// accepts both `&str` literals (with or without a trailing
10096// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
10097// wire-up site changes its per-arm diagnostic shape at the lift.
10098// `#[must_use]` fires a compile warning at any wire-up that mistakenly
10099// discards the constructed error rather than routing it through
10100// `return Err(…)` / `.map_err(…)` / a closure return.
10101//
10102// Every future consumer that wants to construct one of these seven
10103// variants outside the current in-crate wire-up sites (the deferred
10104// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
10105// admission validators, a future `feira validate --<axis>` per-caixa
10106// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
10107// on `:entrada :host`, an M4 typed placement-engine per-cluster /
10108// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
10109// per-path pre-emitter) reaches the variant through one call rather
10110// than re-inlining the four-line struct-literal block in lockstep with
10111// the current in-crate wire-up sites.
10112macro_rules! aplicacao_field_reason_ctors {
10113    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
10114        impl AplicacaoError {
10115            $(
10116                #[doc = concat!(
10117                    "Construct an [`AplicacaoError::",
10118                    stringify!($variant),
10119                    "`] naming the offending `",
10120                    stringify!($field),
10121                    "` under the given `reason`. Folds the uniform ",
10122                    "`{ ",
10123                    stringify!($field),
10124                    ": ",
10125                    stringify!($field),
10126                    ".to_string(), reason: reason.into() }` two-slot ",
10127                    "construction onto one substrate primitive so every ",
10128                    "wire-up on this variant reads through one dispatch ",
10129                    "rather than the pre-lift four-line struct-literal ",
10130                    "block. `reason` accepts both `&str` literals and ",
10131                    "`format!(…)` outputs through the `impl Into<String>` ",
10132                    "bound."
10133                )]
10134                #[must_use]
10135                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
10136                    Self::$variant {
10137                        $field: $field.to_string(),
10138                        reason: reason.into(),
10139                    }
10140                }
10141            )*
10142        }
10143    };
10144}
10145
10146aplicacao_field_reason_ctors! {
10147    membro_caixa_invalid => MembroCaixaInvalid { caixa },
10148    entrada_para_invalid => EntradaParaInvalid { para },
10149    entrada_host_invalid => EntradaHostInvalid { host },
10150    entrada_path_invalid => EntradaPathInvalid { path },
10151    placement_cluster_invalid => PlacementClusterInvalid { cluster },
10152    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
10153    shard_key_invalid => ShardKeyInvalid { shard_key },
10154}
10155
10156// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
10157// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
10158// [`WitContract::target`] onto one substrate-primitive family per typed
10159// variant — the paired `{ de: String, para: String, <field>: String,
10160// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
10161// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
10162// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
10163// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
10164// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
10165// `ContratoSlotEmpty`), and the peer two-slot
10166// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
10167// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
10168// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
10169// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
10170// sibling `AplicacaoError` envelopes, plus the peer four-family
10171// `LayoutError` ctor set on the sibling layout-side envelope.
10172//
10173// Every one of the four wire-up sites — four per-`:contratos` value-
10174// shape gates inside [`WitContract::target`] (the world-ref prefix
10175// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
10176// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
10177// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
10178// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
10179// failure on `:slot`) — opened the identical five-line
10180// `let (de, para) = self.edge_pair();
10181// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
10182// <field>: <val>.to_string(), reason });` block against the local
10183// [`WitContract::edge_pair`] composite-projection accessor and the
10184// per-arm `<val>: &str` argument — the exact "same block re-inlined at
10185// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
10186// altitude the peer three `AplicacaoError` constructor families and the
10187// four peer `LayoutError` constructor families each closed on their
10188// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
10189// macro closes the last unlifted `{ de, para, <field>: String, reason:
10190// String }` four-slot envelope inside `impl WitContract`, so every
10191// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
10192// reads through this one substrate primitive.
10193//
10194// The macro below generates one `#[must_use]` inherent constructor per
10195// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
10196// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
10197// sites onto one dispatch per arm:
10198// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
10199// byte-equal to the pre-lift struct-literal on the same
10200// `(edge_pair, <val>, reason)` triple. The uniform four-field
10201// construction (`de, para` pair-destructure onto same-named fields +
10202// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
10203// once — inside the macro — rather than at every wire-up site. The
10204// `reason: impl Into<String>` bound accepts both `&str` literals and
10205// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
10206// diagnostic shape at the lift, matching the peer
10207// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
10208// envelope. `#[must_use]` fires a compile warning at any wire-up that
10209// mistakenly discards the constructed error.
10210//
10211// Every future consumer that wants to construct one of these four
10212// variants outside [`WitContract::target`] (a deferred
10213// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
10214// admission validator raising per-payload value-shape diagnostics on
10215// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
10216// future `feira validate --contratos` per-caixa admission verb, an M4
10217// typed WIT-registry-driven per-arm pre-emitter probing each declared
10218// `:endpoint` / `:subject` / `:slot` payload against a canonical
10219// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
10220// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
10221// pre-emitter probing each `:endpoint` against the same shared
10222// HTTPPathMatch grammar) reaches the variant through one call rather
10223// than re-inlining the five-line pair-destructure + struct-literal
10224// block in lockstep with the four in-crate wire-up sites.
10225macro_rules! contrato_pair_value_reason_ctors {
10226    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
10227        impl AplicacaoError {
10228            $(
10229                #[doc = concat!(
10230                    "Construct an [`AplicacaoError::",
10231                    stringify!($variant),
10232                    "`] naming the offending edge `(de, para)` pair, the ",
10233                    "per-payload `",
10234                    stringify!($field),
10235                    "` value, and the parser-shaped `reason`. Folds the ",
10236                    "uniform `{ de, para, ",
10237                    stringify!($field),
10238                    ": ",
10239                    stringify!($field),
10240                    ".to_string(), reason: reason.into() }` four-slot ",
10241                    "construction onto one substrate primitive so every ",
10242                    "wire-up on this variant reads through one dispatch ",
10243                    "rather than the pre-lift five-line pair-destructure ",
10244                    "+ struct-literal block. The `edge` pair threads ",
10245                    "verbatim from [`WitContract::edge_pair`] at the ",
10246                    "call site; `reason` accepts both `&str` literals ",
10247                    "and `format!(…)` outputs through the `impl ",
10248                    "Into<String>` bound."
10249                )]
10250                #[must_use]
10251                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
10252                    let (de, para) = edge;
10253                    Self::$variant {
10254                        de,
10255                        para,
10256                        $field: $field.to_string(),
10257                        reason: reason.into(),
10258                    }
10259                }
10260            )*
10261        }
10262    };
10263}
10264
10265contrato_pair_value_reason_ctors! {
10266    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
10267    contrato_subject_invalid => ContratoSubjectInvalid { subject },
10268    contrato_slot_invalid => ContratoSlotInvalid { slot },
10269    contrato_wit_invalid => ContratoWitInvalid { wit },
10270}
10271
10272// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
10273// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
10274// caixa-only struct-variant wire-up sites at
10275// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
10276// `:contratos :para` arms of `ContratoMemberMissing`),
10277// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
10278// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
10279// and [`validate_no_self_membership`] (one site, the parent-`:nome`
10280// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
10281// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
10282// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
10283// three variants on `{ caixa: String }` at
10284// [`crate::SupervisorSpec::validate_children`] and
10285// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
10286// `SupervisorError` envelope, extending the same "one substrate primitive per
10287// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
10288// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
10289// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
10290// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
10291// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
10292// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
10293// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
10294// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
10295// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
10296// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
10297// variants on `{ nome, caminho }`), and
10298// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
10299// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
10300// peer three `AplicacaoError` sub-family folds already lifted here
10301// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
10302// [`aplicacao_field_reason_ctors!`] 981060b,
10303// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
10304// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
10305// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
10306// [`crate::LayoutError::missing_entry`] 1b09f9d,
10307// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
10308// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
10309//
10310// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
10311// at the per-`:contratos :de`/`:para` unknown-member arms, one on
10312// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
10313// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
10314// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
10315// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
10316// three-line struct-literal against a caller-side `&str` — the exact "same
10317// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
10318// bug, on the same altitude the peer `SupervisorError` /
10319// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
10320// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
10321// their sibling envelopes. The four variants share one `{ caixa: String }`
10322// shape, so the fold routes each wire-up site through one dispatch per typed
10323// variant.
10324//
10325// The macro below generates one `#[must_use]` inherent constructor per
10326// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
10327// wire-up site collapses onto one dispatch:
10328// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
10329// on the same `&str` fixture. The uniform one-field construction
10330// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
10331// than at every wire-up site. Every constructor is `#[must_use]` so a caller
10332// who mistakenly discards the constructed error trips a compile warning at
10333// the wire-up site.
10334//
10335// Every future consumer that wants to construct one of these four variants
10336// outside the current in-crate wire-up sites — a deferred
10337// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
10338// re-checking one added/renamed `:membros` entry against the sibling
10339// `:contratos` graph, a future `feira validate --membros` per-caixa admission
10340// verb re-checking each declared `:membros` entry's `:caixa` name against the
10341// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
10342// duplicate / self-referencing / unknown-membered `:contratos` entry against
10343// a cluster-local snapshot the M4 CR materializer projects — now reaches each
10344// variant through one call rather than re-inlining the three-line
10345// struct-literal in lockstep with the five in-crate wire-up sites.
10346macro_rules! aplicacao_caixa_only_ctors {
10347    ($($ctor:ident => $variant:ident),* $(,)?) => {
10348        impl AplicacaoError {
10349            $(
10350                #[doc = concat!(
10351                    "Construct an [`AplicacaoError::",
10352                    stringify!($variant),
10353                    "`] naming the offending `:membros :caixa` (or ",
10354                    "parent `:nome`, on the self-membership arm; or ",
10355                    "`:contratos :de`/`:para`, on the unknown-member ",
10356                    "arm). Folds the uniform `Self::",
10357                    stringify!($variant),
10358                    " { caixa: caixa.to_string() }` one-field ",
10359                    "struct-literal onto one substrate primitive so ",
10360                    "every wire-up on this variant reads through one ",
10361                    "dispatch rather than the pre-lift three-line ",
10362                    "open-coded struct-literal block."
10363                )]
10364                #[must_use]
10365                pub fn $ctor(caixa: &str) -> Self {
10366                    Self::$variant { caixa: caixa.to_string() }
10367                }
10368            )*
10369        }
10370    };
10371}
10372
10373aplicacao_caixa_only_ctors! {
10374    contrato_member_missing => ContratoMemberMissing,
10375    membro_versao_empty => MembroVersaoEmpty,
10376    membro_duplicate => MembroDuplicate,
10377    membro_is_self_aplicacao => MembroIsSelfAplicacao,
10378}
10379
10380// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
10381// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
10382// sites onto one substrate-primitive family per typed variant — the direct
10383// per-`:entrada :paths` value-shape sibling of the peer
10384// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
10385// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
10386// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
10387// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
10388// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
10389// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
10390// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
10391// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
10392// `:deps` envelope — every single-`String`-slot error family in caixa-core
10393// now reaches through one substrate primitive per typed variant.
10394//
10395// The three wire-up sites — one under [`validate_entrada_path`]'s
10396// leading-slash grammar arm (`EntradaPathNotAbsolute` against
10397// `path: &str`), one under the per-`:entrada :paths` loop's identical
10398// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
10399// and one under the per-`:entrada :paths` loop's dedup arm
10400// (`EntradaPathDuplicate` against the same `&String` via
10401// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
10402// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
10403// three-line struct-literal against a caller-side `&str` / `&String`, the
10404// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
10405// names as a bug. Every one of the compile-time guarantees in
10406// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
10407// start with `/` becomes a caixa-build error, not a Gateway API webhook
10408// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
10409// becomes a caixa-build error, not a silent last-writer-wins render) now
10410// routes through one dispatch per typed variant at every emit site.
10411//
10412// The macro below generates one `#[must_use]` inherent constructor per
10413// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
10414// every wire-up site onto one dispatch:
10415// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
10416// on the same `&str` fixture) or the `&String` sites through
10417// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
10418// construction (`path: path.to_string()`) is spelled once — inside the
10419// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
10420// a caller who mistakenly discards the constructed error trips a compile
10421// warning at the wire-up site.
10422//
10423// Every future consumer that wants to construct one of these two variants
10424// outside the current in-crate wire-up sites — a deferred
10425// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
10426// per-`:entrada :paths` re-check against a cluster-local Gateway API
10427// snapshot, a future `feira validate --entrada` per-caixa admission verb
10428// re-checking each declared `:paths` entry against the same axes, a
10429// per-tenant per-`Aplicacao` overlay resolver rejecting a
10430// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
10431// snapshot the M4 CR materializer projects — now reaches each variant
10432// through one call rather than re-inlining the three-line struct-literal in
10433// lockstep with the three in-crate wire-up sites.
10434macro_rules! aplicacao_path_only_ctors {
10435    ($($ctor:ident => $variant:ident),* $(,)?) => {
10436        impl AplicacaoError {
10437            $(
10438                #[doc = concat!(
10439                    "Construct an [`AplicacaoError::",
10440                    stringify!($variant),
10441                    "`] naming the offending `:entrada :paths` entry. ",
10442                    "Folds the uniform `Self::",
10443                    stringify!($variant),
10444                    " { path: path.to_string() }` one-field ",
10445                    "struct-literal onto one substrate primitive so ",
10446                    "every wire-up on this variant reads through one ",
10447                    "dispatch rather than the pre-lift three-line ",
10448                    "open-coded struct-literal block."
10449                )]
10450                #[must_use]
10451                pub fn $ctor(path: &str) -> Self {
10452                    Self::$variant { path: path.to_string() }
10453                }
10454            )*
10455        }
10456    };
10457}
10458
10459aplicacao_path_only_ctors! {
10460    entrada_path_not_absolute => EntradaPathNotAbsolute,
10461    entrada_path_duplicate => EntradaPathDuplicate,
10462}
10463
10464// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
10465// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
10466// substrate-primitive family per typed variant — the per-`:politicas` copy-
10467// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
10468// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
10469// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
10470// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
10471// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
10472// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
10473// the `String`-slot axis, and the peer per-`:politicas` cross-axis
10474// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
10475// carries at line 3064 on the same M3 mesh envelope.
10476//
10477// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
10478// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
10479// { <slot> }` one-line struct-literal closure against the caller-side
10480// `<slot>: <ty>` argument that the shared
10481// [`crate::render::require_positive_bounded_u32`] /
10482// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
10483// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
10484// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
10485// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
10486// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
10487// on line 3211) — the exact "same one-line struct-literal re-inlined at every
10488// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
10489// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
10490// been folded onto a substrate primitive.
10491//
10492// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
10493// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
10494// collapsing every wire-up onto either one direct dispatch
10495// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
10496// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
10497// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
10498// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
10499// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
10500// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
10501// constructor with matching arity and signature. The `const fn` qualifier
10502// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
10503// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
10504// per-variant `$field:ident` axis re-uses the enum's canonical field name so
10505// the generated ctor's parameter name matches every wire-up's local binding
10506// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
10507// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
10508// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
10509// warning at any wire-up that mistakenly discards the constructed error, on
10510// the same footing as every sibling `AplicacaoError` / `DepError` /
10511// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
10512// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
10513// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
10514// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
10515//
10516// Every future consumer that wants to construct one of these eight variants
10517// outside [`MeshPolicy::validate`] — a deferred
10518// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
10519// checking each `:politicas` axis against a cluster-local `:politicas` cap
10520// overlay, a future per-`:contratos`-edge `:politicas` override the
10521// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
10522// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
10523// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
10524// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
10525// a future `feira validate --politicas` per-caixa admission verb re-checking
10526// each declared per-axis value against the same bounds — now reaches each
10527// variant through one call rather than re-inlining the one-line struct-
10528// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
10529// which is exactly the invariant every prior ctor-macro lift already closed
10530// on its sibling envelope. Closes the last remaining per-`:politicas`
10531// per-axis `AplicacaoError` variant family that had not yet been folded onto
10532// a substrate primitive; the compound cross-axis variants
10533// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
10534// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
10535// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
10536macro_rules! aplicacao_policy_scalar_ctors {
10537    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
10538        impl AplicacaoError {
10539            $(
10540                #[doc = concat!(
10541                    "Construct an [`AplicacaoError::",
10542                    stringify!($variant),
10543                    "`] naming the offending per-`:politicas` `",
10544                    stringify!($field),
10545                    "` scalar. Folds the uniform `Self::",
10546                    stringify!($variant),
10547                    " { ",
10548                    stringify!($field),
10549                    " }` one-field `Copy`-pass-through struct-literal onto ",
10550                    "one substrate primitive so every per-axis wire-up on ",
10551                    "this variant reads through one dispatch — as a direct ",
10552                    "call (`AplicacaoError::",
10553                    stringify!($ctor),
10554                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
10555                    "the same `Copy`-`",
10556                    stringify!($ty),
10557                    "` fixture) or as a bare function pointer in the ",
10558                    "`impl FnOnce(",
10559                    stringify!($ty),
10560                    ") -> AplicacaoError` bracket-closure slot every ",
10561                    "`crate::render::require_positive_bounded_*` / ",
10562                    "`crate::render::require_positive_canonical_bounded_*` ",
10563                    "gate carries — rather than the pre-lift open-coded ",
10564                    "one-line closure over the same one-field struct-",
10565                    "literal. `const fn` preserves the `Copy`-pass-through's ",
10566                    "zero-runtime-work property verbatim."
10567                )]
10568                #[must_use]
10569                pub const fn $ctor($field: $ty) -> Self {
10570                    Self::$variant { $field }
10571                }
10572            )*
10573        }
10574    };
10575}
10576
10577aplicacao_policy_scalar_ctors! {
10578    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
10579    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
10580    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
10581    policy_breaker_max_failures_exceeds_cap =>
10582        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
10583    policy_breaker_window_not_canonical =>
10584        PolicyBreakerWindowNotCanonical { window: Duration },
10585    policy_breaker_window_exceeds_cap =>
10586        PolicyBreakerWindowExceedsCap { window: Duration },
10587    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
10588    policy_rate_limit_window_not_canonical =>
10589        PolicyRateLimitWindowNotCanonical { window: Duration },
10590}
10591
10592#[cfg(test)]
10593mod tests {
10594    use super::*;
10595
10596    fn membro(name: &str, ver: &str) -> Membro {
10597        Membro {
10598            caixa: name.into(),
10599            versao: ver.into(),
10600        }
10601    }
10602
10603    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
10604        WitContract {
10605            de: de.into(),
10606            para: para.into(),
10607            wit: "wasi:http/proxy".into(),
10608            endpoint: Some(ep.into()),
10609            subject: None,
10610            slot: None,
10611        }
10612    }
10613
10614    fn three_member_spec() -> AplicacaoSpec {
10615        AplicacaoSpec {
10616            membros: vec![
10617                membro("catalog", "^0.1"),
10618                membro("cart", "^0.1"),
10619                membro("payment", "^0.2"),
10620            ],
10621            contratos: vec![
10622                contract_http("cart", "catalog", "/products/:id"),
10623                contract_http("cart", "payment", "/charge"),
10624            ],
10625            politicas: MeshPolicy {
10626                timeout: Some(Duration::from_secs(30)),
10627                retries: Some(3),
10628                mtls_required: Some(true),
10629                ..Default::default()
10630            },
10631            placement: Placement {
10632                estrategia: PlacementStrategy::Replicated,
10633                clusters: vec!["rio".into(), "mar".into()],
10634                affinity: Some("data-locality".into()),
10635                shard_key: None,
10636            },
10637            entrada: Some(Entrada {
10638                host: "checkout.quero.cloud".into(),
10639                para: "cart".into(),
10640                paths: vec!["/api/cart".into(), "/api/products".into()],
10641                port: 8080,
10642            }),
10643        }
10644    }
10645
10646    #[test]
10647    fn happy_path_validates() {
10648        three_member_spec().validate().unwrap();
10649    }
10650
10651    #[test]
10652    fn rejects_empty_membros() {
10653        let mut s = three_member_spec();
10654        s.membros = vec![];
10655        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
10656    }
10657
10658    #[test]
10659    fn rejects_empty_membro_caixa() {
10660        // A `:caixa ""` entry has no name to render into programs.yaml
10661        // and no caixa.lisp to resolve at lacre time.
10662        let mut s = three_member_spec();
10663        s.membros[1].caixa = String::new();
10664        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
10665    }
10666
10667    #[test]
10668    fn rejects_empty_membro_versao() {
10669        // A `:versao ""` entry can't pin a semver constraint, so the
10670        // lacre pipeline fails far from the source.
10671        let mut s = three_member_spec();
10672        s.membros[2].versao = String::new();
10673        let err = s.validate().unwrap_err();
10674        assert!(
10675            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
10676            "got {err:?}"
10677        );
10678    }
10679
10680    #[test]
10681    fn rejects_duplicate_membro_caixa() {
10682        // Two `:membros` entries with the same `:caixa` collapse to one
10683        // node in the membership HashSet, which masks `:contratos`
10684        // membership errors and produces duplicate programs.yaml entries.
10685        let mut s = three_member_spec();
10686        s.membros.push(membro("cart", "^0.2"));
10687        let err = s.validate().unwrap_err();
10688        assert!(
10689            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
10690            "got {err:?}"
10691        );
10692    }
10693
10694    #[test]
10695    fn rejects_invalid_membro_versao_requirement() {
10696        // The fail-before-pass-after pin: a non-empty but malformed
10697        // semver requirement (`"^bad-version"`) silently passed
10698        // `validate()` on every pre-gate codebase because the prior
10699        // shape only refused the empty string. The parse failure
10700        // surfaced far downstream at lacre-resolve time with a
10701        // `semver::Error` that didn't name which `:membros` entry
10702        // carried the typo. The new gate moves the check to caixa-build
10703        // time at the source caixa.lisp.
10704        let mut s = three_member_spec();
10705        s.membros[2].versao = "^bad-version".into();
10706        let err = s.validate().unwrap_err();
10707        assert!(
10708            matches!(
10709                err,
10710                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10711                    if caixa == "payment" && versao == "^bad-version"
10712            ),
10713            "got {err:?}"
10714        );
10715    }
10716
10717    #[test]
10718    fn rejects_membro_versao_with_double_caret_typo() {
10719        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
10720        // Cargo-shaped requirement on first glance but fails the parser
10721        // because semver doesn't accept stacked operators. Pin this
10722        // adjacent-shape footgun explicitly so a future relaxation that
10723        // accepts "looks-canonical-but-isn't" forms surfaces here.
10724        let mut s = three_member_spec();
10725        s.membros[0].versao = "^^0.1".into();
10726        let err = s.validate().unwrap_err();
10727        assert!(
10728            matches!(
10729                err,
10730                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10731                    if caixa == "catalog" && versao == "^^0.1"
10732            ),
10733            "got {err:?}"
10734        );
10735    }
10736
10737    #[test]
10738    fn rejects_membro_versao_with_v_prefixed_tag() {
10739        // `"v0.1"` is the canonical "git-tag-shape leaking into the
10740        // semver requirement slot" typo — an author copies the
10741        // publish-side git-tag string verbatim into `:versao`, but
10742        // Cargo's semver parser rejects the leading `v` (only digits +
10743        // canonical operators are valid in the major-version
10744        // position). The gate's diagnostic names which member entry
10745        // carried the v-prefix so the fix is one edit, not a grep
10746        // through every member's `:versao`. (Note: bare `x`-glob
10747        // shorthands like `^0.1.x` are *accepted* by the semver crate
10748        // as an `*` wildcard on the patch axis — they're a Cargo-side
10749        // valid shape, not a typo, so the gate intentionally lets them
10750        // through.)
10751        let mut s = three_member_spec();
10752        s.membros[1].versao = "v0.1".into();
10753        let err = s.validate().unwrap_err();
10754        assert!(
10755            matches!(
10756                err,
10757                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
10758                    if caixa == "cart" && versao == "v0.1"
10759            ),
10760            "got {err:?}"
10761        );
10762    }
10763
10764    #[test]
10765    fn accepts_canonical_membro_versao_forms() {
10766        // The four Cargo-shaped requirement forms `:deps :versao`
10767        // already accepts via `crate::parse_requirement` must pass the
10768        // membros gate without re-validating at the resolver layer.
10769        // Pin every leg so a future tightening of the canonical set
10770        // surfaces here as a test failure.
10771        for form in [
10772            "^0.1",      // caret — minor-range pin (the most common shape)
10773            "~0.1.2",    // tilde — patch-range pin
10774            "0.1.0",     // exact — single-version pin
10775            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
10776            ">=0.1, <2", // multi-range — comma-separated comparators
10777        ] {
10778            let mut s = three_member_spec();
10779            for m in &mut s.membros {
10780                m.versao = form.into();
10781            }
10782            s.validate()
10783                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
10784        }
10785    }
10786
10787    #[test]
10788    fn membro_versao_empty_takes_precedence_over_invalid() {
10789        // Order pin: the existing `MembroVersaoEmpty` diagnostic
10790        // (which doesn't try to parse) fires before the new
10791        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
10792        // `:versao` keeps its narrower error message — `parse_requirement`
10793        // would also reject `""`, but the empty-string arm is the more
10794        // self-locating diagnostic for the author.
10795        let mut s = three_member_spec();
10796        s.membros[1].versao = String::new();
10797        let err = s.validate().unwrap_err();
10798        assert!(
10799            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
10800            "got {err:?}"
10801        );
10802    }
10803
10804    #[test]
10805    fn membro_versao_invalid_fires_before_duplicate_check() {
10806        // Order pin: a malformed requirement on a non-duplicate entry
10807        // surfaces *its own* diagnostic (which names the offending
10808        // `:versao` string), even when a later entry would otherwise
10809        // collapse onto an earlier name. The per-entry shape gate runs
10810        // inline before the duplicate-key insert, parallel to
10811        // `membros_validation_runs_before_contratos_membership_check`
10812        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
10813        let mut s = three_member_spec();
10814        s.membros[0].versao = "^bad".into();
10815        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
10816        let err = s.validate().unwrap_err();
10817        assert!(
10818            matches!(
10819                err,
10820                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
10821            ),
10822            "got {err:?}"
10823        );
10824    }
10825
10826    #[test]
10827    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
10828        // The diagnostic-shape pin: the error names the offending
10829        // `:versao` value verbatim so the author can grep their
10830        // caixa.lisp without re-running the build, and carries a
10831        // non-empty `reason` from `semver::VersionReq::parse` so the
10832        // parser's own wording flows through to the diagnostic.
10833        let mut s = three_member_spec();
10834        s.membros[2].versao = "not-a-req".into();
10835        let err = s.validate().unwrap_err();
10836        let AplicacaoError::MembroVersaoInvalid {
10837            caixa,
10838            versao,
10839            reason,
10840        } = err
10841        else {
10842            panic!("expected MembroVersaoInvalid, got other variant");
10843        };
10844        assert_eq!(caixa, "payment");
10845        assert_eq!(versao, "not-a-req");
10846        assert!(
10847            !reason.is_empty(),
10848            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
10849        );
10850    }
10851
10852    #[test]
10853    fn membro_versao_invalid_runs_before_contratos_check() {
10854        // A malformed `:versao` on any member must surface its own
10855        // diagnostic (which names *which* member to fix) before any
10856        // `:contratos` membership lookup raises `ContratoMemberMissing`.
10857        // The `:contratos` gate runs after `validate_membros`, so this
10858        // is structurally guaranteed — pin it explicitly so a future
10859        // refactor that reorders the gates surfaces here.
10860        let mut s = three_member_spec();
10861        s.membros[1].versao = "^^0.1".into();
10862        // Add a contrato whose `:para` doesn't exist — would normally
10863        // raise ContratoMemberMissing at the membership lookup, but
10864        // the membros gate must fire first.
10865        s.contratos
10866            .push(contract_http("cart", "phantom", "/never-reached"));
10867        let err = s.validate().unwrap_err();
10868        assert!(
10869            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
10870            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
10871        );
10872    }
10873
10874    #[test]
10875    fn membros_validation_runs_before_contratos_membership_check() {
10876        // If `:membros` carries a duplicate, the membership-collapse
10877        // would silently accept a `:contratos :para "phantom"` so long
10878        // as some entry hashes to "phantom". Pinning order: the
10879        // duplicate-membros error fires first, regardless of whether
10880        // contratos reference real members.
10881        let mut s = three_member_spec();
10882        s.membros = vec![
10883            membro("cart", "^0.1"),
10884            membro("cart", "^0.2"),
10885            membro("catalog", "^0.1"),
10886            membro("payment", "^0.1"),
10887        ];
10888        let err = s.validate().unwrap_err();
10889        assert!(
10890            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
10891            "got {err:?}"
10892        );
10893    }
10894
10895    #[test]
10896    fn distinct_membros_validate() {
10897        // Pin the happy-path: every `:membros` entry has a non-empty
10898        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
10899        // The fixture already satisfies this; this test makes the
10900        // invariant explicit so a future refactor of the fixture can't
10901        // silently break the guarantee.
10902        three_member_spec().validate().unwrap();
10903    }
10904
10905    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
10906
10907    #[test]
10908    fn rejects_membro_caixa_with_uppercase() {
10909        // The canonical "I copied the Servico's display name verbatim"
10910        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
10911        // but author tools often round-trip a TitleCase or CamelCase
10912        // identifier from an ADR or a sketch. Pin the diagnostic names
10913        // the offending name and suggests the lower-cased fix in one
10914        // edit, mirroring the `rejects_entrada_host_with_uppercase`
10915        // gate's shape (c7d05ec).
10916        let mut s = three_member_spec();
10917        s.membros[1].caixa = "Cart".into();
10918        let err = s.validate().unwrap_err();
10919        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
10920            panic!("expected MembroCaixaInvalid, got other variant");
10921        };
10922        assert_eq!(caixa, "Cart");
10923        assert!(
10924            reason.contains("uppercase"),
10925            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
10926        );
10927        assert!(
10928            reason.contains("\"cart\""),
10929            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
10930        );
10931    }
10932
10933    #[test]
10934    fn rejects_membro_caixa_with_underscore() {
10935        // The canonical "I'm thinking of a Python module / Postgres
10936        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
10937        // label schema. K8s rejects `metadata.name: my_cart` at admission
10938        // time with an opaque `field is invalid` (no source-citing
10939        // diagnostic). The gate moves it to caixa-build time.
10940        let mut s = three_member_spec();
10941        s.membros[0].caixa = "my_cart".into();
10942        let err = s.validate().unwrap_err();
10943        assert!(
10944            matches!(
10945                err,
10946                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10947                    if caixa == "my_cart" && reason.contains('_')
10948            ),
10949            "got {err:?}"
10950        );
10951    }
10952
10953    #[test]
10954    fn rejects_membro_caixa_with_dot() {
10955        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
10956        // subdomain — even though K8s `metadata.name` itself accepts
10957        // dots (DNS-1123 subdomain rule), this string also lands as a
10958        // K8s Service name (DNS-1035 label — no dots) and as a label
10959        // value on identity-based Cilium selectors. The strictest floor
10960        // among the use sites wins. The "I want to namespace my member
10961        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
10962        let mut s = three_member_spec();
10963        s.membros[2].caixa = "team.cart".into();
10964        let err = s.validate().unwrap_err();
10965        assert!(
10966            matches!(
10967                err,
10968                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10969                    if caixa == "team.cart" && reason.contains('.')
10970            ),
10971            "got {err:?}"
10972        );
10973    }
10974
10975    #[test]
10976    fn rejects_membro_caixa_with_leading_hyphen() {
10977        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
10978        // with an alphanumeric. The K8s apiserver rejects `-cart`
10979        // outright; the renderer would emit a `metadata.name: "-cart"`
10980        // that fails admission far from the source caixa.lisp.
10981        let mut s = three_member_spec();
10982        s.membros[0].caixa = "-cart".into();
10983        let err = s.validate().unwrap_err();
10984        assert!(
10985            matches!(
10986                err,
10987                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
10988                    if caixa == "-cart" && reason.contains("start and end")
10989            ),
10990            "got {err:?}"
10991        );
10992    }
10993
10994    #[test]
10995    fn rejects_membro_caixa_with_trailing_hyphen() {
10996        // The symmetric arm of the boundary rule. Pin separately so
10997        // both ends of the label are covered against a future relaxation
10998        // that only checks one boundary.
10999        let mut s = three_member_spec();
11000        s.membros[1].caixa = "cart-".into();
11001        let err = s.validate().unwrap_err();
11002        assert!(
11003            matches!(
11004                err,
11005                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11006                    if caixa == "cart-"
11007            ),
11008            "got {err:?}"
11009        );
11010    }
11011
11012    #[test]
11013    fn rejects_membro_caixa_with_unicode() {
11014        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11015        // (`xn--…`) by the author before it reaches K8s. The byte-by-
11016        // byte ASCII validity check rejects multi-byte UTF-8 sequences
11017        // by the first byte that fails the `[a-z0-9-]` predicate.
11018        let mut s = three_member_spec();
11019        s.membros[2].caixa = "café".into();
11020        let err = s.validate().unwrap_err();
11021        assert!(
11022            matches!(
11023                err,
11024                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11025                    if caixa == "café"
11026            ),
11027            "got {err:?}"
11028        );
11029    }
11030
11031    #[test]
11032    fn rejects_membro_caixa_with_whitespace() {
11033        // Whitespace is the canonical "I pasted from a sketch / doc"
11034        // footgun. The apiserver rejects every `metadata.name` value
11035        // carrying whitespace; pin the gate fires at the right boundary.
11036        let mut s = three_member_spec();
11037        s.membros[0].caixa = "my cart".into();
11038        let err = s.validate().unwrap_err();
11039        assert!(
11040            matches!(
11041                err,
11042                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11043                    if caixa == "my cart"
11044            ),
11045            "got {err:?}"
11046        );
11047    }
11048
11049    #[test]
11050    fn rejects_membro_caixa_too_long() {
11051        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
11052        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
11053        // exactly. The gate's reason names both the cap and the actual
11054        // length so the author can shorten in one edit.
11055        let mut s = three_member_spec();
11056        let too_long = "a".repeat(64);
11057        s.membros[1].caixa = too_long.clone();
11058        let err = s.validate().unwrap_err();
11059        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11060            panic!("expected MembroCaixaInvalid");
11061        };
11062        assert_eq!(caixa, too_long);
11063        assert!(
11064            reason.contains("63") && reason.contains("64"),
11065            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
11066        );
11067    }
11068
11069    #[test]
11070    fn membro_caixa_max_length_validates() {
11071        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
11072        // so a future tightening (e.g. dropping to 62) surfaces here as
11073        // a regression, mirroring `entrada_host_max_length_validates`
11074        // (c7d05ec).
11075        let mut s = three_member_spec();
11076        s.membros[2].caixa = "a".repeat(63);
11077        s.entrada.as_mut().unwrap().para = "a".repeat(63);
11078        // remove contratos referencing the renamed member; they'd
11079        // raise ContratoMemberMissing otherwise
11080        s.contratos
11081            .retain(|c| c.de != "payment" && c.para != "payment");
11082        s.validate().unwrap();
11083    }
11084
11085    #[test]
11086    fn accepts_canonical_membro_caixa_forms() {
11087        // The DNS-1123 label shapes a caixa author is realistically
11088        // going to write: single-word lowercase, hyphen-joined, ending
11089        // in a digit-suffixed version (`cart-v2`), starting with a
11090        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
11091        // DNS-1035 which requires a letter at position 0), single-
11092        // character (`a` — boundary). Pin every leg so a future
11093        // tightening that bans (e.g.) digit-start identifiers surfaces
11094        // here.
11095        for form in [
11096            "checkout",
11097            "cart",
11098            "cart-v2",
11099            "a",
11100            "c0",
11101            "3rd-party-shim",
11102            "x-1-2-3-4",
11103        ] {
11104            let mut s = three_member_spec();
11105            // Renaming a member also requires updating downstream refs;
11106            // drop everything else and rebuild a minimal spec around
11107            // just the one renamed member.
11108            s.membros = vec![membro(form, "^0.1")];
11109            s.contratos = vec![];
11110            s.entrada = None;
11111            s.validate()
11112                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
11113        }
11114    }
11115
11116    #[test]
11117    fn membro_caixa_empty_takes_precedence_over_invalid() {
11118        // Order pin: the existing `MembroCaixaEmpty` diagnostic
11119        // (which doesn't try to parse) fires before the new
11120        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
11121        // `:caixa` keeps its narrower error message — the new gate
11122        // would also reject `""`, but the empty-string arm is the more
11123        // self-locating diagnostic for the author. Mirrors the
11124        // `entrada_host_empty_takes_precedence_over_invalid` pin
11125        // (c7d05ec).
11126        let mut s = three_member_spec();
11127        s.membros[1].caixa = String::new();
11128        let err = s.validate().unwrap_err();
11129        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
11130    }
11131
11132    #[test]
11133    fn membro_caixa_invalid_fires_before_versao_check() {
11134        // Order pin: an invalid-shape `:caixa` surfaces *its own*
11135        // diagnostic (which names the offending caixa name), even when
11136        // the same entry's `:versao` is also empty/invalid. The shape
11137        // gate runs first because the diagnostic is more self-locating —
11138        // an empty/invalid `:versao` on an invalid-shape caixa name is
11139        // a downstream-fix-after-the-caixa-rename concern.
11140        let mut s = three_member_spec();
11141        s.membros[1].caixa = "Cart".into();
11142        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
11143        let err = s.validate().unwrap_err();
11144        assert!(
11145            matches!(
11146                err,
11147                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
11148            ),
11149            "got {err:?}"
11150        );
11151    }
11152
11153    #[test]
11154    fn membro_caixa_invalid_fires_before_duplicate_check() {
11155        // Order pin: a malformed-shape `:caixa` on an earlier entry
11156        // surfaces *its own* diagnostic, even when a later entry would
11157        // otherwise collapse onto a duplicate name. The per-entry shape
11158        // gate runs inline before the duplicate-key insert, parallel
11159        // to `membro_versao_invalid_fires_before_duplicate_check`.
11160        let mut s = three_member_spec();
11161        s.membros[0].caixa = "Catalog".into();
11162        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
11163        let err = s.validate().unwrap_err();
11164        assert!(
11165            matches!(
11166                err,
11167                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
11168            ),
11169            "got {err:?}"
11170        );
11171    }
11172
11173    #[test]
11174    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
11175        // The diagnostic-shape pin: the error names the offending
11176        // `:caixa` value verbatim so the author can grep their
11177        // caixa.lisp without re-running the build, and carries a
11178        // non-empty `reason` naming the specific violation. Same
11179        // shape every typed-shape gate enshrines (c7d05ec's
11180        // `entrada_host_diagnostic_carries_offending_host`,
11181        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
11182        let mut s = three_member_spec();
11183        s.membros[2].caixa = "BAD_NAME".into();
11184        let err = s.validate().unwrap_err();
11185        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11186            panic!("expected MembroCaixaInvalid");
11187        };
11188        assert_eq!(caixa, "BAD_NAME");
11189        assert!(
11190            !reason.is_empty(),
11191            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
11192        );
11193    }
11194
11195    #[test]
11196    fn rejects_contrato_with_unknown_de() {
11197        let mut s = three_member_spec();
11198        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11199        let err = s.validate().unwrap_err();
11200        assert!(
11201            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
11202        );
11203    }
11204
11205    #[test]
11206    fn rejects_contrato_with_unknown_para() {
11207        let mut s = three_member_spec();
11208        s.contratos.push(contract_http("cart", "phantom", "/x"));
11209        let err = s.validate().unwrap_err();
11210        assert!(
11211            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
11212        );
11213    }
11214
11215    #[test]
11216    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
11217        // The read-path pin: the phantom-`:de` refusal arm's
11218        // `ContratoMemberMissing.caixa` carrier must be observed through
11219        // the lifted [`WitContract::source`] accessor, not the raw
11220        // `.de.clone()` field-access `String`-carry. Peer of the sibling
11221        // per-`:contratos` self-loop arm's `.source().to_string()` /
11222        // `.world_ref().to_string()` `String`-carry sites the earlier
11223        // convergence lifted onto the same accessor pair. A future
11224        // silent detour that reintroduced the raw `.de.clone()` at the
11225        // wrap envelope while the shape-gate and membership lookup
11226        // routed through the accessor would surface here as a byte-equal
11227        // miss between the fired diagnostic's `caixa:` field and the
11228        // offending edge's `.source()` — pinning the accessor as the
11229        // sole read path across the phantom-name refusal arm's arg +
11230        // wrap-envelope emit surface.
11231        let mut s = three_member_spec();
11232        let phantom = contract_http("phantom", "catalog", "/x");
11233        s.contratos.push(phantom.clone());
11234        let err = s.validate().unwrap_err();
11235        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
11236            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
11237        };
11238        assert_eq!(
11239            caixa,
11240            phantom.source(),
11241            "ContratoMemberMissing.caixa on the phantom-:de arm must \
11242             byte-equal WitContract::source — the wrap envelope must \
11243             route through the lifted accessor rather than the raw \
11244             .de.clone() field-access String-carry"
11245        );
11246    }
11247
11248    #[test]
11249    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
11250        // The symmetric read-path pin on the `:para` phantom-name
11251        // refusal arm — same shape as the sibling `:de` pin above but
11252        // on the callee-Servico axis. Pins the wrap envelope's
11253        // `caixa:` field is observed through the lifted
11254        // [`WitContract::destination`] accessor, not the raw
11255        // `.para.clone()` field-access `String`-carry.
11256        let mut s = three_member_spec();
11257        let phantom = contract_http("cart", "phantom", "/x");
11258        s.contratos.push(phantom.clone());
11259        let err = s.validate().unwrap_err();
11260        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
11261            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
11262        };
11263        assert_eq!(
11264            caixa,
11265            phantom.destination(),
11266            "ContratoMemberMissing.caixa on the phantom-:para arm must \
11267             byte-equal WitContract::destination — the wrap envelope \
11268             must route through the lifted accessor rather than the raw \
11269             .para.clone() field-access String-carry"
11270        );
11271    }
11272
11273    #[test]
11274    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
11275        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
11276        // refusal arm — the `validate_contrato_caixa` arg must be
11277        // observed through the lifted [`WitContract::source`] accessor,
11278        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
11279        // value routes through the shared
11280        // [`crate::render::require_valid_dns_1123_label`] floor with the
11281        // accessor-projected value; the fired
11282        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
11283        // the offending edge's `.source()`, pinning that the arg + the
11284        // downstream `caixa: caixa.to_string()` wrap route through the
11285        // same accessor's read path.
11286        let mut s = three_member_spec();
11287        let malformed = contract_http("BAD_NAME", "catalog", "/x");
11288        s.contratos.push(malformed.clone());
11289        let err = s.validate().unwrap_err();
11290        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
11291            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
11292        };
11293        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
11294        assert_eq!(
11295            caixa,
11296            malformed.source(),
11297            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
11298             byte-equal WitContract::source — the shape-gate arg + wrap \
11299             envelope must route through the lifted accessor rather \
11300             than the raw &c.de &String-borrow"
11301        );
11302    }
11303
11304    #[test]
11305    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
11306        // Symmetric arm to the sibling `:de` malformed-shape pin above,
11307        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
11308        // route through the lifted [`WitContract::destination`]
11309        // accessor. `:para` runs after the `:de` shape gate in the
11310        // canonical edge-direction order, so the `:de` value must be
11311        // well-shaped for the `:para` gate to fire — the `cart` :de is
11312        // canonical.
11313        let mut s = three_member_spec();
11314        let malformed = contract_http("cart", "BAD_NAME", "/x");
11315        s.contratos.push(malformed.clone());
11316        let err = s.validate().unwrap_err();
11317        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
11318            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
11319        };
11320        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
11321        assert_eq!(
11322            caixa,
11323            malformed.destination(),
11324            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
11325             byte-equal WitContract::destination — the shape-gate arg + \
11326             wrap envelope must route through the lifted accessor \
11327             rather than the raw &c.para &String-borrow"
11328        );
11329    }
11330
11331    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
11332
11333    #[test]
11334    fn rejects_contrato_de_empty() {
11335        // `:de ""` previously fell through to `ContratoMemberMissing`
11336        // (with `caixa: ""`) because the validated `:membros :caixa`
11337        // set never contains the empty string. The narrower
11338        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
11339        // the offending slot.
11340        let mut s = three_member_spec();
11341        s.contratos.push(contract_http("", "catalog", "/x"));
11342        let err = s.validate().unwrap_err();
11343        assert_eq!(
11344            err,
11345            AplicacaoError::ContratoCaixaEmpty {
11346                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11347            },
11348            "got {err:?}"
11349        );
11350    }
11351
11352    #[test]
11353    fn rejects_contrato_para_empty() {
11354        // Symmetric arm to `:de ""` — `:para ""` previously fell
11355        // through to `ContratoMemberMissing { caixa: "" }`.
11356        let mut s = three_member_spec();
11357        s.contratos.push(contract_http("cart", "", "/x"));
11358        let err = s.validate().unwrap_err();
11359        assert_eq!(
11360            err,
11361            AplicacaoError::ContratoCaixaEmpty {
11362                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
11363            },
11364            "got {err:?}"
11365        );
11366    }
11367
11368    #[test]
11369    fn rejects_contrato_de_with_uppercase() {
11370        // The canonical "I copied the Servico's TitleCase display
11371        // name from an ADR" typo. Until this gate landed `:de "Cart"`
11372        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
11373        // as "this caixa isn't in `:membros`" when the root cause is
11374        // "this `:de` value's shape can never legitimately match a
11375        // validated member (DNS-1123 labels are lowercase)". The
11376        // narrower diagnostic names the offending slot, the value
11377        // verbatim, and the parser-shaped reason.
11378        let mut s = three_member_spec();
11379        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11380        let err = s.validate().unwrap_err();
11381        let AplicacaoError::ContratoCaixaInvalid {
11382            slot,
11383            caixa,
11384            reason,
11385        } = err
11386        else {
11387            panic!("expected ContratoCaixaInvalid, got other variant");
11388        };
11389        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
11390        assert_eq!(caixa, "Cart");
11391        assert!(
11392            reason.contains("uppercase"),
11393            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11394        );
11395    }
11396
11397    #[test]
11398    fn rejects_contrato_para_with_underscore() {
11399        // The canonical "I'm thinking of a Python module" leak —
11400        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
11401        // Pin the `:para` axis surfaces the same diagnostic shape as
11402        // the `:de` axis on the underscore violation.
11403        let mut s = three_member_spec();
11404        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
11405        let err = s.validate().unwrap_err();
11406        assert!(
11407            matches!(
11408                err,
11409                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11410                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
11411            ),
11412            "got {err:?}"
11413        );
11414    }
11415
11416    #[test]
11417    fn rejects_contrato_de_with_dot() {
11418        // A `:contratos :de` value is a single DNS-1123 *label*, not
11419        // a subdomain — mirroring the `:membros :caixa` floor. The
11420        // strictest floor among the use sites wins.
11421        let mut s = three_member_spec();
11422        s.contratos
11423            .push(contract_http("team.cart", "catalog", "/x"));
11424        let err = s.validate().unwrap_err();
11425        assert!(
11426            matches!(
11427                err,
11428                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11429                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
11430            ),
11431            "got {err:?}"
11432        );
11433    }
11434
11435    #[test]
11436    fn rejects_contrato_para_with_unicode() {
11437        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11438        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
11439        // validity check rejects multi-byte UTF-8 by the first
11440        // non-`[a-z0-9-]` byte.
11441        let mut s = three_member_spec();
11442        s.contratos.push(contract_http("cart", "café", "/x"));
11443        let err = s.validate().unwrap_err();
11444        assert!(
11445            matches!(
11446                err,
11447                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11448                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
11449            ),
11450            "got {err:?}"
11451        );
11452    }
11453
11454    #[test]
11455    fn rejects_contrato_de_with_leading_hyphen() {
11456        // DNS-1123 boundary rule: labels must start and end with an
11457        // alphanumeric. K8s rejects `-cart` outright; the narrower
11458        // shape diagnostic now names the violation at caixa-build
11459        // time rather than the misframed membership-lookup arm.
11460        let mut s = three_member_spec();
11461        s.contratos.push(contract_http("-cart", "catalog", "/x"));
11462        let err = s.validate().unwrap_err();
11463        assert!(
11464            matches!(
11465                err,
11466                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
11467                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
11468            ),
11469            "got {err:?}"
11470        );
11471    }
11472
11473    #[test]
11474    fn contrato_de_empty_takes_precedence_over_invalid() {
11475        // Order pin: the `ContratoCaixaEmpty` arm fires before the
11476        // `ContratoCaixaInvalid` parse-side arm — same empty-first
11477        // cascade `validate_membro_caixa` / `validate_placement_cluster`
11478        // / `validate_entrada_host` already establish on their peer
11479        // name axes. The empty string is a structurally distinct
11480        // authoring footgun (the author left the field blank, vs.
11481        // typed a malformed value), so it gets its own diagnostic.
11482        let mut s = three_member_spec();
11483        s.contratos.push(contract_http("", "catalog", "/x"));
11484        let err = s.validate().unwrap_err();
11485        assert_eq!(
11486            err,
11487            AplicacaoError::ContratoCaixaEmpty {
11488                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11489            }
11490        );
11491    }
11492
11493    #[test]
11494    fn contrato_de_shape_fires_before_para_shape() {
11495        // Per-axis order pin: within one `:contratos` entry, the `:de`
11496        // shape gate fires before the `:para` shape gate — same
11497        // edge-direction order the existing `ContratoMemberMissing` /
11498        // `ContratoSelfLoop` / target-dispatch checks use, so the
11499        // diagnostic for a contract with both `:de` and `:para`
11500        // malformed is stable. Authors fixing the surfaced `:de`
11501        // first will see `:para`'s diagnostic on re-run.
11502        let mut s = three_member_spec();
11503        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
11504        let err = s.validate().unwrap_err();
11505        assert!(
11506            matches!(
11507                err,
11508                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11509                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11510            ),
11511            "got {err:?}"
11512        );
11513    }
11514
11515    #[test]
11516    fn contrato_shape_fires_before_membership_lookup() {
11517        // The load-bearing pin: an invalid-shape `:de` surfaces its
11518        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
11519        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11520        // an invalid-shape `:de` could never legitimately match any
11521        // member — the prior `ContratoMemberMissing` diagnostic was
11522        // a structural impossibility framed as a graph-membership
11523        // failure. The shape gate now routes every such input through
11524        // the narrower self-locating diagnostic.
11525        let mut s = three_member_spec();
11526        s.contratos.push(contract_http("Cart", "catalog", "/x"));
11527        let err = s.validate().unwrap_err();
11528        assert!(
11529            matches!(
11530                err,
11531                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
11532            ),
11533            "got {err:?}"
11534        );
11535        // And the symmetric case: an invalid-shape `:para` surfaces
11536        // its own diagnostic too, even when `:de` is well-shaped.
11537        let mut s = three_member_spec();
11538        s.contratos.push(contract_http("cart", "Catalog", "/x"));
11539        let err = s.validate().unwrap_err();
11540        assert!(
11541            matches!(
11542                err,
11543                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
11544            ),
11545            "got {err:?}"
11546        );
11547    }
11548
11549    #[test]
11550    fn contrato_shape_fires_before_self_edge_check() {
11551        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
11552        // bugs: the shape violation (uppercase) and the self-edge
11553        // violation. The narrower per-axis shape diagnostic surfaces
11554        // first because fixing the shape may reveal that the author
11555        // also meant to point `:para` at a different member — the
11556        // self-edge framing is only useful once both endpoints have
11557        // valid shape.
11558        let mut s = three_member_spec();
11559        s.contratos.push(contract_http("Cart", "Cart", "/x"));
11560        let err = s.validate().unwrap_err();
11561        assert!(
11562            matches!(
11563                err,
11564                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
11565                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
11566            ),
11567            "got {err:?}"
11568        );
11569    }
11570
11571    #[test]
11572    fn contrato_well_shaped_phantom_still_raises_member_missing() {
11573        // Strict-improvement pin: a well-shaped `:de` that simply
11574        // isn't in `:membros` (a phantom reference — author meant
11575        // to add the member but didn't, or renamed and missed an
11576        // update) still surfaces `ContratoMemberMissing`, unchanged.
11577        // The shape gate only intercepts inputs that could never
11578        // legitimately match a validated member; legitimately-shaped
11579        // phantom references remain on the graph-membership axis.
11580        let mut s = three_member_spec();
11581        s.contratos
11582            .push(contract_http("phantom-shim", "catalog", "/x"));
11583        let err = s.validate().unwrap_err();
11584        assert!(
11585            matches!(
11586                err,
11587                AplicacaoError::ContratoMemberMissing { ref caixa }
11588                    if caixa == "phantom-shim"
11589            ),
11590            "got {err:?}"
11591        );
11592    }
11593
11594    #[test]
11595    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
11596        // The diagnostic-shape pin: the error names the offending
11597        // slot (`:de` or `:para`) verbatim and the offending value
11598        // verbatim plus a non-empty parser-shaped reason, so the
11599        // author can grep their caixa.lisp for `:de "<name>"` /
11600        // `:para "<name>"` and fix it in one edit. Same diagnostic
11601        // shape as `MembroCaixaInvalid` (3f9d7a0) and
11602        // `PlacementClusterInvalid` (6c8c00b).
11603        let mut s = three_member_spec();
11604        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
11605        let err = s.validate().unwrap_err();
11606        let AplicacaoError::ContratoCaixaInvalid {
11607            slot,
11608            caixa,
11609            reason,
11610        } = err
11611        else {
11612            panic!("expected ContratoCaixaInvalid, got {err:?}");
11613        };
11614        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
11615        assert_eq!(caixa, "BAD_NAME");
11616        assert!(
11617            !reason.is_empty(),
11618            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
11619        );
11620    }
11621
11622    #[test]
11623    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
11624        // Scalar-value pin: the two author-facing kebab-case labels the
11625        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
11626        // admits on the `:contratos` per-entry endpoint-shape axis,
11627        // one arm per typed sub-slot. Mirrors the peer scalar-value
11628        // pin the sibling top-level M2 / M3 / Supervisor
11629        // author-facing-label consts carry
11630        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
11631        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
11632        // slot itself), so every altitude of the typed-slot algebra
11633        // shares the same "one canonical byte-string per arm"
11634        // discipline. A future rebrand (`:de` → `:from` matching the
11635        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
11636        // sibling, `:para` → `:to` matching the same, or
11637        // `:de`/`:para` → `:source`/`:target` matching the WIT
11638        // world's `import`/`export` half-vocabulary) lands as an
11639        // edit to exactly one const, and every consumer that reaches
11640        // for the label picks it up at build time rather than at
11641        // runtime as a downstream `ContratoCaixaEmpty` /
11642        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
11643        // diagnostic mismatch far from the rename's commit.
11644        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
11645        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
11646    }
11647
11648    #[test]
11649    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
11650        // Production-through-const pin: the two per-axis labels the
11651        // per-`:contratos` entry endpoint-shape gate at
11652        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
11653        // argument to [`validate_contrato_caixa`] route through the
11654        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
11655        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
11656        // future rebrand that reaches the const but not the gate (or
11657        // vice versa) surfaces here at build time rather than at
11658        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
11659        // `slot: <stale-kebab-case>` diagnostic far from the rename's
11660        // commit. Mirror of the peer
11661        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
11662        // pin (882f498) on the sibling M3 top-level slot axis.
11663        let mut s = three_member_spec();
11664        s.contratos.push(contract_http("", "catalog", "/x"));
11665        assert_eq!(
11666            s.validate().unwrap_err(),
11667            AplicacaoError::ContratoCaixaEmpty {
11668                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
11669            }
11670        );
11671        let mut s = three_member_spec();
11672        s.contratos.push(contract_http("cart", "", "/x"));
11673        assert_eq!(
11674            s.validate().unwrap_err(),
11675            AplicacaoError::ContratoCaixaEmpty {
11676                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
11677            }
11678        );
11679    }
11680
11681    #[test]
11682    fn accepts_canonical_contrato_caixa_forms() {
11683        // The DNS-1123 label shapes a caixa author is realistically
11684        // going to write on a `:contratos :de` / `:para`. Pin every
11685        // leg so a future tightening that bans (e.g.) digit-start
11686        // identifiers surfaces here, mirroring
11687        // `accepts_canonical_membro_caixa_forms` on the peer name
11688        // axis.
11689        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11690            let mut s = three_member_spec();
11691            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
11692            s.contratos = vec![contract_http("checkout", form, "/x")];
11693            s.entrada = None;
11694            s.validate().unwrap_or_else(|e| {
11695                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
11696            });
11697
11698            let mut s = three_member_spec();
11699            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11700            s.contratos = vec![contract_http(form, "catalog", "/x")];
11701            s.entrada = None;
11702            s.validate().unwrap_or_else(|e| {
11703                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
11704            });
11705        }
11706    }
11707
11708    #[test]
11709    fn rejects_empty_wit() {
11710        let mut s = three_member_spec();
11711        s.contratos.push(WitContract {
11712            de: "cart".into(),
11713            para: "catalog".into(),
11714            wit: String::new(),
11715            endpoint: None,
11716            subject: None,
11717            slot: None,
11718        });
11719        let err = s.validate().unwrap_err();
11720        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
11721    }
11722
11723    #[test]
11724    fn rejects_entrada_to_unknown_member() {
11725        let mut s = three_member_spec();
11726        s.entrada.as_mut().unwrap().para = "phantom".into();
11727        assert!(matches!(
11728            s.validate().unwrap_err(),
11729            AplicacaoError::EntradaMemberMissing { .. }
11730        ));
11731    }
11732
11733    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
11734
11735    #[test]
11736    fn rejects_entrada_para_empty() {
11737        // `:para ""` previously fell through to
11738        // `EntradaMemberMissing { para: "" }` because the validated
11739        // `:membros :caixa` set never contains the empty string. The
11740        // narrower `EntradaParaEmpty` diagnostic now names the
11741        // offending slot directly — same empty-first cascade
11742        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
11743        // `ContratoCaixaEmpty` establish on the peer name axes.
11744        let mut s = three_member_spec();
11745        s.entrada.as_mut().unwrap().para = String::new();
11746        let err = s.validate().unwrap_err();
11747        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
11748    }
11749
11750    #[test]
11751    fn rejects_entrada_para_with_uppercase() {
11752        // The canonical "I copied the Servico's TitleCase display
11753        // name from an ADR" typo. Until this gate landed `:para "Cart"`
11754        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
11755        // as "this caixa isn't in `:membros`" when the root cause is
11756        // "this `:para` value's shape can never legitimately match a
11757        // validated member (DNS-1123 labels are lowercase)". The
11758        // narrower diagnostic names the value verbatim plus the
11759        // parser-shaped reason.
11760        let mut s = three_member_spec();
11761        s.entrada.as_mut().unwrap().para = "Cart".into();
11762        let err = s.validate().unwrap_err();
11763        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
11764            panic!("expected EntradaParaInvalid, got other variant");
11765        };
11766        assert_eq!(para, "Cart");
11767        assert!(
11768            reason.contains("uppercase"),
11769            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11770        );
11771    }
11772
11773    #[test]
11774    fn rejects_entrada_para_with_underscore() {
11775        // The canonical "I'm thinking of a Python module" leak —
11776        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
11777        let mut s = three_member_spec();
11778        s.entrada.as_mut().unwrap().para = "my_cart".into();
11779        let err = s.validate().unwrap_err();
11780        assert!(
11781            matches!(
11782                err,
11783                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11784                    if para == "my_cart" && reason.contains('_')
11785            ),
11786            "got {err:?}"
11787        );
11788    }
11789
11790    #[test]
11791    fn rejects_entrada_para_with_dot() {
11792        // An `:entrada :para` value is a single DNS-1123 *label*, not
11793        // a subdomain — mirroring the `:membros :caixa` floor. The
11794        // strictest floor among the use sites wins.
11795        let mut s = three_member_spec();
11796        s.entrada.as_mut().unwrap().para = "team.cart".into();
11797        let err = s.validate().unwrap_err();
11798        assert!(
11799            matches!(
11800                err,
11801                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11802                    if para == "team.cart" && reason.contains('.')
11803            ),
11804            "got {err:?}"
11805        );
11806    }
11807
11808    #[test]
11809    fn rejects_entrada_para_with_unicode() {
11810        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11811        // (`xn--…`) before it reaches K8s.
11812        let mut s = three_member_spec();
11813        s.entrada.as_mut().unwrap().para = "café".into();
11814        let err = s.validate().unwrap_err();
11815        assert!(
11816            matches!(
11817                err,
11818                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
11819            ),
11820            "got {err:?}"
11821        );
11822    }
11823
11824    #[test]
11825    fn rejects_entrada_para_with_leading_hyphen() {
11826        // DNS-1123 boundary rule: labels must start and end with an
11827        // alphanumeric. K8s rejects `-cart` outright.
11828        let mut s = three_member_spec();
11829        s.entrada.as_mut().unwrap().para = "-cart".into();
11830        let err = s.validate().unwrap_err();
11831        assert!(
11832            matches!(
11833                err,
11834                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11835                    if para == "-cart" && reason.contains("start and end")
11836            ),
11837            "got {err:?}"
11838        );
11839    }
11840
11841    #[test]
11842    fn rejects_entrada_para_with_trailing_hyphen() {
11843        // Symmetric boundary arm.
11844        let mut s = three_member_spec();
11845        s.entrada.as_mut().unwrap().para = "cart-".into();
11846        let err = s.validate().unwrap_err();
11847        assert!(
11848            matches!(
11849                err,
11850                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11851                    if para == "cart-" && reason.contains("start and end")
11852            ),
11853            "got {err:?}"
11854        );
11855    }
11856
11857    #[test]
11858    fn rejects_entrada_para_too_long() {
11859        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
11860        // bytes per label. K8s rejects longer names at admission on
11861        // every `metadata.name` axis.
11862        let mut s = three_member_spec();
11863        s.entrada.as_mut().unwrap().para = "a".repeat(64);
11864        let err = s.validate().unwrap_err();
11865        assert!(
11866            matches!(
11867                err,
11868                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
11869                    if para.len() == 64 && reason.contains("max length")
11870            ),
11871            "got {err:?}"
11872        );
11873    }
11874
11875    #[test]
11876    fn entrada_para_empty_takes_precedence_over_invalid() {
11877        // Order pin: the `EntradaParaEmpty` arm fires before the
11878        // `EntradaParaInvalid` parse-side arm — same empty-first
11879        // cascade `validate_membro_caixa` / `validate_placement_cluster`
11880        // / `validate_contrato_caixa` already establish.
11881        let mut s = three_member_spec();
11882        s.entrada.as_mut().unwrap().para = String::new();
11883        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
11884    }
11885
11886    #[test]
11887    fn entrada_para_shape_fires_before_membership_lookup() {
11888        // The load-bearing pin: an invalid-shape `:para` surfaces its
11889        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
11890        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
11891        // an invalid-shape `:para` could never legitimately match any
11892        // member — the prior `EntradaMemberMissing` diagnostic framed
11893        // a structural impossibility as a graph-membership failure.
11894        let mut s = three_member_spec();
11895        s.entrada.as_mut().unwrap().para = "Cart".into();
11896        let err = s.validate().unwrap_err();
11897        assert!(
11898            matches!(
11899                err,
11900                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
11901            ),
11902            "got {err:?}"
11903        );
11904    }
11905
11906    #[test]
11907    fn entrada_para_shape_fires_before_host_gate() {
11908        // Per-`:entrada` order pin: the `:para` shape gate fires
11909        // before the `:host` gate, mirroring the existing
11910        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
11911        // ordering where the member-lookup arm preceded the host gate.
11912        // The shape gate slots ahead of that, so a malformed `:para`
11913        // surfaces its own diagnostic even when `:host` is also wrong.
11914        let mut s = three_member_spec();
11915        let e = s.entrada.as_mut().unwrap();
11916        e.para = "Cart".into();
11917        e.host = "BAD HOST".into();
11918        let err = s.validate().unwrap_err();
11919        assert!(
11920            matches!(
11921                err,
11922                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
11923            ),
11924            "got {err:?}"
11925        );
11926    }
11927
11928    #[test]
11929    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
11930        // Strict-improvement pin: a well-shaped `:para` that simply
11931        // isn't in `:membros` (a phantom reference — author meant to
11932        // add the member but didn't, or renamed and missed an
11933        // update) still surfaces `EntradaMemberMissing`, unchanged.
11934        // The shape gate only intercepts inputs that could never
11935        // legitimately match a validated member.
11936        let mut s = three_member_spec();
11937        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
11938        let err = s.validate().unwrap_err();
11939        assert!(
11940            matches!(
11941                err,
11942                AplicacaoError::EntradaMemberMissing { ref para }
11943                    if para == "phantom-shim"
11944            ),
11945            "got {err:?}"
11946        );
11947    }
11948
11949    #[test]
11950    fn entrada_para_invalid_diagnostic_carries_offending_para() {
11951        // The diagnostic-shape pin: the error names the offending
11952        // `:para` value verbatim plus a non-empty parser-shaped
11953        // reason, so the author can grep their caixa.lisp for
11954        // `:para "<name>"` and fix it in one edit. Same diagnostic
11955        // shape as `MembroCaixaInvalid` (3f9d7a0),
11956        // `PlacementClusterInvalid` (6c8c00b), and
11957        // `ContratoCaixaInvalid` (8d5af6b).
11958        let mut s = three_member_spec();
11959        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
11960        let err = s.validate().unwrap_err();
11961        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
11962            panic!("expected EntradaParaInvalid, got {err:?}");
11963        };
11964        assert_eq!(para, "BAD_NAME");
11965        assert!(
11966            !reason.is_empty(),
11967            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
11968        );
11969    }
11970
11971    #[test]
11972    fn accepts_canonical_entrada_para_forms() {
11973        // Positive-control sweep covering the DNS-1123 label shapes a
11974        // caixa author is realistically going to write on `:entrada
11975        // :para`. Pin every leg so a future tightening that bans
11976        // (e.g.) digit-start identifiers surfaces here, mirroring
11977        // `accepts_canonical_membro_caixa_forms` and
11978        // `accepts_canonical_contrato_caixa_forms` on the peer name
11979        // axes.
11980        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
11981            let mut s = three_member_spec();
11982            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
11983            s.contratos = vec![contract_http(form, "catalog", "/x")];
11984            s.entrada = Some(Entrada {
11985                host: "checkout.quero.cloud".into(),
11986                para: form.into(),
11987                paths: vec!["/api".into()],
11988                port: 8080,
11989            });
11990            s.validate().unwrap_or_else(|e| {
11991                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
11992            });
11993        }
11994    }
11995
11996    #[test]
11997    fn rejects_replicated_without_clusters() {
11998        let mut s = three_member_spec();
11999        s.placement.clusters = vec![];
12000        assert!(matches!(
12001            s.validate().unwrap_err(),
12002            AplicacaoError::PlacementWithoutClusters { .. }
12003        ));
12004    }
12005
12006    #[test]
12007    fn rejects_sharded_without_key() {
12008        let mut s = three_member_spec();
12009        s.placement.estrategia = PlacementStrategy::Sharded;
12010        s.placement.shard_key = None;
12011        s.placement.clusters = vec!["rio".into()];
12012        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
12013    }
12014
12015    #[test]
12016    fn sharded_with_key_validates() {
12017        let mut s = three_member_spec();
12018        s.placement.estrategia = PlacementStrategy::Sharded;
12019        s.placement.shard_key = Some("$tenantId".into());
12020        s.validate().unwrap();
12021    }
12022
12023    #[test]
12024    fn round_trip_via_json_preserves_shape() {
12025        let s = three_member_spec();
12026        let json = serde_json::to_string(&s.membros).unwrap();
12027        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
12028        assert_eq!(back, s.membros);
12029
12030        let json = serde_json::to_string(&s.contratos).unwrap();
12031        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
12032        assert_eq!(back, s.contratos);
12033
12034        let json = serde_json::to_string(&s.placement).unwrap();
12035        let back: Placement = serde_json::from_str(&json).unwrap();
12036        assert_eq!(back, s.placement);
12037
12038        let json = serde_json::to_string(&s.entrada).unwrap();
12039        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
12040        assert_eq!(back, s.entrada);
12041    }
12042
12043    #[test]
12044    fn rate_limit_round_trip_seconds() {
12045        let policy = MeshPolicy {
12046            rate_limit: Some(RateLimit {
12047                rate: 100,
12048                window: Duration::from_secs(1),
12049            }),
12050            ..Default::default()
12051        };
12052        let json = serde_json::to_string(&policy).unwrap();
12053        assert!(json.contains("\"100/s\""));
12054        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
12055        assert_eq!(back.rate_limit.unwrap().rate, 100);
12056        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
12057    }
12058
12059    #[test]
12060    fn rate_limit_round_trip_minutes() {
12061        let policy = MeshPolicy {
12062            rate_limit: Some(RateLimit {
12063                rate: 5000,
12064                window: Duration::from_secs(60),
12065            }),
12066            ..Default::default()
12067        };
12068        let json = serde_json::to_string(&policy).unwrap();
12069        assert!(json.contains("\"5000/m\""));
12070    }
12071
12072    #[test]
12073    fn circuit_breaker_round_trip() {
12074        let policy = MeshPolicy {
12075            circuit_breaker: Some(CircuitBreaker {
12076                max_failures: 5,
12077                window: Duration::from_secs(60),
12078            }),
12079            ..Default::default()
12080        };
12081        let json = serde_json::to_string(&policy).unwrap();
12082        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
12083        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
12084        assert_eq!(
12085            back.circuit_breaker.unwrap().window,
12086            Duration::from_secs(60)
12087        );
12088    }
12089
12090    #[test]
12091    fn rejects_http_contrato_without_endpoint() {
12092        let mut s = three_member_spec();
12093        s.contratos.push(WitContract {
12094            de: "cart".into(),
12095            para: "catalog".into(),
12096            wit: "wasi:http/proxy".into(),
12097            endpoint: None,
12098            subject: None,
12099            slot: None,
12100        });
12101        let err = s.validate().unwrap_err();
12102        assert!(matches!(
12103            err,
12104            AplicacaoError::ContratoMissingTarget {
12105                expected: WitTarget::HTTP_FIELD_NAME,
12106                ..
12107            }
12108        ));
12109    }
12110
12111    #[test]
12112    fn rejects_http_contrato_with_subject() {
12113        let mut s = three_member_spec();
12114        s.contratos.push(WitContract {
12115            de: "cart".into(),
12116            para: "catalog".into(),
12117            wit: "wasi:http/proxy".into(),
12118            endpoint: Some("/x".into()),
12119            subject: Some("not.allowed.here".into()),
12120            slot: None,
12121        });
12122        let err = s.validate().unwrap_err();
12123        assert!(matches!(
12124            err,
12125            AplicacaoError::ContratoWrongTarget {
12126                expected: WitTarget::HTTP_FIELD_NAME,
12127                ..
12128            }
12129        ));
12130    }
12131
12132    #[test]
12133    fn rejects_pubsub_contrato_without_subject() {
12134        let mut s = three_member_spec();
12135        s.contratos.push(WitContract {
12136            de: "cart".into(),
12137            para: "catalog".into(),
12138            wit: "nats:pub-sub".into(),
12139            endpoint: None,
12140            subject: None,
12141            slot: None,
12142        });
12143        let err = s.validate().unwrap_err();
12144        assert!(matches!(
12145            err,
12146            AplicacaoError::ContratoMissingTarget {
12147                expected: WitTarget::PUBSUB_FIELD_NAME,
12148                ..
12149            }
12150        ));
12151    }
12152
12153    #[test]
12154    fn rejects_pubsub_contrato_with_endpoint() {
12155        let mut s = three_member_spec();
12156        s.contratos.push(WitContract {
12157            de: "cart".into(),
12158            para: "catalog".into(),
12159            wit: "kafka:topic".into(),
12160            endpoint: Some("/wrong".into()),
12161            subject: Some("topic.x".into()),
12162            slot: None,
12163        });
12164        let err = s.validate().unwrap_err();
12165        assert!(matches!(
12166            err,
12167            AplicacaoError::ContratoWrongTarget {
12168                expected: WitTarget::PUBSUB_FIELD_NAME,
12169                ..
12170            }
12171        ));
12172    }
12173
12174    #[test]
12175    fn rejects_store_contrato_without_slot() {
12176        let mut s = three_member_spec();
12177        s.contratos.push(WitContract {
12178            de: "cart".into(),
12179            para: "catalog".into(),
12180            wit: "wasi:keyvalue/store".into(),
12181            endpoint: None,
12182            subject: None,
12183            slot: None,
12184        });
12185        let err = s.validate().unwrap_err();
12186        assert!(matches!(
12187            err,
12188            AplicacaoError::ContratoMissingTarget {
12189                expected: WitTarget::STORE_FIELD_NAME,
12190                ..
12191            }
12192        ));
12193    }
12194
12195    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
12196
12197    #[test]
12198    fn rejects_http_contrato_with_empty_endpoint() {
12199        // `Some("")` for an HTTP endpoint passes the presence check
12200        // (target() previously returned WitTarget::Http { endpoint: "" })
12201        // but renders as a `path: ""` Cilium L7 rule that matches no
12202        // traffic. Same value-shape footgun closed for :entrada :paths
12203        // entries (eb3456d).
12204        let mut s = three_member_spec();
12205        s.contratos.push(WitContract {
12206            de: "cart".into(),
12207            para: "catalog".into(),
12208            wit: "wasi:http/proxy".into(),
12209            endpoint: Some(String::new()),
12210            subject: None,
12211            slot: None,
12212        });
12213        let err = s.validate().unwrap_err();
12214        assert!(
12215            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
12216                if de == "cart" && para == "catalog"),
12217            "got {err:?}"
12218        );
12219    }
12220
12221    #[test]
12222    fn rejects_http_contrato_with_relative_endpoint() {
12223        // Cilium L7 :path + Gateway API PathPrefix both require a
12224        // leading `/`. Same shape required of :entrada :paths
12225        // (eb3456d). Lifted into target() so every consumer of the
12226        // typed WitTarget view inherits the guarantee.
12227        let mut s = three_member_spec();
12228        s.contratos.push(WitContract {
12229            de: "cart".into(),
12230            para: "catalog".into(),
12231            wit: "wasi:http/proxy".into(),
12232            endpoint: Some("products/:id".into()),
12233            subject: None,
12234            slot: None,
12235        });
12236        let err = s.validate().unwrap_err();
12237        assert!(
12238            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12239                if endpoint == "products/:id"),
12240            "got {err:?}"
12241        );
12242    }
12243
12244    #[test]
12245    fn rejects_pubsub_contrato_with_empty_subject() {
12246        // NATS / Kafka publish without a subject is a no-op subscribe;
12247        // never the author's intent. Same empty-string rejection as
12248        // :membros :caixa, :placement :clusters entries, :entrada
12249        // :paths entries — every value carried by every typed slot is
12250        // value-shape-checked at validate().
12251        let mut s = three_member_spec();
12252        s.contratos.push(WitContract {
12253            de: "cart".into(),
12254            para: "catalog".into(),
12255            wit: "nats:pub-sub".into(),
12256            endpoint: None,
12257            subject: Some(String::new()),
12258            slot: None,
12259        });
12260        let err = s.validate().unwrap_err();
12261        assert!(
12262            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
12263                if de == "cart" && para == "catalog"),
12264            "got {err:?}"
12265        );
12266    }
12267
12268    #[test]
12269    fn rejects_store_contrato_with_empty_slot() {
12270        // An empty slot template addresses the bucket root, defeating
12271        // the per-key isolation the slot exists for — a footgun on
12272        // `wasi:keyvalue/store` whose closest analog is the empty
12273        // shard-key rejected on :placement Sharded (c7c7799).
12274        let mut s = three_member_spec();
12275        s.contratos.push(WitContract {
12276            de: "cart".into(),
12277            para: "catalog".into(),
12278            wit: "wasi:keyvalue/store".into(),
12279            endpoint: None,
12280            subject: None,
12281            slot: Some(String::new()),
12282        });
12283        let err = s.validate().unwrap_err();
12284        assert!(
12285            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
12286                if de == "cart" && para == "catalog"),
12287            "got {err:?}"
12288        );
12289    }
12290
12291    #[test]
12292    fn http_contrato_root_endpoint_validates() {
12293        // Pin the boundary case: a single-`/` endpoint is the catch-all
12294        // form the Gateway HTTPRoute renderer falls back to when
12295        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
12296        // must remain a valid contrato endpoint too.
12297        let mut s = three_member_spec();
12298        s.contratos.push(contract_http("cart", "catalog", "/"));
12299        s.validate().unwrap();
12300    }
12301
12302    // ── :contratos :endpoint value-shape gate ────────────────────────────
12303    //
12304    // Mirrors the `:entrada :paths` value-shape suite on the peer
12305    // HTTP-path axis. Until this gate landed `WitContract::target()`
12306    // only refused the empty string + the missing-leading-`/` form
12307    // (c4213a4); a structurally invalid endpoint passed validate and
12308    // landed verbatim as a Cilium L7 `path:` rule
12309    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
12310    // traffic or was rejected at apply time by Cilium policy admission.
12311    // Every authoring footgun the K8s Gateway API webhook / Cilium
12312    // policy validator would catch on admission now becomes a caixa-
12313    // build-time `ContratoEndpointInvalid` with the offending
12314    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
12315    // shape as `EntradaPathInvalid` on the sibling axis; same shared
12316    // predicate (`crate::render::is_gateway_api_http_path`) ensures
12317    // drift between the two axes' rule enforcement is a build error
12318    // at the predicate.
12319
12320    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
12321        // Fresh spec per call so the would-be-duplicate edge
12322        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
12323        // `three_member_spec`'s pre-existing
12324        // `(cart, catalog, …, /products/:id)` entry — only the
12325        // endpoint payload differs.
12326        let mut s = three_member_spec();
12327        s.contratos.push(contract_http("cart", "catalog", ep));
12328        s.validate().unwrap_err()
12329    }
12330
12331    #[test]
12332    fn rejects_http_contrato_endpoint_with_query() {
12333        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
12334        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
12335        // rule the L7 matcher would never satisfy.
12336        let err = contrato_endpoint_err("/charge?token=X");
12337        assert!(
12338            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12339                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
12340            "got {err:?}"
12341        );
12342    }
12343
12344    #[test]
12345    fn rejects_http_contrato_endpoint_with_fragment() {
12346        let err = contrato_endpoint_err("/charge#frag");
12347        assert!(
12348            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12349                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
12350            "got {err:?}"
12351        );
12352    }
12353
12354    #[test]
12355    fn rejects_http_contrato_endpoint_with_whitespace() {
12356        let err = contrato_endpoint_err("/foo bar");
12357        assert!(
12358            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12359                if endpoint == "/foo bar" && reason.contains("whitespace")),
12360            "got {err:?}"
12361        );
12362    }
12363
12364    #[test]
12365    fn rejects_http_contrato_endpoint_with_control_char() {
12366        let err = contrato_endpoint_err("/api/\x01bar");
12367        assert!(
12368            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12369                if endpoint == "/api/\x01bar" && reason.contains("control character")),
12370            "got {err:?}"
12371        );
12372    }
12373
12374    #[test]
12375    fn rejects_http_contrato_endpoint_with_non_ascii() {
12376        let err = contrato_endpoint_err("/api/café");
12377        assert!(
12378            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12379                if endpoint == "/api/café" && reason.contains("non-ASCII")),
12380            "got {err:?}"
12381        );
12382    }
12383
12384    #[test]
12385    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
12386        let err = contrato_endpoint_err("/api//cart");
12387        assert!(
12388            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12389                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
12390            "got {err:?}"
12391        );
12392    }
12393
12394    #[test]
12395    fn rejects_http_contrato_endpoint_with_dot_segment() {
12396        let err = contrato_endpoint_err("/api/./cart");
12397        assert!(
12398            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12399                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
12400            "got {err:?}"
12401        );
12402    }
12403
12404    #[test]
12405    fn rejects_http_contrato_endpoint_with_parent_segment() {
12406        // Path-traversal in a contrato endpoint is the canonical
12407        // "L7 rule that the workload's HTTP server's path-resolution
12408        // logic interprets differently than the policy enforcer"
12409        // footgun. Rejected outright at validate time.
12410        let err = contrato_endpoint_err("/api/../etc");
12411        assert!(
12412            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12413                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
12414            "got {err:?}"
12415        );
12416    }
12417
12418    #[test]
12419    fn rejects_http_contrato_endpoint_too_long() {
12420        // 1025-byte endpoint — one over the Gateway API
12421        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
12422        // path matcher has no inherent length limit but the policy
12423        // CR itself rides through the K8s apiserver, which enforces
12424        // ConfigMap-shaped limits; sharing the Gateway API cap is the
12425        // conservative floor.
12426        let big = format!("/api/{}", "a".repeat(1020));
12427        assert_eq!(big.len(), 1025);
12428        let err = contrato_endpoint_err(&big);
12429        assert!(
12430            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
12431                if endpoint == &big && reason.contains("max length of 1024")),
12432            "got {err:?}"
12433        );
12434    }
12435
12436    #[test]
12437    fn http_contrato_endpoint_max_length_validates() {
12438        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
12439        // in the cap surfaces here and at
12440        // `rejects_http_contrato_endpoint_too_long` simultaneously,
12441        // mirroring `entrada_path_max_length_validates` on the peer
12442        // axis.
12443        let big = format!("/api/{}", "a".repeat(1019));
12444        assert_eq!(big.len(), 1024);
12445        let mut s = three_member_spec();
12446        s.contratos.push(contract_http("cart", "catalog", &big));
12447        s.validate().unwrap();
12448    }
12449
12450    #[test]
12451    fn http_contrato_endpoint_accepts_canonical_forms() {
12452        // Positive-set sweep: every canonical HTTP-path shape the
12453        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
12454        // plain paths, hidden-file-style `.config` segments distinct
12455        // from the `.` segment, digit-bearing segments, the canonical
12456        // route-template `:param` form, trailing-slash form,
12457        // percent-encoded segments, the `/foo..bar` interior-`..`-
12458        // substring forms that are NOT `..` segments) must remain a
12459        // valid contrato endpoint too. Drift between this list and
12460        // the entrada path positive sweep surfaces at the shared
12461        // `is_gateway_api_http_path` substrate-side suite — one
12462        // source of truth. Uses a fresh `(payment, catalog)` edge so
12463        // none of the swept endpoints collide with the pre-existing
12464        // `(cart, catalog, /products/:id)` / `(cart, payment,
12465        // /charge)` entries in `three_member_spec`.
12466        for ep in [
12467            "/",
12468            "/charge",
12469            "/v1/charge",
12470            "/api/.config",
12471            "/products/:id",
12472            "/api/cart/",
12473            "/api/caf%C3%A9",
12474            "/foo..bar",
12475            "/...",
12476        ] {
12477            let mut s = three_member_spec();
12478            s.contratos.push(contract_http("payment", "catalog", ep));
12479            s.validate()
12480                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
12481        }
12482    }
12483
12484    #[test]
12485    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
12486        // Ordering pin: `ContratoEndpointEmpty` is the more self-
12487        // locating diagnostic on `""` and must lead — the value-
12488        // shape gate is only reached after the empty-check fires.
12489        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
12490        // on the peer axis.
12491        let mut s = three_member_spec();
12492        s.contratos.push(WitContract {
12493            de: "cart".into(),
12494            para: "catalog".into(),
12495            wit: "wasi:http/proxy".into(),
12496            endpoint: Some(String::new()),
12497            subject: None,
12498            slot: None,
12499        });
12500        let err = s.validate().unwrap_err();
12501        assert!(
12502            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
12503            "got {err:?}"
12504        );
12505    }
12506
12507    #[test]
12508    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
12509        // Ordering pin: an endpoint without a leading `/` surfaces the
12510        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
12511        // value-shape gate is only consulted on endpoints that already
12512        // satisfy the absolute-prefix invariant. Mirrors
12513        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
12514        let err = contrato_endpoint_err("bad path");
12515        assert!(
12516            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12517                if endpoint == "bad path"),
12518            "got {err:?}"
12519        );
12520    }
12521
12522    #[test]
12523    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
12524        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
12525        // `:para` + a non-empty reason flow through verbatim so the
12526        // author can grep their caixa.lisp for the offending contrato
12527        // block and fix it in one edit. Same shape as
12528        // `entrada_path_diagnostic_carries_offending_path`.
12529        let err = contrato_endpoint_err("/api?q=1");
12530        match err {
12531            AplicacaoError::ContratoEndpointInvalid {
12532                de,
12533                para,
12534                endpoint,
12535                reason,
12536            } => {
12537                assert_eq!(de, "cart");
12538                assert_eq!(para, "catalog");
12539                assert_eq!(endpoint, "/api?q=1");
12540                assert!(!reason.is_empty(), "reason field must be non-empty");
12541            }
12542            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
12543        }
12544    }
12545
12546    #[test]
12547    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
12548        // The compounding theorem: every &str inside a WitTarget
12549        // returned by target() is non-empty (and absolute, for Http).
12550        // Renderers downstream of typed_view() can rely on this
12551        // without re-checking — the type system carries the proof.
12552        let http = contract_http("cart", "catalog", "/x");
12553        match http.target().unwrap() {
12554            WitTarget::Http { endpoint } => {
12555                assert!(!endpoint.is_empty());
12556                assert!(endpoint.starts_with('/'));
12557            }
12558            other => panic!("expected Http, got {other:?}"),
12559        }
12560        let nats = WitContract {
12561            de: "a".into(),
12562            para: "b".into(),
12563            wit: "nats:pub-sub".into(),
12564            endpoint: None,
12565            subject: Some("topic.x".into()),
12566            slot: None,
12567        };
12568        match nats.target().unwrap() {
12569            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
12570            other => panic!("expected PubSub, got {other:?}"),
12571        }
12572        let kv = WitContract {
12573            de: "a".into(),
12574            para: "b".into(),
12575            wit: "wasi:keyvalue/store".into(),
12576            endpoint: None,
12577            subject: None,
12578            slot: Some("checkout/$orderId".into()),
12579        };
12580        match kv.target().unwrap() {
12581            WitTarget::Store { slot } => assert!(!slot.is_empty()),
12582            other => panic!("expected Store, got {other:?}"),
12583        }
12584    }
12585
12586    #[test]
12587    fn target_diagnostic_names_offending_endpoint_value() {
12588        // When the malformed endpoint string is non-trivial, the
12589        // diagnostic carries the actual value back to the author —
12590        // not a generic "endpoint malformed" error.
12591        let bad = WitContract {
12592            de: "src".into(),
12593            para: "dst".into(),
12594            wit: "wasi:http/proxy".into(),
12595            endpoint: Some("api/v1/charge".into()),
12596            subject: None,
12597            slot: None,
12598        };
12599        match bad.target().unwrap_err() {
12600            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
12601                assert_eq!(de, "src");
12602                assert_eq!(para, "dst");
12603                assert_eq!(endpoint, "api/v1/charge");
12604            }
12605            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
12606        }
12607    }
12608
12609    #[test]
12610    fn rejects_unknown_wit_with_target_set() {
12611        let mut s = three_member_spec();
12612        s.contratos.push(WitContract {
12613            de: "cart".into(),
12614            para: "catalog".into(),
12615            wit: "custom:exchange".into(),
12616            endpoint: Some("/leaked".into()),
12617            subject: None,
12618            slot: None,
12619        });
12620        let err = s.validate().unwrap_err();
12621        assert!(matches!(
12622            err,
12623            AplicacaoError::ContratoWrongTarget {
12624                expected: WitTarget::CAPABILITY_EXPECTED,
12625                ..
12626            }
12627        ));
12628    }
12629
12630    #[test]
12631    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
12632        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
12633        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
12634        // fourth arm of the same "which payload field name goes in the
12635        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
12636        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
12637        // consts cover on the peer HTTP / PubSub / Store arms
12638        // (`wit_target_field_name_pins_per_variant`). Until this lift
12639        // landed the byte-string sat twice — once inline in the
12640        // [`WitContract::target`] Capability-arm rejection at the
12641        // production dispatch, once in `rejects_unknown_wit_with_target_set`
12642        // pinning against the same literal — with no compile-time link
12643        // between them. Same "one canonical declaration, next to the
12644        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
12645        // lift established for the payload-less arm's human-readable
12646        // label axis; this test is the shape peer of
12647        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
12648        // pair (routes-through-const + scalar-value pin) on the
12649        // wrong-target diagnostic-scalar axis.
12650        //
12651        // Fail-before-pass-after was verified locally by mutating the
12652        // const declaration to `"capability"` — the scalar-value pin
12653        // below fires (`"capability" != "none"`) and the routes-through
12654        // assertion below still holds (production and const walk in
12655        // lockstep), which is the correct behavior: a rename on the
12656        // const drifts here first, not at a downstream consumer.
12657        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
12658
12659        let mut s = three_member_spec();
12660        s.contratos.push(WitContract {
12661            de: "cart".into(),
12662            para: "catalog".into(),
12663            wit: "custom:exchange".into(),
12664            endpoint: Some("/leaked".into()),
12665            subject: None,
12666            slot: None,
12667        });
12668        match s.validate().unwrap_err() {
12669            AplicacaoError::ContratoWrongTarget { expected, .. } => {
12670                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
12671            }
12672            other => panic!("expected ContratoWrongTarget, got {other:?}"),
12673        }
12674    }
12675
12676    #[test]
12677    fn unknown_wit_capability_only_validates() {
12678        let mut s = three_member_spec();
12679        s.contratos.push(WitContract {
12680            de: "cart".into(),
12681            para: "catalog".into(),
12682            // A WIT world we haven't yet shaped — accept it as a typed
12683            // capability edge so authors aren't blocked while the WIT
12684            // registry catches up. No payload field may be carried.
12685            wit: "custom:exchange".into(),
12686            endpoint: None,
12687            subject: None,
12688            slot: None,
12689        });
12690        s.validate().unwrap();
12691        let added = s.contratos.last().unwrap();
12692        assert_eq!(added.target().unwrap(), WitTarget::Capability);
12693    }
12694
12695    #[test]
12696    fn target_typed_view_round_trips_each_shape() {
12697        let http = contract_http("cart", "catalog", "/products/:id");
12698        assert_eq!(
12699            http.target().unwrap(),
12700            WitTarget::Http {
12701                endpoint: "/products/:id"
12702            }
12703        );
12704        let nats = WitContract {
12705            de: "a".into(),
12706            para: "b".into(),
12707            wit: "nats:pub-sub".into(),
12708            endpoint: None,
12709            subject: Some("topic.x".into()),
12710            slot: None,
12711        };
12712        assert_eq!(
12713            nats.target().unwrap(),
12714            WitTarget::PubSub { subject: "topic.x" }
12715        );
12716        let kv = WitContract {
12717            de: "a".into(),
12718            para: "b".into(),
12719            wit: "wasi:keyvalue/store".into(),
12720            endpoint: None,
12721            subject: None,
12722            slot: Some("checkout/$orderId".into()),
12723        };
12724        assert_eq!(
12725            kv.target().unwrap(),
12726            WitTarget::Store {
12727                slot: "checkout/$orderId"
12728            }
12729        );
12730    }
12731
12732    #[test]
12733    fn wit_contract_kind_predicates() {
12734        let http = contract_http("a", "b", "/x");
12735        assert!(http.is_http());
12736        assert!(!http.is_pubsub());
12737        assert!(!http.is_store());
12738        assert!(!http.is_capability());
12739
12740        let nats = WitContract {
12741            de: "a".into(),
12742            para: "b".into(),
12743            wit: "nats:pub-sub".into(),
12744            endpoint: None,
12745            subject: Some("topic.x".into()),
12746            slot: None,
12747        };
12748        assert!(nats.is_pubsub());
12749        assert!(!nats.is_http());
12750        assert!(!nats.is_capability());
12751
12752        let kv = WitContract {
12753            de: "a".into(),
12754            para: "b".into(),
12755            wit: "wasi:keyvalue/store".into(),
12756            endpoint: None,
12757            subject: None,
12758            slot: Some("checkout/$orderId".into()),
12759        };
12760        assert!(kv.is_store());
12761        assert!(!kv.is_http());
12762        assert!(!kv.is_capability());
12763
12764        // Fourth arm on the paired closed-set predicate family: the
12765        // payload-less capability edge that projects to the payload-
12766        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
12767        // Extends the 3-arm predicate sweep this test opened to cover
12768        // the closed 4-way partition [`WitContract::is_capability`]
12769        // closes on the pre-projection WIT-shape axis, matched with the
12770        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
12771        // 4-arm predicate set.
12772        let cap = WitContract {
12773            de: "a".into(),
12774            para: "b".into(),
12775            wit: "custom:capability-only".into(),
12776            endpoint: None,
12777            subject: None,
12778            slot: None,
12779        };
12780        assert!(cap.is_capability());
12781        assert!(!cap.is_http());
12782        assert!(!cap.is_pubsub());
12783        assert!(!cap.is_store());
12784    }
12785
12786    // ── :contratos :wit value-shape gate ─────────────────────────────────
12787    //
12788    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
12789    // dispatch-discriminator axis. Until this gate landed
12790    // `WitContract::target()` accepted any non-empty string and
12791    // silently demoted unrecognized shapes to a capability-only L4
12792    // edge — the canonical "I thought I had L7 HTTP routing, got
12793    // L4-only" footgun. Every authoring footgun the WIT registry's
12794    // own grammar rejects (uppercase, hyphen-for-colon typo,
12795    // whitespace, empty package, doubled `@`, …) now becomes a
12796    // caixa-build-time `ContratoWitInvalid` with the offending
12797    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
12798    // as `ContratoEndpointInvalid` on the sibling axis; same shared
12799    // predicate (`crate::render::is_wit_world_ref`) ensures drift
12800    // between any two axes' rule enforcement is a build error at the
12801    // predicate, not piecemeal across renderers.
12802
12803    fn contrato_wit_err(wit: &str) -> AplicacaoError {
12804        // Fresh spec per call so the new contract doesn't collide on
12805        // identity with `three_member_spec`'s pre-existing entries.
12806        // The new edge uses `(payment, catalog)` — a pair the fixture
12807        // doesn't already declare — with no payload field set, so the
12808        // wit-shape gate fires before any payload-shape arm.
12809        let mut s = three_member_spec();
12810        s.contratos.push(WitContract {
12811            de: "payment".into(),
12812            para: "catalog".into(),
12813            wit: wit.into(),
12814            endpoint: None,
12815            subject: None,
12816            slot: None,
12817        });
12818        s.validate().unwrap_err()
12819    }
12820
12821    #[test]
12822    fn rejects_wit_with_uppercase_namespace() {
12823        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
12824        // didn't match the lowercase `wasi:http/` prefix is_http() keys
12825        // off, so the dispatch fell through to the capability arm and
12826        // the contract silently rendered as an L4-only Cilium edge.
12827        // The new gate surfaces the uppercase typo at validate time
12828        // with the offending `:wit` named.
12829        let err = contrato_wit_err("WASI:http/proxy");
12830        assert!(
12831            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12832                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
12833            "got {err:?}"
12834        );
12835    }
12836
12837    #[test]
12838    fn rejects_wit_with_hyphen_for_colon_typo() {
12839        // The canonical "I forgot the `:` separator" typo — pre-gate
12840        // this passed as Capability silently, so the renderer emitted
12841        // an L4-only policy where the author expected L7 HTTP rules.
12842        let err = contrato_wit_err("wasi-http/proxy");
12843        assert!(
12844            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12845                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
12846            "got {err:?}"
12847        );
12848    }
12849
12850    #[test]
12851    fn rejects_wit_with_multiple_colons() {
12852        // Doubled `:` — the namespace/package split has nowhere to
12853        // anchor, so the dispatch silently demotes to Capability.
12854        let err = contrato_wit_err("wasi:http:proxy");
12855        assert!(
12856            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12857                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
12858            "got {err:?}"
12859        );
12860    }
12861
12862    #[test]
12863    fn rejects_wit_with_empty_package() {
12864        // `wasi:` — namespace alone with no package. Pre-gate this
12865        // failed neither the is_http nor is_pubsub nor is_store
12866        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
12867        // a bare `wasi:`), so it silently demoted to Capability.
12868        let err = contrato_wit_err("wasi:");
12869        assert!(
12870            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12871                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
12872            "got {err:?}"
12873        );
12874    }
12875
12876    #[test]
12877    fn rejects_wit_with_underscore() {
12878        // Underscore — WIT identifiers are kebab-case, same rule
12879        // DNS-1123 enforces on its peer axes. The diagnostic carries
12880        // the explicit "use `-` instead" remediation.
12881        let err = contrato_wit_err("wasi:http_proxy");
12882        assert!(
12883            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12884                if wit == "wasi:http_proxy" && reason.contains('_')),
12885            "got {err:?}"
12886        );
12887    }
12888
12889    #[test]
12890    fn rejects_wit_with_whitespace() {
12891        // Whitespace mid-token — the prefix check matches but the
12892        // package-and-onward parse silently demoted to Capability.
12893        let err = contrato_wit_err("wasi:http proxy");
12894        assert!(
12895            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12896                if wit == "wasi:http proxy" && reason.contains("whitespace")),
12897            "got {err:?}"
12898        );
12899    }
12900
12901    #[test]
12902    fn rejects_wit_with_non_ascii() {
12903        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12904        // the package name from a doc with smart quotes / accented
12905        // characters" footgun.
12906        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
12907        assert!(
12908            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12909                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
12910            "got {err:?}"
12911        );
12912    }
12913
12914    #[test]
12915    fn rejects_wit_with_consecutive_hyphens() {
12916        // `pub--sub` — WIT identifiers join words with single hyphens.
12917        let err = contrato_wit_err("nats:pub--sub");
12918        assert!(
12919            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12920                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
12921            "got {err:?}"
12922        );
12923    }
12924
12925    #[test]
12926    fn rejects_wit_with_trailing_at_no_version() {
12927        // `wasi:http/proxy@` — the version-suffix author started to
12928        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
12929        // parser would reject this; surface it at validate time.
12930        let err = contrato_wit_err("wasi:http/proxy@");
12931        assert!(
12932            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12933                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
12934            "got {err:?}"
12935        );
12936    }
12937
12938    #[test]
12939    fn rejects_wit_too_long() {
12940        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
12941        // The legitimate-shape arms all pass (lowercase, single `:`,
12942        // kebab-case identifiers); only the cap arm fires. Surfaces
12943        // the paste-from-binary / accidental-multi-line-blob landing
12944        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12945        // on the peer axis.
12946        let big = format!("wasi:{}", "a".repeat(124));
12947        assert_eq!(big.len(), 129);
12948        let err = contrato_wit_err(&big);
12949        assert!(
12950            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
12951                if wit == &big && reason.contains("max length of 128")),
12952            "got {err:?}"
12953        );
12954    }
12955
12956    #[test]
12957    fn wit_max_length_validates() {
12958        // 128-byte WIT reference — exactly the cap. Boundary pin:
12959        // drift in the cap surfaces here and at `rejects_wit_too_long`
12960        // simultaneously, mirroring
12961        // `http_contrato_endpoint_max_length_validates` on the peer
12962        // axis.
12963        let big = format!("wasi:{}", "a".repeat(123));
12964        assert_eq!(big.len(), 128);
12965        let mut s = three_member_spec();
12966        s.contratos.push(WitContract {
12967            de: "payment".into(),
12968            para: "catalog".into(),
12969            wit: big,
12970            endpoint: None,
12971            subject: None,
12972            slot: None,
12973        });
12974        s.validate().unwrap();
12975    }
12976
12977    #[test]
12978    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
12979        // Positive-set sweep through the AplicacaoSpec::validate
12980        // surface (rather than the substrate-side predicate directly)
12981        // — pins every shape the existing test fixtures + the
12982        // checkout-aplicacao example carry, so the gate's accept-set
12983        // matches the substrate's emit-set. Drift between this list
12984        // and `render::tests::wit_world_ref_accepts_canonical_forms`
12985        // surfaces at the substrate layer's positive sweep — one
12986        // source of truth for the rule.
12987        for wit in [
12988            "wasi:http/proxy",
12989            "wasi:keyvalue/store",
12990            "nats:pub-sub",
12991            "kafka:topic",
12992            "custom:exchange",
12993            "pleme:cap/audit",
12994            "wasi:http/proxy@0.2.0",
12995        ] {
12996            // Payload field paired to the dispatched WIT shape so the
12997            // shape-↔-target arm doesn't fire instead of the wit-shape
12998            // arm we're exercising. Routes off the same
12999            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
13000            // `wit_shape_is_store` free functions the production
13001            // `WitContract::is_http` / `is_pubsub` / `is_store`
13002            // methods delegate to (both consult the lifted
13003            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
13004            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
13005            // future prefix addition to the routing accept-set
13006            // reaches this test's payload-dispatch arm by
13007            // construction — no per-test-site drift can hide a
13008            // shape-→-target-slot mismatch that would silently
13009            // demote a canonical `:wit` value to the
13010            // `(None, None, None)` capability-only arm and let the
13011            // `AplicacaoSpec::validate` positive sweep pass on a
13012            // shape it should exercise as HTTP / pub-sub / store.
13013            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
13014                (Some("/x".into()), None, None)
13015            } else if wit_shape_is_pubsub(wit) {
13016                (None, Some("topic.x".into()), None)
13017            } else if wit_shape_is_store(wit) {
13018                (None, None, Some("bucket/$key".into()))
13019            } else {
13020                (None, None, None)
13021            };
13022            let mut s = three_member_spec();
13023            s.contratos.push(WitContract {
13024                de: "payment".into(),
13025                para: "catalog".into(),
13026                wit: wit.into(),
13027                endpoint,
13028                subject,
13029                slot,
13030            });
13031            s.validate()
13032                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
13033        }
13034    }
13035
13036    #[test]
13037    fn wit_shape_predicates_accept_canonical_prefix_set() {
13038        // Positive-set sweep pinning every prefix in
13039        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
13040        // WIT_STORE_SHAPE_PREFIXES against the three free-function
13041        // dispatch predicates. The six prefixes are the load-bearing
13042        // routing keys the substrate's WIT-shape dispatch consults
13043        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
13044        // key/value-store-slot admission); any drift between the
13045        // free-function accept-set and this list surfaces here
13046        // rather than at apply time as a silent
13047        // shape-→-capability-only demotion.
13048        assert!(wit_shape_is_http("wasi:http/proxy"));
13049        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
13050        assert!(wit_shape_is_http("http:incoming"));
13051
13052        assert!(wit_shape_is_pubsub("nats:pub-sub"));
13053        assert!(wit_shape_is_pubsub("kafka:topic"));
13054
13055        assert!(wit_shape_is_store("wasi:keyvalue/store"));
13056        assert!(wit_shape_is_store("kv:cache/session"));
13057    }
13058
13059    #[test]
13060    fn wit_shape_predicates_reject_uncanonical_forms() {
13061        // Negative-set pin: the six canonical prefixes are
13062        // lowercase-only (mirrors the `is_wit_world_ref` substrate
13063        // predicate's lowercase invariant — see its docstring on the
13064        // "I thought I had L7 HTTP routing, got L4-only" footgun).
13065        // The empty string, an uppercase-prefixed form, a hyphen-
13066        // instead-of-colon typo, and a bare kebab identifier all miss
13067        // every shape arm — reachable-by-construction only via the
13068        // `is_wit_world_ref` gate that admission-checks the `:wit`
13069        // value first, but pinned here so any future
13070        // free-function change (e.g. a case-insensitive
13071        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
13072        // this unit level.
13073        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
13074            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
13075            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
13076            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
13077        }
13078    }
13079
13080    #[test]
13081    fn wit_shape_predicates_partition_canonical_set() {
13082        // Every canonical prefix routes to exactly one shape arm —
13083        // the three prefix sets are pairwise disjoint. Pins the
13084        // routing property [`WitContract::target`] relies on: an
13085        // `is_http()` return of `true` guarantees `is_pubsub()` and
13086        // `is_store()` return `false`, so the shape-→-target-slot
13087        // dispatch (endpoint vs subject vs slot) is unambiguous.
13088        // Drift (e.g. a future `"kv:"` moved into the HTTP set
13089        // without removal from the store set) would silently route
13090        // one prefix to two arms and the first-matching-arm order
13091        // becomes load-bearing — this pin surfaces it as a build
13092        // error instead.
13093        for prefix in WIT_HTTP_SHAPE_PREFIXES {
13094            let sample = format!("{prefix}x");
13095            assert!(wit_shape_is_http(&sample));
13096            assert!(!wit_shape_is_pubsub(&sample));
13097            assert!(!wit_shape_is_store(&sample));
13098        }
13099        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
13100            let sample = format!("{prefix}x");
13101            assert!(!wit_shape_is_http(&sample));
13102            assert!(wit_shape_is_pubsub(&sample));
13103            assert!(!wit_shape_is_store(&sample));
13104        }
13105        for prefix in WIT_STORE_SHAPE_PREFIXES {
13106            let sample = format!("{prefix}x");
13107            assert!(!wit_shape_is_http(&sample));
13108            assert!(!wit_shape_is_pubsub(&sample));
13109            assert!(wit_shape_is_store(&sample));
13110        }
13111    }
13112
13113    #[test]
13114    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
13115        // Positive pin: [`wit_shape_matches`] is exactly the
13116        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
13117        // parameterized on the accept-set. Two-prefix accept-set,
13118        // one-prefix accept-set, and empty accept-set (which must
13119        // reject everything, including the empty string — an empty
13120        // `any()` fold returns `false`) all pinned so a future
13121        // reimplementation that swaps `starts_with` for `contains`,
13122        // `==`, or a case-folded comparator surfaces at unit-test
13123        // time.
13124        let two = &["wasi:http/", "http:"];
13125        assert!(wit_shape_matches("wasi:http/proxy", two));
13126        assert!(wit_shape_matches("http:incoming", two));
13127        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
13128
13129        let one = &["nats:"];
13130        assert!(wit_shape_matches("nats:pub-sub", one));
13131        assert!(!wit_shape_matches("kafka:topic", one));
13132
13133        // Empty accept-set matches nothing — the identity element
13134        // for the disjunctive `any()` fold across the prefix set.
13135        // Reachable via a future `wit_shape_is_<name>` const paired
13136        // to a still-empty prefix table on a nascent shape-arm draft.
13137        let empty: &[&str] = &[];
13138        assert!(!wit_shape_matches("wasi:http/proxy", empty));
13139        assert!(!wit_shape_matches("", empty));
13140
13141        // starts_with, not contains: a prefix embedded mid-string
13142        // never matches. Pins the routing invariant [`WitContract::target`]
13143        // relies on (an authored `:wit "custom:wasi:http/"` string
13144        // does not silently route through the HTTP arm just because
13145        // it happens to contain the canonical HTTP prefix).
13146        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
13147    }
13148
13149    #[test]
13150    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
13151        // Equivalence pin: each per-shape predicate is exactly
13152        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
13153        // every canonical prefix + the empty string + one negative
13154        // sample against every peer so a future predicate that grew
13155        // its own inline `iter().any(starts_with)` (rather than
13156        // delegating through the lifted combinator) drifts loudly here
13157        // — the peer-const table's contents must agree with the
13158        // predicate's accept-set by construction.
13159        let samples = [
13160            String::new(),
13161            "wasi:http/proxy".to_string(),
13162            "http:incoming".to_string(),
13163            "nats:pub-sub".to_string(),
13164            "kafka:topic".to_string(),
13165            "wasi:keyvalue/store".to_string(),
13166            "kv:cache/session".to_string(),
13167            "custom-shape".to_string(),
13168            "WASI:HTTP/proxy".to_string(),
13169        ];
13170        for wit in &samples {
13171            assert_eq!(
13172                wit_shape_is_http(wit),
13173                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
13174                "wit_shape_is_http drifted from combinator on {wit:?}",
13175            );
13176            assert_eq!(
13177                wit_shape_is_pubsub(wit),
13178                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
13179                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
13180            );
13181            assert_eq!(
13182                wit_shape_is_store(wit),
13183                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
13184                "wit_shape_is_store drifted from combinator on {wit:?}",
13185            );
13186        }
13187    }
13188
13189    #[test]
13190    fn wit_contract_shape_methods_delegate_to_free_functions() {
13191        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
13192        // `is_store` are `&self` conveniences on top of the free
13193        // functions — for every canonical prefix the method's return
13194        // matches its free-function peer. Sweeps the union of the
13195        // three prefix sets so a future method that grew its own
13196        // inline prefix logic (rather than delegating) drifts loudly
13197        // here on the first prefix the free function accepts and the
13198        // method doesn't.
13199        for shape_set in [
13200            WIT_HTTP_SHAPE_PREFIXES,
13201            WIT_PUBSUB_SHAPE_PREFIXES,
13202            WIT_STORE_SHAPE_PREFIXES,
13203        ] {
13204            for prefix in shape_set {
13205                let c = WitContract {
13206                    de: "cart".into(),
13207                    para: "catalog".into(),
13208                    wit: format!("{prefix}x"),
13209                    endpoint: None,
13210                    subject: None,
13211                    slot: None,
13212                };
13213                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
13214                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
13215                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
13216                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
13217            }
13218        }
13219        // Capability-arm delegation sweep: two representative
13220        // Capability-shaped `:wit` values (a bare non-prefix-matching
13221        // WIT world, the deliberately-shaped empty string
13222        // [`WitContract::is_capability`]'s docstring calls out as
13223        // syntactically Capability). Extends the free-function
13224        // delegation pin onto the fourth arm so a future
13225        // [`WitContract::is_capability`] rewrite that grew an inline
13226        // prefix-set scan (rather than delegating through
13227        // [`wit_shape_is_capability`]) drifts loudly here on the first
13228        // Capability-shaped sample.
13229        for wit in ["custom:capability-only", ""] {
13230            let c = WitContract {
13231                de: "cart".into(),
13232                para: "catalog".into(),
13233                wit: wit.into(),
13234                endpoint: None,
13235                subject: None,
13236                slot: None,
13237            };
13238            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
13239        }
13240    }
13241
13242    #[test]
13243    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
13244        // 4-way partition-witness pin on the raw `&str` axis: for every
13245        // canonical prefix in the three payload-arm accept-sets,
13246        // exactly one of the four [`wit_shape_is_http`] /
13247        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
13248        // [`wit_shape_is_capability`] free functions returns `true` and
13249        // the other three return `false` — the four-arm partition
13250        // witness that locks the free-function WIT-shape-classifier
13251        // family into a partition of the `:contratos :wit` axis
13252        // load-bearing. Peer of the sibling [`WitContract`]-surface
13253        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
13254        // partition pin — extends the discipline onto the raw `&str`
13255        // axis so any future arm addition (a hypothetical
13256        // `wasi:sockets/*` transport-layer shape, an `oci:*`
13257        // capability-import carrier per the sibling
13258        // [`wit_shape_matches`] docstring's trajectory bullet) that
13259        // landed on one of the payload-arm free functions without
13260        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
13261        // here as two arms returning `true` simultaneously at
13262        // caixa-core build time rather than a silent per-consumer
13263        // misclassification at renderer emit time.
13264        for shape_set in [
13265            WIT_HTTP_SHAPE_PREFIXES,
13266            WIT_PUBSUB_SHAPE_PREFIXES,
13267            WIT_STORE_SHAPE_PREFIXES,
13268        ] {
13269            for prefix in shape_set {
13270                let wit = format!("{prefix}x");
13271                let hits = [
13272                    wit_shape_is_http(&wit),
13273                    wit_shape_is_pubsub(&wit),
13274                    wit_shape_is_store(&wit),
13275                    wit_shape_is_capability(&wit),
13276                ]
13277                .iter()
13278                .filter(|&&b| b)
13279                .count();
13280                assert_eq!(
13281                    hits,
13282                    1,
13283                    "raw-&str WIT-shape 4-way predicate partition must \
13284                     admit exactly one arm per canonical prefix; got {hits} \
13285                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
13286                     is_capability={})",
13287                    wit_shape_is_http(&wit),
13288                    wit_shape_is_pubsub(&wit),
13289                    wit_shape_is_store(&wit),
13290                    wit_shape_is_capability(&wit),
13291                );
13292            }
13293        }
13294        // Capability-arm sweep on the raw `&str` axis: two
13295        // representative Capability-shaped `:wit` values (a bare non-
13296        // prefix-matching WIT world, the deliberately-shaped empty
13297        // string the pure classifier still admits per
13298        // [`wit_shape_is_capability`]'s docstring). Both must land on
13299        // the fourth arm exclusively so the partition witness holds
13300        // across the full 4-arm closure on the raw `&str` axis.
13301        for wit in ["custom:capability-only", ""] {
13302            let hits = [
13303                wit_shape_is_http(wit),
13304                wit_shape_is_pubsub(wit),
13305                wit_shape_is_store(wit),
13306                wit_shape_is_capability(wit),
13307            ]
13308            .iter()
13309            .filter(|&&b| b)
13310            .count();
13311            assert_eq!(
13312                hits, 1,
13313                "raw-&str WIT-shape 4-way predicate partition must \
13314                 admit exactly one arm on Capability-shaped wit={wit:?}"
13315            );
13316            assert!(
13317                wit_shape_is_capability(wit),
13318                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
13319            );
13320        }
13321    }
13322
13323    #[test]
13324    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
13325        // Composition-witness pin: [`wit_shape_is_capability`] is the
13326        // exact-inverse disjunction of the sibling payload-arm free-
13327        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
13328        // / [`wit_shape_is_store`]. A future reimplementation that
13329        // grew its own prefix-set scan (e.g. inlining a fourth
13330        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
13331        // not own today) rather than delegating to the sibling trio
13332        // would drift loudly here — the composition contract binds the
13333        // fourth-arm free-function predicate to the exact-inverse of
13334        // the three payload-arm free-function predicates, so any
13335        // rebrand of any prefix-set const flows through
13336        // [`wit_shape_is_capability`] by construction without a
13337        // coordinated per-consumer rewrite. Peer of the sibling
13338        // [`WitContract`]-surface
13339        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
13340        // composition pin — extends the discipline onto the raw
13341        // `&str` axis.
13342        let mut cases: Vec<String> = Vec::new();
13343        for shape_set in [
13344            WIT_HTTP_SHAPE_PREFIXES,
13345            WIT_PUBSUB_SHAPE_PREFIXES,
13346            WIT_STORE_SHAPE_PREFIXES,
13347        ] {
13348            for prefix in shape_set {
13349                cases.push(format!("{prefix}x"));
13350            }
13351        }
13352        cases.push("custom:capability-only".to_string());
13353        cases.push(String::new());
13354        for wit in cases {
13355            assert_eq!(
13356                wit_shape_is_capability(&wit),
13357                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
13358                "wit_shape_is_capability must equal \
13359                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
13360                 at wit={wit:?}"
13361            );
13362        }
13363    }
13364
13365    #[test]
13366    fn wit_shape_classifier_family_is_const_fn() {
13367        // Fail-before-pass-after pin on the 4-arm free-function WIT-
13368        // shape classifier family's `const`-eval posture. Each of the
13369        // four peer classifiers ([`wit_shape_is_http`] /
13370        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
13371        // [`wit_shape_is_capability`]) and the underlying combinator
13372        // [`wit_shape_matches`] must be `pub const fn` — any future
13373        // accidental downgrade to non-`const` fails the `const fn`
13374        // wrappers below at caixa-core build time with E0015
13375        // (`cannot call non-const function`), strictly stronger than
13376        // a runtime `assert!` and strictly stronger than the module-
13377        // scope `const _: () = assert!(…)` pins immediately after the
13378        // classifier declarations (those anchor specific accept-set
13379        // truth-table entries; this pin anchors the `const` posture
13380        // itself via `const fn` wrappers that are only well-formed
13381        // when the callee is itself `const fn`).
13382        //
13383        // Verified fail-before-pass-after by locally reverting
13384        // `pub const fn` → `pub fn` on each classifier and observing
13385        // E0015 at every corresponding wrapper call site (build
13386        // error, no test-time surface), then restoring `pub const fn`
13387        // and observing the pin pass at test time. Peer of the
13388        // sibling M3
13389        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
13390        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
13391        // M2
13392        // [`child_spec_restart_accessor_is_const_fn`] /
13393        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
13394        // and M3
13395        // [`placement_estrategia_accessor_is_const_fn`] /
13396        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
13397        // sibling `const`-eval-surface-pass axes.
13398        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
13399            wit_shape_matches(wit, prefixes)
13400        }
13401        const fn http_via_const_fn(wit: &str) -> bool {
13402            wit_shape_is_http(wit)
13403        }
13404        const fn pubsub_via_const_fn(wit: &str) -> bool {
13405            wit_shape_is_pubsub(wit)
13406        }
13407        const fn store_via_const_fn(wit: &str) -> bool {
13408            wit_shape_is_store(wit)
13409        }
13410        const fn capability_via_const_fn(wit: &str) -> bool {
13411            wit_shape_is_capability(wit)
13412        }
13413        // Sweep one canonical accept-set sample per arm plus the
13414        // payload-less/empty capability samples, asserting the
13415        // wrapper and direct dispatches agree byte-for-byte across
13416        // the closed 4-arm partition.
13417        let cases: [(&str, bool, bool, bool, bool); 6] = [
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        ];
13425        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
13426            assert_eq!(
13427                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
13428                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
13429                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
13430            );
13431            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
13432            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
13433            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
13434            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
13435            assert_eq!(wit_shape_is_http(wit), is_http);
13436            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
13437            assert_eq!(wit_shape_is_store(wit), is_store);
13438        }
13439        // Payload-less capability arm (the 4th partition arm).
13440        let capability_samples: [&str; 3] =
13441            ["wasi:filesystem/preopens", "custom:capability-only", ""];
13442        for wit in capability_samples {
13443            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
13444            assert!(wit_shape_is_capability(wit));
13445            assert!(!wit_shape_is_http(wit));
13446            assert!(!wit_shape_is_pubsub(wit));
13447            assert!(!wit_shape_is_store(wit));
13448        }
13449    }
13450
13451    #[test]
13452    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
13453        // Composition-witness pin: [`wit_shape_matches`] agrees with
13454        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
13455        // dispatch (the prior non-`const` implementation) across
13456        // boundary lengths — empty `wit`, empty prefix, one-byte
13457        // slack, prefix longer than `wit`, one-byte trailing slack.
13458        // The rewrite to a byte-level manual starts_with loop (the
13459        // enabler for the `pub const fn` posture) must not change any
13460        // truth-table entry on the canonical accept-set — this pin
13461        // sweeps a targeted boundary corpus and asserts byte-for-byte
13462        // agreement, locking the const-fn rewrite's semantics against
13463        // the prior iterator body by construction.
13464        let prefixes = &["wasi:http/", "http:"][..];
13465        let cases: [(&str, bool); 12] = [
13466            ("wasi:http/proxy", true),
13467            ("wasi:http/", true), // exact-length match on prefix
13468            ("wasi:http", false), // one byte short
13469            ("http:", true),
13470            ("http:incoming", true),
13471            ("http", false), // one byte short
13472            ("", false),
13473            ("wasi:https/proxy", false),
13474            ("nats:events", false),
13475            ("HTTPS:", false), // uppercase — no case-fold in classifier
13476            ("wasi:HTTP/proxy", false),
13477            ("wasi:http", false),
13478        ];
13479        for (wit, expected) in cases {
13480            assert_eq!(
13481                wit_shape_matches(wit, prefixes),
13482                expected,
13483                "wit_shape_matches disagrees with reference at wit={wit:?}",
13484            );
13485            // Byte-equal to the iterator body it replaced.
13486            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
13487            assert_eq!(
13488                wit_shape_matches(wit, prefixes),
13489                via_iter,
13490                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
13491            );
13492        }
13493        // Empty prefix set → always false regardless of `wit`.
13494        let empty: &[&str] = &[];
13495        assert!(!wit_shape_matches("", empty));
13496        assert!(!wit_shape_matches("wasi:http/proxy", empty));
13497        // Empty prefix inside a non-empty set → always true (every
13498        // string starts with the empty string, matching the
13499        // iterator body's semantics on `str::starts_with("")`).
13500        let contains_empty: &[&str] = &["nats:", ""];
13501        assert!(wit_shape_matches("", contains_empty));
13502        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
13503    }
13504
13505    #[test]
13506    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
13507        // 4-way partition-witness pin: for every canonical prefix in
13508        // the payload-arm accept-sets, exactly one of the four
13509        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13510        // [`WitContract::is_store`] / [`WitContract::is_capability`]
13511        // predicates returns `true` and the other three return `false`
13512        // — the four-arm partition witness that locks the substrate's
13513        // WIT-shape-space closure on the pre-projection axis load-
13514        // bearing. A future arm addition (a hypothetical fourth
13515        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
13516        // shape) that landed on one of the payload-arm predicates
13517        // without shrinking [`WitContract::is_capability`]'s accept-set
13518        // would surface here as two arms returning `true` simultaneously
13519        // — a partition-witness break the pin catches at caixa-core
13520        // build time rather than a silent per-consumer misclassification
13521        // at renderer emit time. Peer of the sibling `WitTarget`-side
13522        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
13523        // partition-witness pin on the post-projection payload-scalar
13524        // arm-set — extends the discipline onto the pre-projection
13525        // 4-arm shape-space.
13526        for shape_set in [
13527            WIT_HTTP_SHAPE_PREFIXES,
13528            WIT_PUBSUB_SHAPE_PREFIXES,
13529            WIT_STORE_SHAPE_PREFIXES,
13530        ] {
13531            for prefix in shape_set {
13532                let c = WitContract {
13533                    de: "cart".into(),
13534                    para: "catalog".into(),
13535                    wit: format!("{prefix}x"),
13536                    endpoint: None,
13537                    subject: None,
13538                    slot: None,
13539                };
13540                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13541                    .iter()
13542                    .filter(|&&b| b)
13543                    .count();
13544                assert_eq!(
13545                    hits,
13546                    1,
13547                    "WitContract WIT-shape 4-way predicate partition must \
13548                     admit exactly one arm per canonical prefix; got {hits} \
13549                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
13550                     is_capability={})",
13551                    c.wit,
13552                    c.is_http(),
13553                    c.is_pubsub(),
13554                    c.is_store(),
13555                    c.is_capability(),
13556                );
13557            }
13558        }
13559        // Capability-arm sweep: two representative capability shapes
13560        // (a bare WIT world outside the three payload-arm prefix sets,
13561        // and the deliberately-shaped empty string that
13562        // [`crate::render::is_wit_world_ref`] rejects at
13563        // [`WitContract::target`] time but which the pure classifier
13564        // still admits — see the method docstring's "purely syntactic
13565        // classification" note). Both must land on the fourth arm
13566        // exclusively, so the partition witness holds across the full
13567        // 4-arm closure.
13568        for wit in ["custom:capability-only", ""] {
13569            let c = WitContract {
13570                de: "cart".into(),
13571                para: "catalog".into(),
13572                wit: wit.into(),
13573                endpoint: None,
13574                subject: None,
13575                slot: None,
13576            };
13577            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
13578                .iter()
13579                .filter(|&&b| b)
13580                .count();
13581            assert_eq!(
13582                hits, 1,
13583                "WitContract WIT-shape 4-way predicate partition must \
13584                 admit exactly one arm on Capability-shaped wit={wit:?}"
13585            );
13586            assert!(
13587                c.is_capability(),
13588                "wit={wit:?} must project onto the Capability arm"
13589            );
13590        }
13591    }
13592
13593    #[test]
13594    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
13595        // Composition-witness pin: [`WitContract::is_capability`] is the
13596        // exact-inverse disjunction of the sibling payload-arm predicate
13597        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
13598        // [`WitContract::is_store`]. A future reimplementation that
13599        // grew its own prefix-set scan (e.g. inlining a fourth
13600        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
13601        // own today) rather than delegating to the sibling trio would
13602        // drift loudly here — the composition contract binds the
13603        // fourth-arm predicate to the exact-inverse of the three
13604        // payload-arm predicates, so any rebrand of any prefix-set const
13605        // flows through this method by construction without a
13606        // coordinated per-consumer rewrite. Sweeps the union of the
13607        // three payload-arm prefix sets plus two Capability-shaped
13608        // shapes (a bare non-prefix-matching WIT world, the deliberately-
13609        // empty string the pure classifier still admits per the method
13610        // docstring's "purely syntactic classification" note).
13611        let mut cases: Vec<String> = Vec::new();
13612        for shape_set in [
13613            WIT_HTTP_SHAPE_PREFIXES,
13614            WIT_PUBSUB_SHAPE_PREFIXES,
13615            WIT_STORE_SHAPE_PREFIXES,
13616        ] {
13617            for prefix in shape_set {
13618                cases.push(format!("{prefix}x"));
13619            }
13620        }
13621        cases.push("custom:capability-only".to_string());
13622        cases.push(String::new());
13623        for wit in cases {
13624            let c = WitContract {
13625                de: "cart".into(),
13626                para: "catalog".into(),
13627                wit: wit.clone(),
13628                endpoint: None,
13629                subject: None,
13630                slot: None,
13631            };
13632            assert_eq!(
13633                c.is_capability(),
13634                !c.is_http() && !c.is_pubsub() && !c.is_store(),
13635                "WitContract::is_capability must equal \
13636                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
13637            );
13638        }
13639    }
13640
13641    #[test]
13642    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
13643        // Cross-projection-witness pin: whenever [`WitContract::target`]
13644        // succeeds, the pre-projection [`WitContract::is_capability`]
13645        // classification agrees with the post-projection
13646        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
13647        // predicate — the 4-arm typed partition on the substrate's
13648        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
13649        // partition on the pre-projection axis line up by construction.
13650        // A future divergence between the two axes (a peer
13651        // [`WitTarget`] variant addition that landed on the typed-view
13652        // surface without a peer prefix-set + [`WitContract`] predicate
13653        // extension, or vice versa) would surface here at caixa-core
13654        // build time rather than a silent per-consumer split at renderer
13655        // emit time. Peer of the sibling pre-/post-projection
13656        // agreement pins the payload-carrier trio
13657        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13658        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
13659        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
13660        // post-projection — b11bb49 trio lift) already carry across the
13661        // three payload arms — this pin closes the pair on the fourth
13662        // payload-less arm.
13663        let http = WitContract {
13664            de: "cart".into(),
13665            para: "catalog".into(),
13666            wit: "wasi:http/proxy".into(),
13667            endpoint: Some("/x".into()),
13668            subject: None,
13669            slot: None,
13670        };
13671        assert!(!http.is_capability());
13672        assert!(!http.target().unwrap().is_capability());
13673
13674        let nats = WitContract {
13675            de: "cart".into(),
13676            para: "catalog".into(),
13677            wit: "nats:pub-sub".into(),
13678            endpoint: None,
13679            subject: Some("events.x".into()),
13680            slot: None,
13681        };
13682        assert!(!nats.is_capability());
13683        assert!(!nats.target().unwrap().is_capability());
13684
13685        let kv = WitContract {
13686            de: "cart".into(),
13687            para: "catalog".into(),
13688            wit: "wasi:keyvalue/store".into(),
13689            endpoint: None,
13690            subject: None,
13691            slot: Some("checkout/$orderId".into()),
13692        };
13693        assert!(!kv.is_capability());
13694        assert!(!kv.target().unwrap().is_capability());
13695
13696        let cap = WitContract {
13697            de: "cart".into(),
13698            para: "catalog".into(),
13699            wit: "custom:capability-only".into(),
13700            endpoint: None,
13701            subject: None,
13702            slot: None,
13703        };
13704        assert!(cap.is_capability());
13705        assert!(cap.target().unwrap().is_capability());
13706    }
13707
13708    #[test]
13709    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
13710        // Fail-before-pass-after pin on the [`WitContract`] pre-
13711        // projection accessor family's `const`-eval-surface posture.
13712        // Each of the three per-`:contratos` byte-string scalar
13713        // accessors ([`WitContract::source`] / [`WitContract::destination`]
13714        // / [`WitContract::world_ref`], each projecting through
13715        // `String::as_str` — const-stable since Rust 1.87, well within
13716        // the workspace MSRV) and each of the four peer WIT-shape
13717        // predicates ([`WitContract::is_http`] /
13718        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
13719        // [`WitContract::is_capability`], each composing
13720        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
13721        // free-function classifier family the sibling
13722        // [`wit_shape_classifier_family_is_const_fn`] pin already
13723        // anchors on the raw `&str → bool` axis) must be `pub const fn`
13724        // — any future accidental downgrade to non-`const` fails the
13725        // `const fn` wrappers below at caixa-core build time with E0015
13726        // (`cannot call non-const function`), strictly stronger than a
13727        // runtime `assert!` and strictly stronger than a
13728        // module-scope `const _: () = assert!(…)` pin (which cannot be
13729        // formed on a `&WitContract` fixture because the type's
13730        // `String` / `Option<String>` carriers rule out `const`-context
13731        // construction; the `const fn` wrapper is the load-bearing
13732        // shape that side-steps the destructor-in-const restriction on
13733        // the value axis while still pinning the `const`-fn posture on
13734        // the callee).
13735        //
13736        // Peer of the sibling free-function classifier pin
13737        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
13738        // raw `&str → bool` axis — this pin extends the same
13739        // `const`-eval-surface discipline onto the peer method surface
13740        // that composes through those free-function classifiers, and
13741        // simultaneously onto the underlying per-`:contratos`
13742        // byte-string scalar-accessor trio each predicate reads
13743        // through. Sibling of the peer M3
13744        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
13745        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
13746        // M2
13747        // [`child_spec_restart_accessor_is_const_fn`] /
13748        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
13749        // and M3
13750        // [`placement_estrategia_accessor_is_const_fn`] /
13751        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
13752        // sibling `const`-eval-surface-pass axes.
13753        const fn source_via_const_fn(c: &WitContract) -> &str {
13754            c.source()
13755        }
13756        const fn destination_via_const_fn(c: &WitContract) -> &str {
13757            c.destination()
13758        }
13759        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
13760            c.world_ref()
13761        }
13762        const fn is_http_via_const_fn(c: &WitContract) -> bool {
13763            c.is_http()
13764        }
13765        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
13766            c.is_pubsub()
13767        }
13768        const fn is_store_via_const_fn(c: &WitContract) -> bool {
13769            c.is_store()
13770        }
13771        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
13772            c.is_capability()
13773        }
13774        // Sweep one canonical accept-set sample per WIT-shape arm plus
13775        // a payload-less capability sample, asserting the wrapper and
13776        // direct dispatches agree byte-for-byte across the closed
13777        // 4-arm partition on both the scalar-accessor trio and the
13778        // WIT-shape-predicate family.
13779        for (wit, is_http, is_pubsub, is_store, is_capability) in [
13780            ("wasi:http/proxy", true, false, false, false),
13781            ("http:incoming", true, false, false, false),
13782            ("nats:events", false, true, false, false),
13783            ("kafka:topic", false, true, false, false),
13784            ("wasi:keyvalue/store", false, false, true, false),
13785            ("kv:cache", false, false, true, false),
13786            ("custom:capability-only", false, false, false, true),
13787            ("", false, false, false, true),
13788        ] {
13789            let c = WitContract {
13790                de: "cart".into(),
13791                para: "catalog".into(),
13792                wit: wit.into(),
13793                endpoint: None,
13794                subject: None,
13795                slot: None,
13796            };
13797            assert_eq!(source_via_const_fn(&c), c.source());
13798            assert_eq!(destination_via_const_fn(&c), c.destination());
13799            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
13800            assert_eq!(is_http_via_const_fn(&c), c.is_http());
13801            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
13802            assert_eq!(is_store_via_const_fn(&c), c.is_store());
13803            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
13804            assert_eq!(c.source(), "cart");
13805            assert_eq!(c.destination(), "catalog");
13806            assert_eq!(c.world_ref(), wit);
13807            assert_eq!(c.is_http(), is_http);
13808            assert_eq!(c.is_pubsub(), is_pubsub);
13809            assert_eq!(c.is_store(), is_store);
13810            assert_eq!(c.is_capability(), is_capability);
13811        }
13812    }
13813
13814    #[test]
13815    fn wit_contract_identity_projection_accessor_is_const_fn() {
13816        // Fail-before-pass-after pin on the [`WitContract::identity`]
13817        // six-arm composite-projection accessor's `const`-eval-surface
13818        // posture. The accessor projects the typed edge's six identity
13819        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
13820        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
13821        // every callee is itself `pub const fn` ([`WitContract::source`]
13822        // / [`WitContract::destination`] / [`WitContract::world_ref`]
13823        // through `String::as_str`, const-stable since Rust 1.87;
13824        // [`WitContract::endpoint`] / [`WitContract::subject`] /
13825        // [`WitContract::slot`] through the sibling `match &self
13826        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
13827        // 0650f64 closed the const-eval surface on) and the tuple
13828        // constructor from borrowed-reference / `Option`-of-borrowed-
13829        // reference arms is trivially const. Any future accidental
13830        // downgrade fails the `identity_via_const_fn` wrapper at
13831        // caixa-core build time with E0015 (`cannot call non-const
13832        // method`), strictly stronger than a runtime `assert!` and
13833        // strictly stronger than a module-scope `const _: () =
13834        // assert!(…)` pin (which cannot be formed on a `&WitContract`
13835        // fixture because the type's `String` / `Option<String>`
13836        // carriers rule out `const`-context value construction; the
13837        // `const fn` wrapper is the load-bearing shape that side-steps
13838        // the destructor-in-const restriction on the value axis while
13839        // still pinning the `const`-fn posture on the callee — mirror
13840        // of the sibling
13841        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13842        // pin's discipline verbatim on the peer scalar-accessor
13843        // surface).
13844        //
13845        // Peer of the sibling
13846        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13847        // (279823b) pin on the six per-`:contratos` scalar-accessor
13848        // callees this composite-projection reads through — where that
13849        // pin anchors the const-eval surface at the six individual
13850        // scalar-accessor arms, this pin extends the same posture onto
13851        // the composite six-tuple projection every consumer that dedups
13852        // typed edges on the [`ContratoIdentity`] axis keys off (the
13853        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
13854        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
13855        // materializer's per-edge identity-based admission webhook; a
13856        // future L7 policy-emitter that shards CNPs by identity-tuple
13857        // rather than by name). Same fail-before-pass-after wrapper
13858        // discipline as the peer M2 / M3 accessor-family pins on the
13859        // sibling `const`-eval-surface passes.
13860        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
13861            c.identity()
13862        }
13863        // Sweep one canonical WIT-shape sample per payload-carrier arm
13864        // plus a payload-less capability sample so the pin exercises
13865        // both `Some(_)`-carrying and `None`-carrying arms on all three
13866        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
13867        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
13868        // with the direct method call on every arm of the closed WIT-
13869        // shape partition.
13870        for (wit, endpoint, subject, slot) in [
13871            ("wasi:http/proxy", Some("/checkout"), None, None),
13872            ("http:incoming", Some("/api"), None, None),
13873            ("nats:events", None, Some("orders.placed"), None),
13874            ("kafka:topic", None, Some("orders.stream"), None),
13875            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
13876            ("kv:cache", None, None, Some("session/{token}")),
13877            ("custom:capability-only", None, None, None),
13878        ] {
13879            let c = WitContract {
13880                de: "cart".into(),
13881                para: "catalog".into(),
13882                wit: wit.into(),
13883                endpoint: endpoint.map(str::to_string),
13884                subject: subject.map(str::to_string),
13885                slot: slot.map(str::to_string),
13886            };
13887            assert_eq!(identity_via_const_fn(&c), c.identity());
13888            assert_eq!(
13889                c.identity(),
13890                ("cart", "catalog", wit, endpoint, subject, slot,),
13891            );
13892        }
13893    }
13894
13895    #[test]
13896    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
13897        // Fail-before-pass-after pin on the four M3 mesh-slot
13898        // `String → &str` scalar accessors ([`Membro::nome`] /
13899        // [`Membro::versao_requirement`] on the per-`:membros` axis,
13900        // [`Entrada::hostname`] / [`Entrada::destination`] on the
13901        // per-`:entrada` axis) — each projects the typed slot's
13902        // [`String`] storage through the `pub const fn`
13903        // [`String::as_str`] (const-stable since Rust 1.87, well
13904        // within the workspace MSRV) and any future accidental
13905        // downgrade to non-`const` fails the corresponding
13906        // `<name>_via_const_fn` wrapper at caixa-core build time with
13907        // E0015 (`cannot call non-const method`), strictly stronger
13908        // than a runtime `assert!` and strictly stronger than a
13909        // module-scope `const _: () = assert!(…)` pin (which cannot
13910        // be formed on `&Membro` / `&Entrada` fixtures because the
13911        // types' `String` carriers rule out `const`-context value
13912        // construction; the `const fn` wrapper is the load-bearing
13913        // shape that side-steps the destructor-in-const restriction
13914        // on the value axis while still pinning the `const`-fn
13915        // posture on the callee — mirror of the sibling
13916        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
13917        // (279823b) pin on the per-`:contratos` axis). Peer of the
13918        // sibling per-M2/M3/universal-axis `String → &str` accessor
13919        // family pins on the sibling `const`-eval-surface passes
13920        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
13921        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
13922        // typed-newtype wrapper,
13923        // [`crate::supervisor::ChildSpec::nome`] /
13924        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
13925        // M2 supervisor-tree axis,
13926        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
13927        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
13928        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
13929        // axis, and the sibling per-`:contratos`
13930        // [`WitContract::source`] / [`WitContract::destination`] /
13931        // [`WitContract::world_ref`] trio at 279823b).
13932        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
13933            m.nome()
13934        }
13935        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
13936            m.versao_requirement()
13937        }
13938        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
13939            e.hostname()
13940        }
13941        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
13942            e.destination()
13943        }
13944        for (caixa, versao) in [
13945            ("cart", "^0.1"),
13946            ("catalog-v2", "~0.2.3"),
13947            ("checkout", "*"),
13948        ] {
13949            let m = Membro {
13950                caixa: caixa.into(),
13951                versao: versao.into(),
13952            };
13953            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
13954            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
13955            assert_eq!(m.nome(), caixa);
13956            assert_eq!(m.versao_requirement(), versao);
13957        }
13958        for (host, para) in [
13959            ("cart.example.com", "cart"),
13960            ("api.checkout.io", "checkout"),
13961        ] {
13962            let e = Entrada {
13963                host: host.into(),
13964                para: para.into(),
13965                paths: vec![],
13966                port: DEFAULT_SERVICO_PORT,
13967            };
13968            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
13969            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
13970            assert_eq!(e.hostname(), host);
13971            assert_eq!(e.destination(), para);
13972        }
13973    }
13974
13975    #[test]
13976    fn m3_option_string_scalar_accessor_family_is_const_fn() {
13977        // Fail-before-pass-after pin on the five M3 mesh-slot
13978        // `Option<String> → Option<&str>` scalar accessors
13979        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
13980        // [`WitContract::slot`] on the per-`:contratos` HTTP /
13981        // pub-sub / key-value payload-carrier trio,
13982        // [`Placement::shard_key`] / [`Placement::affinity`] on the
13983        // per-`:placement` Akka-sharding-key + Adaptive-compression-
13984        // hint pair). Each accessor destructures the typed slot's
13985        // `Option<String>` storage through the `match &self.<field> {
13986        // Some(s) => Some(s.as_str()), None => None }` shape —
13987        // routing through [`String::as_str`] (const-stable since Rust
13988        // 1.87, well within the workspace MSRV) rather than the
13989        // non-const [`Option::as_deref`] the pre-lift bodies carried
13990        // — and any future accidental downgrade to non-`const` fails
13991        // the corresponding `<name>_via_const_fn` wrapper at
13992        // caixa-core build time with E0015 (`cannot call non-const
13993        // method`), strictly stronger than a runtime `assert!` and
13994        // strictly stronger than a module-scope `const _: () =
13995        // assert!(…)` pin (which cannot be formed on `&WitContract`
13996        // / `&Placement` fixtures because the types' `String` /
13997        // `Option<String>` carriers rule out `const`-context value
13998        // construction; the `const fn` wrapper is the load-bearing
13999        // shape that side-steps the destructor-in-const restriction
14000        // on the value axis while still pinning the `const`-fn
14001        // posture on the callee — mirror of the sibling
14002        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14003        // (279823b) and
14004        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
14005        // (29c5d7e) pins on the peer `String → &str` axes at the same
14006        // structs).
14007        //
14008        // Peer of the sibling per-`Caixa` `Option<String> →
14009        // Option<&str>` accessor family pin
14010        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
14011        // on the top-level manifest's optional universal-axis surface
14012        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
14013        // `:restart-window`).
14014        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
14015            w.endpoint()
14016        }
14017        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
14018            w.subject()
14019        }
14020        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
14021            w.slot()
14022        }
14023        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
14024            p.shard_key()
14025        }
14026        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
14027            p.affinity()
14028        }
14029        // Sweep every closed shape-arm partition on the
14030        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
14031        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
14032        // pair None), key-value (`:slot` Some, sibling pair None),
14033        // and Capability (all three None) so each accessor's
14034        // Some/None arm carries a pin through the const dispatch.
14035        for (wit, endpoint, subject, slot) in [
14036            ("wasi:http/proxy", Some("/api"), None, None),
14037            ("nats:pub-sub", None, Some("orders.paid"), None),
14038            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
14039            ("custom:capability-only", None, None, None),
14040        ] {
14041            let c = WitContract {
14042                de: "cart".into(),
14043                para: "catalog".into(),
14044                wit: wit.into(),
14045                endpoint: endpoint.map(str::to_string),
14046                subject: subject.map(str::to_string),
14047                slot: slot.map(str::to_string),
14048            };
14049            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
14050            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
14051            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
14052            assert_eq!(c.endpoint(), endpoint);
14053            assert_eq!(c.subject(), subject);
14054            assert_eq!(c.slot(), slot);
14055        }
14056        // Sweep both `Some`/`None` arms on each per-`:placement`
14057        // optional-scalar so the shard-key + affinity pair carries a
14058        // const-dispatch pin on both arms.
14059        for (shard_key, affinity) in [
14060            (Some("tenantId"), Some("data-locality")),
14061            (Some("$tenantId"), None),
14062            (None, Some("low-latency")),
14063            (None, None),
14064        ] {
14065            let p = Placement {
14066                estrategia: PlacementStrategy::default(),
14067                clusters: vec![],
14068                affinity: affinity.map(str::to_string),
14069                shard_key: shard_key.map(str::to_string),
14070            };
14071            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
14072            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
14073            assert_eq!(p.shard_key(), shard_key);
14074            assert_eq!(p.affinity(), affinity);
14075        }
14076    }
14077
14078    #[test]
14079    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
14080        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
14081        // composite `Vec → &[String]` slice-return accessors on
14082        // [`Placement::clusters`] and [`Entrada::paths`]. Each
14083        // destructures the typed slot's `Vec<String>` storage through
14084        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
14085        // 1.66, well within the workspace MSRV) — any future accidental
14086        // downgrade to non-`const` fails the corresponding
14087        // `<name>_via_const_fn` wrapper at caixa-core build time with
14088        // E0015 (`cannot call non-const method`), strictly stronger
14089        // than a runtime `assert!`. Sibling of the peer
14090        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
14091        // pin on the outer-`AplicacaoSpec` reference-return family
14092        // (`:membros` / `:contratos` slice-return + `:politicas` /
14093        // `:placement` / `:entrada` composite-reference), and of the
14094        // peer M2 slice-return axis pins
14095        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
14096        // (on `SupervisorSpec::children`) and
14097        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
14098        // (on `UpgradeFromEntry::instructions`). Together the four
14099        // pins close the last unlifted reference-return accessor
14100        // family across the substrate primitive.
14101        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
14102            p.clusters()
14103        }
14104        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
14105            e.paths()
14106        }
14107        // Sweep both the empty-Vec (no author-declared entries) and
14108        // the populated-Vec arms on every slice-return accessor so
14109        // each carries a const-dispatch pin on both arms.
14110        let p_empty = Placement {
14111            estrategia: PlacementStrategy::default(),
14112            clusters: vec![],
14113            affinity: None,
14114            shard_key: None,
14115        };
14116        let p_full = Placement {
14117            estrategia: PlacementStrategy::default(),
14118            clusters: vec!["prod-a".into(), "prod-b".into()],
14119            affinity: None,
14120            shard_key: None,
14121        };
14122        assert_eq!(
14123            placement_clusters_via_const_fn(&p_empty),
14124            p_empty.clusters()
14125        );
14126        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
14127        assert!(p_empty.clusters().is_empty());
14128        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
14129        let e_empty = Entrada {
14130            host: "web.example.com".into(),
14131            para: "web".into(),
14132            paths: vec![],
14133            port: DEFAULT_SERVICO_PORT,
14134        };
14135        let e_full = Entrada {
14136            host: "web.example.com".into(),
14137            para: "web".into(),
14138            paths: vec!["/api".into(), "/health".into()],
14139            port: DEFAULT_SERVICO_PORT,
14140        };
14141        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
14142        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
14143        assert!(e_empty.paths().is_empty());
14144        assert_eq!(e_full.paths(), &["/api", "/health"]);
14145    }
14146
14147    #[test]
14148    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
14149        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
14150        // reference-return accessors — the two `Vec → &[T]` slice-
14151        // return accessors on [`AplicacaoSpec::membros`] and
14152        // [`AplicacaoSpec::contratos`] (each routes through the
14153        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
14154        // 1.66), the two `&Composite` composite-reference accessors
14155        // on [`AplicacaoSpec::politicas`] and
14156        // [`AplicacaoSpec::placement`] (each routes through a raw
14157        // `&self.<field>` borrow, trivially const), and the one
14158        // `Option<&Composite>` optional-composite-reference accessor
14159        // on [`AplicacaoSpec::entrada`] (routes through the
14160        // `pub const fn` [`Option::as_ref`], const-stable since Rust
14161        // 1.83). Any future accidental downgrade to non-`const` fails
14162        // the corresponding `<name>_via_const_fn` wrapper at caixa-
14163        // core build time with E0015 (`cannot call non-const
14164        // method`), strictly stronger than a runtime `assert!`.
14165        // Sibling of the peer inner-composite pin
14166        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
14167        // on the `Placement::clusters` + `Entrada::paths` slice-
14168        // return pair, and of the peer M2 axis pins on
14169        // [`crate::supervisor::SupervisorSpec::children`] and
14170        // [`crate::upgrade::UpgradeFromEntry::instructions`].
14171        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
14172            s.membros()
14173        }
14174        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
14175            s.contratos()
14176        }
14177        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
14178            s.politicas()
14179        }
14180        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
14181            s.placement()
14182        }
14183        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
14184            s.entrada()
14185        }
14186        // Construct both a minimal "no :entrada" (internal-only
14187        // mesh) and a full "with :entrada" (external-gateway)
14188        // fixture so the family pins both the `None`-arm (author-
14189        // omitted `:entrada`) and the `Some`-arm (author-declared
14190        // `:entrada`) on the optional-composite axis.
14191        let membro = Membro {
14192            caixa: "web".into(),
14193            versao: "^0.1".into(),
14194        };
14195        let entrada_full = Entrada {
14196            host: "web.example.com".into(),
14197            para: "web".into(),
14198            paths: vec!["/api".into()],
14199            port: DEFAULT_SERVICO_PORT,
14200        };
14201        let internal_only = AplicacaoSpec {
14202            membros: vec![membro.clone()],
14203            contratos: vec![],
14204            politicas: MeshPolicy::default(),
14205            placement: Placement::default(),
14206            entrada: None,
14207        };
14208        let with_entrada = AplicacaoSpec {
14209            membros: vec![membro],
14210            contratos: vec![],
14211            politicas: MeshPolicy::default(),
14212            placement: Placement::default(),
14213            entrada: Some(entrada_full),
14214        };
14215        assert_eq!(
14216            aplicacao_membros_via_const_fn(&internal_only),
14217            internal_only.membros()
14218        );
14219        assert_eq!(
14220            aplicacao_membros_via_const_fn(&with_entrada),
14221            with_entrada.membros()
14222        );
14223        assert_eq!(
14224            aplicacao_contratos_via_const_fn(&internal_only),
14225            internal_only.contratos()
14226        );
14227        assert!(std::ptr::eq(
14228            aplicacao_politicas_via_const_fn(&internal_only),
14229            internal_only.politicas(),
14230        ));
14231        assert!(std::ptr::eq(
14232            aplicacao_placement_via_const_fn(&internal_only),
14233            internal_only.placement(),
14234        ));
14235        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
14236        match (
14237            aplicacao_entrada_via_const_fn(&with_entrada),
14238            with_entrada.entrada(),
14239        ) {
14240            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
14241            _ => panic!(
14242                "aplicacao_entrada_via_const_fn must agree with \
14243                 AplicacaoSpec::entrada on the Some-arm reference"
14244            ),
14245        }
14246    }
14247
14248    #[test]
14249    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
14250        // Load-bearing contract pin: on every canonical
14251        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
14252        // [`WitContract::target_projected`] returns byte-equal to
14253        // [`WitContract::target`]`().unwrap()` — the post-validation
14254        // projection accessor is a thin panicking wrapper over the
14255        // pre-validation validator, no extra work in the projection
14256        // path. Any future divergence (a validator-side normalization
14257        // the projection doesn't route through, an accessor-side
14258        // caching layer the validator doesn't populate) would surface
14259        // here at caixa-core build time rather than a silent per-consumer
14260        // split at renderer emit time. Sweeps the closed 4-arm
14261        // [`WitTarget`] partition ([`WitTarget::Http`] /
14262        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
14263        // [`WitTarget::Capability`]) so every arm carries a byte-equality
14264        // pin on the two-accessor pair.
14265        for (wit, endpoint, subject, slot) in [
14266            ("wasi:http/proxy", Some("/x"), None, None),
14267            ("nats:pub-sub", None, Some("events.x"), None),
14268            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
14269            ("custom:capability-only", None, None, None),
14270        ] {
14271            let c = WitContract {
14272                de: "cart".into(),
14273                para: "catalog".into(),
14274                wit: wit.into(),
14275                endpoint: endpoint.map(str::to_string),
14276                subject: subject.map(str::to_string),
14277                slot: slot.map(str::to_string),
14278            };
14279            assert_eq!(
14280                c.target_projected(),
14281                c.target().unwrap(),
14282                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
14283            );
14284        }
14285    }
14286
14287    #[test]
14288    #[should_panic(expected = "validated by typed_view")]
14289    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
14290        // Panic-path pin: [`WitContract::target_projected`] threads the
14291        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
14292        // through its expect-panic when called on a contract whose
14293        // (`:wit`, payload) shape has not been crossed by
14294        // [`AplicacaoSpec::validate`] — a contract with a structurally-
14295        // invalid `:wit` (hyphen-for-colon typo) that would surface
14296        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
14297        // A future rebrand on the panic-message axis would land at one
14298        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
14299        // and this pin's [`should_panic(expected = …)`] literal would
14300        // migrate alongside — the pin catches drift between the const
14301        // and the accessor's `expect(…)` call by construction.
14302        let c = WitContract {
14303            de: "cart".into(),
14304            para: "catalog".into(),
14305            // Hyphen-for-colon typo: `WitContract::target` returns
14306            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
14307            // driving the [`WitContract::target_projected`] expect-panic.
14308            wit: "wasi-http/proxy".into(),
14309            endpoint: Some("/x".into()),
14310            subject: None,
14311            slot: None,
14312        };
14313        let _ = c.target_projected();
14314    }
14315
14316    #[test]
14317    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
14318        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
14319        // carries the exact byte-string the two prior open-coded
14320        // `.target().expect("validated by typed_view")` production
14321        // consumers threaded through inline before this lift converged
14322        // them onto [`WitContract::target_projected`] — the caixa-mesh
14323        // per-`(:de, :para)` CNP L7 introspection branch at
14324        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
14325        // graph` per-`:contratos` payload-column printer at
14326        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
14327        // byte-string load-bearing so a well-meaning const-side rebrand
14328        // that didn't carry a matched pin migration would surface here
14329        // at caixa-core build time rather than a silent per-consumer
14330        // panic-message drift at cluster-apply time. Peer of the
14331        // sibling [`WitTarget::CAPABILITY_LABEL`] /
14332        // [`WitTarget::CAPABILITY_EXPECTED`] /
14333        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
14334        // the paired payload-less-arm scalar-const family.
14335        assert_eq!(
14336            WitContract::PROJECTED_INVARIANT_MSG,
14337            "validated by typed_view"
14338        );
14339    }
14340
14341    #[test]
14342    fn empty_wit_takes_precedence_over_invalid() {
14343        // Ordering pin: `EmptyWit` is the more self-locating
14344        // diagnostic on `""` and must lead — the value-shape gate is
14345        // only reached after the empty-check fires. Mirrors
14346        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14347        // the peer payload axis.
14348        let mut s = three_member_spec();
14349        s.contratos.push(WitContract {
14350            de: "payment".into(),
14351            para: "catalog".into(),
14352            wit: String::new(),
14353            endpoint: None,
14354            subject: None,
14355            slot: None,
14356        });
14357        let err = s.validate().unwrap_err();
14358        assert!(
14359            matches!(err, AplicacaoError::EmptyWit { .. }),
14360            "got {err:?}"
14361        );
14362    }
14363
14364    #[test]
14365    fn wit_invalid_fires_before_payload_shape_arm() {
14366        // Ordering pin: a malformed `:wit` surfaces *its own*
14367        // diagnostic (which names the offending wit verbatim) before
14368        // any payload-field check — a contrato whose wit is
14369        // structurally invalid AND carries a wrong target field
14370        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
14371        // because the dispatch on the wit is what decides which
14372        // payload field is "right" in the first place. Without this
14373        // ordering, the author would see "wrong target field" for a
14374        // wit that hasn't even been parsed, which doesn't name the
14375        // root cause.
14376        let mut s = three_member_spec();
14377        s.contratos.push(WitContract {
14378            de: "payment".into(),
14379            para: "catalog".into(),
14380            // Hyphen-for-colon typo + endpoint set: pre-gate this
14381            // raised `ContratoWrongTarget { expected: "none" }` (the
14382            // Capability arm rejecting the endpoint), masking the
14383            // real authoring mistake (the wit isn't `wasi:http/proxy`).
14384            wit: "wasi-http/proxy".into(),
14385            endpoint: Some("/x".into()),
14386            subject: None,
14387            slot: None,
14388        });
14389        let err = s.validate().unwrap_err();
14390        assert!(
14391            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
14392                if wit == "wasi-http/proxy"),
14393            "got {err:?}"
14394        );
14395    }
14396
14397    #[test]
14398    fn wit_invalid_diagnostic_carries_offending_wit() {
14399        // Diagnostic-shape pin — the offending `:wit` + `:de` +
14400        // `:para` + a non-empty reason flow through verbatim so the
14401        // author can grep their caixa.lisp for the offending contrato
14402        // block and fix it in one edit. Same shape as
14403        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
14404        let err = contrato_wit_err("WASI:HTTP/proxy");
14405        match err {
14406            AplicacaoError::ContratoWitInvalid {
14407                de,
14408                para,
14409                wit,
14410                reason,
14411            } => {
14412                assert_eq!(de, "payment");
14413                assert_eq!(para, "catalog");
14414                assert_eq!(wit, "WASI:HTTP/proxy");
14415                assert!(!reason.is_empty(), "reason field must be non-empty");
14416            }
14417            other => panic!("expected ContratoWitInvalid, got {other:?}"),
14418        }
14419    }
14420
14421    // ── :contratos :subject value-shape gate ─────────────────────────────
14422    //
14423    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
14424    // suites on the peer payload axes. Until this gate landed
14425    // `WitContract::target()` only refused the empty string; a
14426    // structurally invalid subject silently passed validate and the
14427    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
14428    // Subject'` on publish / subscribe, or as a silent message drop,
14429    // far from the source caixa.lisp. Every authoring footgun the
14430    // NATS server's subject parser would catch on admission now
14431    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
14432    // offending `:subject` + `:de` + `:para` named verbatim. Same
14433    // diagnostic shape as `ContratoEndpointInvalid` /
14434    // `ContratoWitInvalid` on the peer payload axes; same shared
14435    // predicate (`crate::render::is_nats_subject`) ensures drift
14436    // between any two axes' rule enforcement is a build error at the
14437    // predicate, not piecemeal across renderers.
14438
14439    fn contrato_subject_err(subject: &str) -> AplicacaoError {
14440        // Fresh spec per call so the new contract doesn't collide on
14441        // identity with `three_member_spec`'s pre-existing entries.
14442        // The new edge uses `(payment, catalog)` — a pair the fixture
14443        // doesn't already declare — with `:wit "nats:pub-sub"` and the
14444        // varying `:subject`, so the subject-shape gate fires cleanly
14445        // after the wit-shape gate (which `"nats:pub-sub"` passes).
14446        let mut s = three_member_spec();
14447        s.contratos.push(WitContract {
14448            de: "payment".into(),
14449            para: "catalog".into(),
14450            wit: "nats:pub-sub".into(),
14451            endpoint: None,
14452            subject: Some(subject.into()),
14453            slot: None,
14454        });
14455        s.validate().unwrap_err()
14456    }
14457
14458    #[test]
14459    fn rejects_pubsub_contrato_subject_with_whitespace() {
14460        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
14461        // landed at the NATS server as a malformed subject the parser
14462        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
14463        // source caixa.lisp.
14464        let err = contrato_subject_err("foo bar");
14465        assert!(
14466            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14467                if subject == "foo bar" && reason.contains("whitespace")),
14468            "got {err:?}"
14469        );
14470    }
14471
14472    #[test]
14473    fn rejects_pubsub_contrato_subject_with_control_char() {
14474        let err = contrato_subject_err("foo\x01bar");
14475        assert!(
14476            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14477                if subject == "foo\x01bar" && reason.contains("control character")),
14478            "got {err:?}"
14479        );
14480    }
14481
14482    #[test]
14483    fn rejects_pubsub_contrato_subject_with_non_ascii() {
14484        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14485        // the subject from a doc with smart quotes / accented
14486        // characters" footgun.
14487        let err = contrato_subject_err("foo.caf\u{e9}");
14488        assert!(
14489            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14490                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
14491            "got {err:?}"
14492        );
14493    }
14494
14495    #[test]
14496    fn rejects_pubsub_contrato_subject_with_leading_dot() {
14497        // Empty leading token — NATS rejects.
14498        let err = contrato_subject_err(".foo");
14499        assert!(
14500            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14501                if subject == ".foo" && reason.contains("must not start with `.`")),
14502            "got {err:?}"
14503        );
14504    }
14505
14506    #[test]
14507    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
14508        // Empty trailing token — NATS rejects. The remediation
14509        // (use `>` instead) is in the reason string.
14510        let err = contrato_subject_err("foo.");
14511        assert!(
14512            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14513                if subject == "foo." && reason.contains("must not end with `.`")),
14514            "got {err:?}"
14515        );
14516    }
14517
14518    #[test]
14519    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
14520        // The canonical "I forgot to fill in the middle segment"
14521        // typo — `"foo..bar"`. NATS rejects empty tokens.
14522        let err = contrato_subject_err("foo..bar");
14523        assert!(
14524            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14525                if subject == "foo..bar" && reason.contains("consecutive `.`")),
14526            "got {err:?}"
14527        );
14528    }
14529
14530    #[test]
14531    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
14532        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
14533        // as the final segment. Pre-gate this passed as a typed edge
14534        // and surfaced at runtime as a NATS subscribe rejection.
14535        let err = contrato_subject_err("foo.>.bar");
14536        assert!(
14537            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14538                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
14539            "got {err:?}"
14540        );
14541    }
14542
14543    #[test]
14544    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
14545        // `foo*.bar` — NATS wildcards are standalone tokens. The
14546        // remediation is in the reason string.
14547        let err = contrato_subject_err("foo*.bar");
14548        assert!(
14549            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14550                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
14551            "got {err:?}"
14552        );
14553    }
14554
14555    #[test]
14556    fn rejects_pubsub_contrato_subject_with_invalid_char() {
14557        // `foo,bar` — comma is not a valid NATS subject character.
14558        // Pinned separately from the wildcard arms so the invalid-
14559        // character diagnostic is in force.
14560        let err = contrato_subject_err("foo,bar");
14561        assert!(
14562            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14563                if subject == "foo,bar" && reason.contains("invalid character")),
14564            "got {err:?}"
14565        );
14566    }
14567
14568    #[test]
14569    fn rejects_pubsub_contrato_subject_too_long() {
14570        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
14571        // The legitimate-shape arms all pass (one all-`a` token, no
14572        // `.`, no wildcards); only the cap arm fires. Surfaces the
14573        // paste-from-binary / accidental-multi-line-blob landing
14574        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
14575        // on the peer axis.
14576        let big = "a".repeat(257);
14577        assert_eq!(big.len(), 257);
14578        let err = contrato_subject_err(&big);
14579        assert!(
14580            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
14581                if subject == &big && reason.contains("max length of 256")),
14582            "got {err:?}"
14583        );
14584    }
14585
14586    #[test]
14587    fn pubsub_contrato_subject_max_length_validates() {
14588        // 256-byte subject — exactly the cap. Boundary pin: drift in
14589        // the cap surfaces here and at
14590        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
14591        // mirroring `http_contrato_endpoint_max_length_validates` and
14592        // `wit_max_length_validates` on the peer axes.
14593        let big = "a".repeat(256);
14594        assert_eq!(big.len(), 256);
14595        let mut s = three_member_spec();
14596        s.contratos.push(WitContract {
14597            de: "payment".into(),
14598            para: "catalog".into(),
14599            wit: "nats:pub-sub".into(),
14600            endpoint: None,
14601            subject: Some(big),
14602            slot: None,
14603        });
14604        s.validate().unwrap();
14605    }
14606
14607    #[test]
14608    fn pubsub_contrato_subject_accepts_canonical_forms() {
14609        // Positive-set sweep: every canonical NATS subject shape the
14610        // substrate-side `is_nats_subject` predicate accepts (the
14611        // multi-dot `events.order.charged`, the snake_case / kebab-
14612        // case / mixed-case tokens, the digit-bearing tokens, the
14613        // single-token wildcard `*` at every segment position, and
14614        // the trailing `>` multi-token wildcard) must remain a valid
14615        // contrato subject too. Drift between this list and the
14616        // substrate-side `nats_subject_accepts_canonical_forms` sweep
14617        // surfaces at the shared predicate — one source of truth.
14618        // Uses a fresh `(payment, catalog)` edge so none of the swept
14619        // subjects collide with the pre-existing entries in
14620        // `three_member_spec`.
14621        for subject in [
14622            "checkout.events.charge.failed",
14623            "rio.events.order.charged",
14624            "orders",
14625            "orders.123",
14626            "snake_case.token",
14627            "kebab-case.token",
14628            "MixedCase.Token",
14629            "orders.*.charged",
14630            "*.events.*",
14631            "orders.>",
14632        ] {
14633            let mut s = three_member_spec();
14634            s.contratos.push(WitContract {
14635                de: "payment".into(),
14636                para: "catalog".into(),
14637                wit: "nats:pub-sub".into(),
14638                endpoint: None,
14639                subject: Some(subject.into()),
14640                slot: None,
14641            });
14642            s.validate()
14643                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
14644        }
14645    }
14646
14647    #[test]
14648    fn contrato_subject_empty_takes_precedence_over_invalid() {
14649        // Ordering pin: `ContratoSubjectEmpty` is the more self-
14650        // locating diagnostic on `""` and must lead — the value-shape
14651        // gate is only reached after the empty-check fires. Mirrors
14652        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14653        // the peer payload axis.
14654        let mut s = three_member_spec();
14655        s.contratos.push(WitContract {
14656            de: "payment".into(),
14657            para: "catalog".into(),
14658            wit: "nats:pub-sub".into(),
14659            endpoint: None,
14660            subject: Some(String::new()),
14661            slot: None,
14662        });
14663        let err = s.validate().unwrap_err();
14664        assert!(
14665            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
14666            "got {err:?}"
14667        );
14668    }
14669
14670    #[test]
14671    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
14672        // Diagnostic-shape pin — the offending `:subject` + `:de` +
14673        // `:para` + a non-empty reason flow through verbatim so the
14674        // author can grep their caixa.lisp for the offending contrato
14675        // block and fix it in one edit. Same shape as
14676        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
14677        // and `wit_invalid_diagnostic_carries_offending_wit`.
14678        let err = contrato_subject_err("foo..bar");
14679        match err {
14680            AplicacaoError::ContratoSubjectInvalid {
14681                de,
14682                para,
14683                subject,
14684                reason,
14685            } => {
14686                assert_eq!(de, "payment");
14687                assert_eq!(para, "catalog");
14688                assert_eq!(subject, "foo..bar");
14689                assert!(!reason.is_empty(), "reason field must be non-empty");
14690            }
14691            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
14692        }
14693    }
14694
14695    #[test]
14696    fn target_view_pubsub_subject_passes_through_to_typed_view() {
14697        // The compounding theorem on the pub-sub axis: every
14698        // `WitTarget::PubSub { subject }` returned by `target()` carries
14699        // a NATS-server-accepted subject. Renderers downstream of
14700        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
14701        // NATS Stream/Consumer CR emitter, the future `feira app graph`
14702        // view's subject labeller) can rely on this without re-checking
14703        // — the type system carries the proof. Mirrors
14704        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
14705        // on the peer axes.
14706        let nats = WitContract {
14707            de: "a".into(),
14708            para: "b".into(),
14709            wit: "nats:pub-sub".into(),
14710            endpoint: None,
14711            subject: Some("orders.events.*.charged".into()),
14712            slot: None,
14713        };
14714        match nats.target().unwrap() {
14715            WitTarget::PubSub { subject } => {
14716                assert_eq!(subject, "orders.events.*.charged");
14717            }
14718            other => panic!("expected PubSub, got {other:?}"),
14719        }
14720    }
14721
14722    // ── :contratos :slot value-shape gate ────────────────────────────────
14723    //
14724    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
14725    // (63e18a0) value-shape suites on the peer payload axes. Until this
14726    // gate landed `WitContract::target()` only refused the empty string
14727    // for the Store arm; a structurally invalid slot (raw whitespace,
14728    // control character, non-ASCII byte, paste-from-binary multi-line
14729    // blob) silently passed validate and surfaced at runtime as a
14730    // per-backend kv write rejection or a silent next-read corruption,
14731    // far from the source caixa.lisp with no field naming which
14732    // `:contratos` edge carried the typo. Every authoring footgun the
14733    // kv backend intersection-floor would catch on write now becomes a
14734    // caixa-build-time `ContratoSlotInvalid` with the offending
14735    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
14736    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
14737    // peer payload axes; same shared predicate
14738    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
14739    // any two axes' rule enforcement is a build error at the
14740    // predicate, not piecemeal across renderers. Closes the typed
14741    // payload-axis value-shape trajectory across all three legs of the
14742    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
14743
14744    fn contrato_slot_err(slot: &str) -> AplicacaoError {
14745        // Fresh spec per call so the new contract doesn't collide on
14746        // identity with `three_member_spec`'s pre-existing entries
14747        // and doesn't close a synchronous cycle the cycle detector
14748        // would reject before the slot-shape gate fires. The new edge
14749        // uses `(payment, catalog)` — a pair the fixture doesn't
14750        // already declare in either direction (the fixture carries
14751        // `cart -> catalog` and `cart -> payment`, so `payment ->
14752        // catalog` doesn't form a cycle on the sync subgraph) — with
14753        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
14754        // slot-shape gate fires cleanly after the wit-shape gate
14755        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
14756        // peer `contrato_subject_err` helper uses (63e18a0).
14757        let mut s = three_member_spec();
14758        s.contratos.push(WitContract {
14759            de: "payment".into(),
14760            para: "catalog".into(),
14761            wit: "wasi:keyvalue/store".into(),
14762            endpoint: None,
14763            subject: None,
14764            slot: Some(slot.into()),
14765        });
14766        s.validate().unwrap_err()
14767    }
14768
14769    #[test]
14770    fn rejects_store_contrato_slot_with_whitespace() {
14771        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
14772        // silently landed at the kv backend with whitespace whose
14773        // runtime behavior varies unpredictably across backends (etcd
14774        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
14775        // rejects on write). Now caught at the source caixa.lisp.
14776        let err = contrato_slot_err("check out/$order");
14777        assert!(
14778            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14779                if slot == "check out/$order" && reason.contains("whitespace")),
14780            "got {err:?}"
14781        );
14782    }
14783
14784    #[test]
14785    fn rejects_store_contrato_slot_with_tab() {
14786        // Tab byte arm-pinned separately from the space arm so a
14787        // future relaxation that admits one but not the other surfaces
14788        // here.
14789        let err = contrato_slot_err("check\tout");
14790        assert!(
14791            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14792                if slot == "check\tout" && reason.contains("whitespace")),
14793            "got {err:?}"
14794        );
14795    }
14796
14797    #[test]
14798    fn rejects_store_contrato_slot_with_control_char() {
14799        // SOH (0x01) — distinct from the whitespace arm. Redis admits
14800        // and corrupts on RESP protocol framing; DynamoDB rejects on
14801        // write.
14802        let err = contrato_slot_err("checkout/\x01order");
14803        assert!(
14804            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14805                if slot == "checkout/\x01order" && reason.contains("control character")),
14806            "got {err:?}"
14807        );
14808    }
14809
14810    #[test]
14811    fn rejects_store_contrato_slot_with_newline() {
14812        // Embedded newline — the canonical "the paste-from-binary slug
14813        // spans multiple lines" footgun. Distinct from the whitespace
14814        // arm because `\n` is a control character (0x0A).
14815        let err = contrato_slot_err("checkout\norder");
14816        assert!(
14817            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14818                if slot == "checkout\norder" && reason.contains("control character")),
14819            "got {err:?}"
14820        );
14821    }
14822
14823    #[test]
14824    fn rejects_store_contrato_slot_with_non_ascii() {
14825        // Un-percent-encoded non-ASCII byte — the canonical "I copied
14826        // the slot from a doc with accented characters" footgun. Each
14827        // kv backend re-encodes non-ASCII differently (etcd preserves
14828        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
14829        // rejects), so the typed slot's value set is the intersection-
14830        // floor every backend admits identically (printable ASCII).
14831        let err = contrato_slot_err("ch\u{e9}ckout/$order");
14832        assert!(
14833            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14834                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
14835            "got {err:?}"
14836        );
14837    }
14838
14839    #[test]
14840    fn rejects_store_contrato_slot_too_long() {
14841        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
14842        // legitimate-shape arms all pass (a single all-`a` token, no
14843        // separators); only the cap arm fires. Surfaces the paste-
14844        // from-binary / accidental-multi-line-blob landing footgun.
14845        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
14846        // `rejects_http_contrato_endpoint_too_long` on the peer
14847        // payload axes.
14848        let big = "a".repeat(513);
14849        assert_eq!(big.len(), 513);
14850        let err = contrato_slot_err(&big);
14851        assert!(
14852            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
14853                if slot == &big && reason.contains("max length of 512")),
14854            "got {err:?}"
14855        );
14856    }
14857
14858    #[test]
14859    fn store_contrato_slot_max_length_validates() {
14860        // 512-byte slot — exactly the cap. Boundary pin: drift in the
14861        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
14862        // simultaneously, mirroring
14863        // `pubsub_contrato_subject_max_length_validates` and
14864        // `http_contrato_endpoint_max_length_validates` on the peer
14865        // payload axes.
14866        let big = "a".repeat(512);
14867        assert_eq!(big.len(), 512);
14868        let mut s = three_member_spec();
14869        s.contratos.push(WitContract {
14870            de: "payment".into(),
14871            para: "catalog".into(),
14872            wit: "wasi:keyvalue/store".into(),
14873            endpoint: None,
14874            subject: None,
14875            slot: Some(big),
14876        });
14877        s.validate().unwrap();
14878    }
14879
14880    #[test]
14881    fn store_contrato_slot_accepts_canonical_forms() {
14882        // Positive-set sweep: every canonical kv slot template the
14883        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
14884        // (single-token identifiers, path-namespaced `$`-templates,
14885        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
14886        // snake_case / kebab-case / MixedCase tokens, digit-bearing
14887        // tokens, percent-encoded fragments) must remain valid
14888        // contrato slots too. Drift between this list and the
14889        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
14890        // surfaces at the shared predicate — one source of truth.
14891        // Uses a fresh `(payment, catalog)` edge so none of the swept
14892        // slots collide with the pre-existing entries in
14893        // `three_member_spec`.
14894        for slot in [
14895            "checkout",
14896            "checkout/$orderId",
14897            "users:{tenant}/{id}",
14898            "session.<sid>",
14899            "session.tokens.<sid>",
14900            "snake_case_key",
14901            "kebab-case-key",
14902            "MixedCase",
14903            "shard0",
14904            "v2/key",
14905            "users/caf%C3%A9",
14906        ] {
14907            let mut s = three_member_spec();
14908            s.contratos.push(WitContract {
14909                de: "payment".into(),
14910                para: "catalog".into(),
14911                wit: "wasi:keyvalue/store".into(),
14912                endpoint: None,
14913                subject: None,
14914                slot: Some(slot.into()),
14915            });
14916            s.validate()
14917                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
14918        }
14919    }
14920
14921    #[test]
14922    fn contrato_slot_empty_takes_precedence_over_invalid() {
14923        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
14924        // diagnostic on `""` and must lead — the value-shape gate is
14925        // only reached after the empty-check fires. Mirrors
14926        // `contrato_subject_empty_takes_precedence_over_invalid` and
14927        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
14928        // the peer payload axes.
14929        let mut s = three_member_spec();
14930        s.contratos.push(WitContract {
14931            de: "payment".into(),
14932            para: "catalog".into(),
14933            wit: "wasi:keyvalue/store".into(),
14934            endpoint: None,
14935            subject: None,
14936            slot: Some(String::new()),
14937        });
14938        let err = s.validate().unwrap_err();
14939        assert!(
14940            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
14941            "got {err:?}"
14942        );
14943    }
14944
14945    #[test]
14946    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
14947        // Diagnostic-shape pin — the offending `:slot` + `:de` +
14948        // `:para` + a non-empty reason flow through verbatim so the
14949        // author can grep their caixa.lisp for the offending contrato
14950        // block and fix it in one edit. Same shape as
14951        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
14952        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
14953        // on the peer payload axes.
14954        let err = contrato_slot_err("check out/$order");
14955        match err {
14956            AplicacaoError::ContratoSlotInvalid {
14957                de,
14958                para,
14959                slot,
14960                reason,
14961            } => {
14962                assert_eq!(de, "payment");
14963                assert_eq!(para, "catalog");
14964                assert_eq!(slot, "check out/$order");
14965                assert!(!reason.is_empty(), "reason field must be non-empty");
14966            }
14967            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
14968        }
14969    }
14970
14971    #[test]
14972    fn target_view_store_slot_passes_through_to_typed_view() {
14973        // The compounding theorem on the store axis: every
14974        // `WitTarget::Store { slot }` returned by `target()` carries a
14975        // kv-backend-accepted slot template. Renderers downstream of
14976        // `typed_view()` (the future per-Servico `:capabilities
14977        // wasi:keyvalue/store` axis emitter, the future `feira app
14978        // graph` view's slot labeller, the future kv-provider CR
14979        // materializer) can rely on this without re-checking — the
14980        // type system carries the proof. Mirrors
14981        // `target_view_pubsub_subject_passes_through_to_typed_view` on
14982        // the peer payload axis.
14983        let store = WitContract {
14984            de: "a".into(),
14985            para: "b".into(),
14986            wit: "wasi:keyvalue/store".into(),
14987            endpoint: None,
14988            subject: None,
14989            slot: Some("checkout/$orderId".into()),
14990        };
14991        match store.target().unwrap() {
14992            WitTarget::Store { slot } => {
14993                assert_eq!(slot, "checkout/$orderId");
14994            }
14995            other => panic!("expected Store, got {other:?}"),
14996        }
14997    }
14998
14999    #[test]
15000    fn rejects_self_loop_in_synchronous_contratos() {
15001        // A synchronous self-edge (`cart → cart` over HTTP) is now
15002        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
15003        // "this edge is degenerate" diagnostic — rather than incidentally
15004        // by the cycle detector framing it as a `["cart", "cart"]`
15005        // multi-node deadlock.
15006        let mut s = three_member_spec();
15007        s.contratos.push(contract_http("cart", "cart", "/loop"));
15008        let err = s.validate().unwrap_err();
15009        match err {
15010            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
15011                assert_eq!(caixa, "cart");
15012                assert_eq!(wit, "wasi:http/proxy");
15013            }
15014            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15015        }
15016    }
15017
15018    #[test]
15019    fn rejects_self_loop_in_pubsub_contratos() {
15020        // The cycle detector excludes pub-sub edges (acyclic by
15021        // construction), so before the explicit gate a `nats:pub-sub`
15022        // self-edge silently validated and rendered a self-allow CNP.
15023        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
15024        let mut s = three_member_spec();
15025        s.contratos.push(WitContract {
15026            de: "payment".into(),
15027            para: "payment".into(),
15028            wit: "nats:pub-sub".into(),
15029            endpoint: None,
15030            subject: Some("rio.events.payment".into()),
15031            slot: None,
15032        });
15033        let err = s.validate().unwrap_err();
15034        match err {
15035            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
15036                assert_eq!(caixa, "payment");
15037                assert_eq!(wit, "nats:pub-sub");
15038            }
15039            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15040        }
15041    }
15042
15043    #[test]
15044    fn self_loop_fires_before_payload_shape_check() {
15045        // The structural "this edge can't exist" error precedes the
15046        // narrower payload-shape diagnostics: a self-edge carrying an
15047        // otherwise-malformed endpoint still reports ContratoSelfLoop,
15048        // not ContratoEndpointInvalid.
15049        let mut s = three_member_spec();
15050        s.contratos.push(WitContract {
15051            de: "cart".into(),
15052            para: "cart".into(),
15053            wit: "wasi:http/proxy".into(),
15054            endpoint: Some("not-absolute".into()),
15055            subject: None,
15056            slot: None,
15057        });
15058        match s.validate().unwrap_err() {
15059            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
15060            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15061        }
15062    }
15063
15064    #[test]
15065    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
15066        // A self-edge naming a non-member reports the more fundamental
15067        // ContratoMemberMissing first (the member doesn't exist), so the
15068        // self-loop gate is reached only once both endpoints resolve.
15069        let mut s = three_member_spec();
15070        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
15071        match s.validate().unwrap_err() {
15072            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
15073            other => panic!("expected ContratoMemberMissing, got {other:?}"),
15074        }
15075    }
15076
15077    #[test]
15078    fn rejects_two_node_synchronous_cycle() {
15079        let mut s = three_member_spec();
15080        // existing edges: cart → catalog, cart → payment
15081        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
15082        s.contratos
15083            .push(contract_http("catalog", "cart", "/refresh"));
15084        let err = s.validate().unwrap_err();
15085        match err {
15086            AplicacaoError::ContratoCycle { cycle } => {
15087                // Cycle traversal should mention both endpoints, with
15088                // the back-edge target appearing as both first and last
15089                // element to close the loop.
15090                assert!(cycle.len() >= 3);
15091                assert_eq!(cycle.first(), cycle.last());
15092                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
15093                assert!(body.contains("cart"));
15094                assert!(body.contains("catalog"));
15095            }
15096            other => panic!("expected ContratoCycle, got {other:?}"),
15097        }
15098    }
15099
15100    #[test]
15101    fn rejects_three_node_synchronous_cycle() {
15102        let mut s = three_member_spec();
15103        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
15104        s.contratos = vec![
15105            contract_http("catalog", "cart", "/x"),
15106            contract_http("cart", "payment", "/y"),
15107            contract_http("payment", "catalog", "/z"),
15108        ];
15109        let err = s.validate().unwrap_err();
15110        match err {
15111            AplicacaoError::ContratoCycle { cycle } => {
15112                assert_eq!(cycle.first(), cycle.last());
15113                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
15114                assert_eq!(body.len(), 3);
15115                assert!(body.contains("cart"));
15116                assert!(body.contains("catalog"));
15117                assert!(body.contains("payment"));
15118            }
15119            other => panic!("expected ContratoCycle, got {other:?}"),
15120        }
15121    }
15122
15123    #[test]
15124    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
15125        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
15126        // "acyclic by construction" — so a cycle whose closing edge
15127        // is pub-sub should NOT raise ContratoCycle.
15128        let mut s = three_member_spec();
15129        s.contratos = vec![
15130            contract_http("catalog", "cart", "/x"),
15131            contract_http("cart", "payment", "/y"),
15132            // Closing edge is pub-sub — async; not a sync deadlock.
15133            WitContract {
15134                de: "payment".into(),
15135                para: "catalog".into(),
15136                wit: "nats:pub-sub".into(),
15137                endpoint: None,
15138                subject: Some("checkout.events.charge.completed".into()),
15139                slot: None,
15140            },
15141        ];
15142        s.validate().expect("pub-sub edge breaks the sync cycle");
15143    }
15144
15145    #[test]
15146    fn store_edge_counts_as_synchronous_for_cycle_detection() {
15147        // wasi:keyvalue/store is request/response; a cycle through one
15148        // *is* a sync deadlock, just like HTTP.
15149        let mut s = three_member_spec();
15150        s.contratos = vec![
15151            contract_http("catalog", "cart", "/x"),
15152            WitContract {
15153                de: "cart".into(),
15154                para: "catalog".into(),
15155                wit: "wasi:keyvalue/store".into(),
15156                endpoint: None,
15157                subject: None,
15158                slot: Some("session/$id".into()),
15159            },
15160        ];
15161        let err = s.validate().unwrap_err();
15162        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
15163    }
15164
15165    #[test]
15166    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
15167        // Capability-only edges (unknown WIT shape, no payload) default
15168        // to synchronous — safer; authors with truly async capability
15169        // semantics can model them as pub-sub explicitly.
15170        let mut s = three_member_spec();
15171        s.contratos = vec![
15172            contract_http("catalog", "cart", "/x"),
15173            WitContract {
15174                de: "cart".into(),
15175                para: "catalog".into(),
15176                wit: "custom:exchange".into(),
15177                endpoint: None,
15178                subject: None,
15179                slot: None,
15180            },
15181        ];
15182        let err = s.validate().unwrap_err();
15183        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
15184    }
15185
15186    #[test]
15187    fn long_acyclic_chain_validates() {
15188        // A long sync chain (no back-edges) must validate even when
15189        // every node is reachable from the first.
15190        let mut s = three_member_spec();
15191        s.membros = vec![
15192            membro("a", "^0.1"),
15193            membro("b", "^0.1"),
15194            membro("c", "^0.1"),
15195            membro("d", "^0.1"),
15196            membro("e", "^0.1"),
15197        ];
15198        s.contratos = vec![
15199            contract_http("a", "b", "/1"),
15200            contract_http("b", "c", "/2"),
15201            contract_http("c", "d", "/3"),
15202            contract_http("d", "e", "/4"),
15203        ];
15204        s.entrada.as_mut().unwrap().para = "a".into();
15205        s.validate().unwrap();
15206    }
15207
15208    #[test]
15209    fn diamond_acyclic_validates() {
15210        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
15211        let mut s = three_member_spec();
15212        s.membros = vec![
15213            membro("a", "^0.1"),
15214            membro("b", "^0.1"),
15215            membro("c", "^0.1"),
15216            membro("d", "^0.1"),
15217        ];
15218        s.contratos = vec![
15219            contract_http("a", "b", "/1"),
15220            contract_http("a", "c", "/2"),
15221            contract_http("b", "d", "/3"),
15222            contract_http("c", "d", "/4"),
15223        ];
15224        s.entrada.as_mut().unwrap().para = "a".into();
15225        s.validate().unwrap();
15226    }
15227
15228    // ── duplicate-`:contratos` build-error gate ──────────────────────────
15229
15230    #[test]
15231    fn rejects_duplicate_http_contrato() {
15232        // Fail-before-pass-after pin: the fixture's `cart → catalog`
15233        // HTTP edge appears once. Push an identical entry — same
15234        // (de, para, wit, endpoint) — and validate() must reject it.
15235        // Until this gate landed the typed surface accepted the
15236        // duplicate silently and caixa-mesh's `cilium_network_policies`
15237        // emitted two ``CiliumNetworkPolicy`` objects with identical
15238        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
15239        // admission rejects on `kubectl apply` far from the source.
15240        let mut s = three_member_spec();
15241        s.contratos
15242            .push(contract_http("cart", "catalog", "/products/:id"));
15243        let err = s.validate().unwrap_err();
15244        assert!(
15245            matches!(
15246                err,
15247                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15248                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
15249            ),
15250            "got {err:?}"
15251        );
15252    }
15253
15254    #[test]
15255    fn rejects_duplicate_pubsub_contrato() {
15256        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
15257        // edges with identical (de, para, subject) are degenerate;
15258        // pin that the typed surface refuses both at validate time.
15259        let mut s = three_member_spec();
15260        let pubsub = WitContract {
15261            de: "payment".into(),
15262            para: "cart".into(),
15263            wit: "nats:pub-sub".into(),
15264            endpoint: None,
15265            subject: Some("checkout.events.charge.failed".into()),
15266            slot: None,
15267        };
15268        s.contratos.push(pubsub.clone());
15269        s.contratos.push(pubsub);
15270        let err = s.validate().unwrap_err();
15271        assert!(
15272            matches!(
15273                err,
15274                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15275                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
15276            ),
15277            "got {err:?}"
15278        );
15279    }
15280
15281    #[test]
15282    fn rejects_duplicate_store_contrato() {
15283        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
15284        // edges with identical (de, para, slot) collapse to one mesh-
15285        // policy edge; pin the build error.
15286        let mut s = three_member_spec();
15287        let store = WitContract {
15288            de: "cart".into(),
15289            para: "payment".into(),
15290            wit: "wasi:keyvalue/store".into(),
15291            endpoint: None,
15292            subject: None,
15293            slot: Some("checkout/$orderId".into()),
15294        };
15295        // Drop the conflicting HTTP `cart → payment` edge from the
15296        // fixture so the duplicate-store pair is the only one
15297        // distinguishable on this pair.
15298        s.contratos
15299            .retain(|c| !(c.de == "cart" && c.para == "payment"));
15300        s.contratos.push(store.clone());
15301        s.contratos.push(store);
15302        let err = s.validate().unwrap_err();
15303        assert!(
15304            matches!(
15305                err,
15306                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15307                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
15308            ),
15309            "got {err:?}"
15310        );
15311    }
15312
15313    #[test]
15314    fn rejects_duplicate_capability_contrato() {
15315        // Same gate on the pure-capability axis (no payload selector).
15316        // Two contracts with identical (de, para, wit) and no
15317        // endpoint/subject/slot are duplicate edges; pin so a future
15318        // `target_label` change can't accidentally collapse the
15319        // capability arm into a None-shaped key that compares equal
15320        // to a populated one.
15321        let mut s = three_member_spec();
15322        let capability = WitContract {
15323            de: "cart".into(),
15324            para: "catalog".into(),
15325            wit: "pleme:cap/audit".into(),
15326            endpoint: None,
15327            subject: None,
15328            slot: None,
15329        };
15330        s.contratos.push(capability.clone());
15331        s.contratos.push(capability);
15332        let err = s.validate().unwrap_err();
15333        match err {
15334            AplicacaoError::ContratoDuplicate {
15335                de,
15336                para,
15337                wit,
15338                target,
15339            } => {
15340                assert_eq!(de, "cart");
15341                assert_eq!(para, "catalog");
15342                assert_eq!(wit, "pleme:cap/audit");
15343                assert!(
15344                    target.contains("capability"),
15345                    "capability-edge duplicate diagnostic must surface the \
15346                     no-payload shape (got target = {target:?})"
15347                );
15348            }
15349            other => panic!("expected ContratoDuplicate, got {other:?}"),
15350        }
15351    }
15352
15353    #[test]
15354    fn accepts_distinct_http_paths_between_same_pair() {
15355        // Negative pin: two HTTP contracts cart → catalog at distinct
15356        // endpoints (`/products/:id` and `/search`) are *not*
15357        // duplicates — they're distinct typed edges differing on the
15358        // payload axis. The duplicate-gate must not over-match here,
15359        // since the cart-calls-catalog-on-multiple-paths shape is the
15360        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
15361        // example: cart calls catalog at /products/:id, payment at
15362        // /charge — same shape extends to two paths on one para).
15363        let mut s = three_member_spec();
15364        s.contratos
15365            .push(contract_http("cart", "catalog", "/search"));
15366        s.validate()
15367            .expect("distinct endpoints between same (de, para) must validate");
15368    }
15369
15370    #[test]
15371    fn accepts_same_endpoint_on_different_pairs() {
15372        // Negative pin: the same `/charge` endpoint reused on two
15373        // different (de, para) pairs is two distinct edges, not a
15374        // duplicate. Pinning this shape so the gate's identity key
15375        // includes both `de` and `para` (not just `(wit, endpoint)`).
15376        let mut s = three_member_spec();
15377        s.contratos
15378            .push(contract_http("payment", "catalog", "/charge"));
15379        s.validate()
15380            .expect("same endpoint reused on distinct (de, para) must validate");
15381    }
15382
15383    #[test]
15384    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
15385        // Pin the diagnostic shape: the duplicate-edge error names
15386        // *which* target field carried the conflict, so the author
15387        // doesn't have to re-grep the source caixa.lisp to find it.
15388        // Same self-locating diagnostic discipline as
15389        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
15390        let mut s = three_member_spec();
15391        s.contratos
15392            .push(contract_http("cart", "catalog", "/products/:id"));
15393        let err = s.validate().unwrap_err();
15394        let msg = format!("{err}");
15395        assert!(
15396            msg.contains("\"/products/:id\""),
15397            "duplicate-contrato diagnostic must name the offending \
15398             :endpoint payload (got: {msg:?})"
15399        );
15400        assert!(
15401            msg.contains("cart") && msg.contains("catalog"),
15402            "diagnostic must name both endpoints of the duplicate edge \
15403             (got: {msg:?})"
15404        );
15405    }
15406
15407    #[test]
15408    fn duplicate_contrato_gate_runs_after_membership_check() {
15409        // Order pin: a duplicate contract whose `:de` is *also* not in
15410        // `:membros` surfaces the membership error first — the
15411        // missing-member diagnostic is more locating than the
15412        // duplicate-edge one (the author has to fix the membership
15413        // before the duplicate is meaningful). Same ordering
15414        // discipline as `membros_validation_runs_before_contratos_membership_check`.
15415        let mut s = three_member_spec();
15416        s.contratos.push(contract_http("phantom", "catalog", "/x"));
15417        s.contratos.push(contract_http("phantom", "catalog", "/x"));
15418        let err = s.validate().unwrap_err();
15419        assert!(
15420            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
15421            "membership-missing must fire before duplicate-edge (got {err:?})"
15422        );
15423    }
15424
15425    #[test]
15426    fn duplicate_contrato_gate_runs_after_target_shape_check() {
15427        // Order pin: a contract with a malformed target (e.g. an HTTP
15428        // wit world with an empty :endpoint) surfaces the target-shape
15429        // error first, not the duplicate one. Even when two such
15430        // malformed entries are identical, the per-contract `target()`
15431        // check fires inside the loop *before* the duplicate-key
15432        // insert, so the diagnostic remains the most-locating one.
15433        let mut s = three_member_spec();
15434        let malformed = WitContract {
15435            de: "cart".into(),
15436            para: "catalog".into(),
15437            wit: "wasi:http/proxy".into(),
15438            endpoint: Some(String::new()),
15439            subject: None,
15440            slot: None,
15441        };
15442        s.contratos.push(malformed.clone());
15443        s.contratos.push(malformed);
15444        let err = s.validate().unwrap_err();
15445        assert!(
15446            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
15447            "endpoint-empty must fire before duplicate-edge (got {err:?})"
15448        );
15449    }
15450
15451    #[test]
15452    fn wit_target_label_pins_per_variant_format() {
15453        // Label format is the single source of truth every duplicate-
15454        // `:contratos` diagnostic + every future `feira app graph`
15455        // consumer routes through. Pin the shape per variant so a
15456        // future edit to `WitTarget::label` (e.g. a JSON emitter that
15457        // strips the leading `:`, or a rename from `endpoint` →
15458        // `path`) surfaces as a red-red test rather than as a silent
15459        // downstream diagnostic drift. Together with the exhaustive
15460        // `match` on `WitTarget` inside `label()`, adding a future
15461        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
15462        // peer, per-edge WIT registry variants) is a compile error at
15463        // the label site — not a fall-through into the `Capability`
15464        // "no payload" default the prior raw-field-probe helper
15465        // silently landed on.
15466        assert_eq!(
15467            WitTarget::Http {
15468                endpoint: "/charge",
15469            }
15470            .label(),
15471            "\
15472:endpoint \"/charge\""
15473        );
15474        assert_eq!(
15475            WitTarget::PubSub {
15476                subject: "events.checkout.paid",
15477            }
15478            .label(),
15479            "\
15480:subject \"events.checkout.paid\""
15481        );
15482        assert_eq!(
15483            WitTarget::Store {
15484                slot: "checkout/$order",
15485            }
15486            .label(),
15487            "\
15488:slot \"checkout/$order\""
15489        );
15490        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
15491        // Capability-arm label routes through the lifted
15492        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
15493        // declaration per arm, next to the variant" discipline the
15494        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
15495        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15496        // consts already carry extends to the payload-less arm; the
15497        // byte-string equality pin below plus this label-routes-
15498        // through-the-const pin make a future rebrand on either the
15499        // const declaration or the `label()` template a build error
15500        // here rather than a downstream consumer surprise.
15501        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
15502        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
15503    }
15504
15505    #[test]
15506    fn wit_target_display_routes_through_label_helper() {
15507        // Fail-before-pass-after pin on the fourth (and only remaining)
15508        // typed-shape-discriminator axis to converge onto the
15509        // three-path-convergence discipline the sibling M3
15510        // [`PlacementStrategy`] (0a2f653) and M2
15511        // [`crate::supervisor::RestartStrategy`] /
15512        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
15513        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
15514        // through [`WitTarget::label`], so every consumer reaching for
15515        // `format!("{v}")` on a typed payload target lands on the same
15516        // stable author-facing byte-string [`WitTarget::label`] returns
15517        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
15518        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
15519        // `:contratos` gate seeds via [`WitTarget::label`] at
15520        // aplicacao.rs:5491 already threads through.
15521        //
15522        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
15523        // through to the `Debug` derive's structural output
15524        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
15525        // rather than the [`WitTarget::label`] helper's stable byte-
15526        // string (`:endpoint "/charge"` — the author-facing `:contratos`
15527        // keyword form). Every future consumer that reaches for
15528        // `format!("{target}")` — the canonical shape every user-facing
15529        // pretty-print site on the sibling typed-enum axes
15530        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
15531        // [`crate::supervisor::RestartPolicy`]) already uses — would
15532        // silently land under a different byte-string than the
15533        // [`WitTarget::label`] callers that the duplicate-`:contratos`
15534        // diagnostic already threads through, with the mismatch
15535        // surfacing as a downstream diagnostic / graph / audit line
15536        // reading one spelling while the substrate's own gate emitted
15537        // another.
15538        //
15539        // Pin the routing here so a future
15540        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
15541        // that hand-rolls the per-arm formatting instead of delegating
15542        // to [`WitTarget::label`] fails at caixa-core build time.
15543        for variant in [
15544            WitTarget::Http {
15545                endpoint: "/charge",
15546            },
15547            WitTarget::PubSub {
15548                subject: "events.checkout.paid",
15549            },
15550            WitTarget::Store {
15551                slot: "checkout/$order",
15552            },
15553            WitTarget::Capability,
15554        ] {
15555            assert_eq!(
15556                variant.to_string(),
15557                variant.label(),
15558                "WitTarget::{variant:?} Display must route through \
15559                 WitTarget::label (single source of truth: the lifted \
15560                 payload_pair 4-arm dispatch the label helper already \
15561                 threads through)"
15562            );
15563        }
15564    }
15565
15566    #[test]
15567    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
15568        // Consumer-side pin on the three-path convergence:
15569        // [`std::fmt::Display`] agrees byte-for-byte with the
15570        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
15571        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
15572        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
15573        // Pre-lift the two paths were structurally independent — the
15574        // substrate-side gate reached for `target_view.label()` while a
15575        // future downstream diagnostic / graph / audit line reaching
15576        // for `format!("{target}")` would silently land on the `Debug`
15577        // derive's structural output. Pin the two paths byte-for-byte
15578        // here so any future variant addition (M4 `Rest`/`Grpc` split
15579        // of [`WitTarget::Http`], `Queue`-shaped peer of
15580        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
15581        // match error at [`WitTarget::payload_pair`] rather than a
15582        // silent per-consumer dispatch miss.
15583        for variant in [
15584            WitTarget::Http {
15585                endpoint: "/charge",
15586            },
15587            WitTarget::PubSub {
15588                subject: "events.checkout.paid",
15589            },
15590            WitTarget::Store {
15591                slot: "checkout/$order",
15592            },
15593            WitTarget::Capability,
15594        ] {
15595            assert_eq!(
15596                format!("{variant}"),
15597                variant.label(),
15598                "WitTarget::{variant:?} Display byte-string must match \
15599                 the AplicacaoError::ContratoDuplicate `target:` carrier \
15600                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
15601                 seeds via WitTarget::label — three-path convergence: \
15602                 Display + label + payload_pair all resolve to the same \
15603                 per-arm byte-string"
15604            );
15605        }
15606    }
15607
15608    #[test]
15609    fn wit_target_payload_pair_pins_per_variant() {
15610        // Pin the per-arm `(field-name, payload)` pair single-sourced
15611        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
15612        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
15613        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
15614        // and [`WitTarget::field_name`] (returns the first component)
15615        // route through. Until this lift landed [`WitTarget::label`]
15616        // dispatched on the same three arms with a per-arm
15617        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
15618        // paired [`WitTarget::HTTP_FIELD_NAME`] /
15619        // [`WitTarget::PUBSUB_FIELD_NAME`] /
15620        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
15621        // canonical "same shape, written N times" duplication
15622        // THEORY.md §I.3.5 promotes to a build-time concern. A future
15623        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
15624        // [`WitTarget::Http`], `Queue`-shaped peer of
15625        // [`WitTarget::Store`]) is one match-arm edit at
15626        // [`WitTarget::payload_pair`], visible here as a compile-time
15627        // exhaustiveness error on both this pin and the label-format
15628        // pin above.
15629        assert_eq!(
15630            WitTarget::Http {
15631                endpoint: "/charge"
15632            }
15633            .payload_pair(),
15634            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
15635        );
15636        assert_eq!(
15637            WitTarget::PubSub {
15638                subject: "events.x",
15639            }
15640            .payload_pair(),
15641            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
15642        );
15643        assert_eq!(
15644            WitTarget::Store {
15645                slot: "checkout/$order",
15646            }
15647            .payload_pair(),
15648            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
15649        );
15650        assert_eq!(WitTarget::Capability.payload_pair(), None);
15651    }
15652
15653    #[test]
15654    fn wit_target_field_name_pins_per_variant() {
15655        // Pin the per-arm author-facing `:contratos` payload field
15656        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
15657        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
15658        // + returned by [`WitTarget::field_name`]. Every downstream
15659        // consumer (the [`WitContract::target`] gate's `expected:`
15660        // scalar, the [`WitTarget::label`] template's keyword prefix,
15661        // the `feira app graph` verb's `endpoint=…` prefix) routes
15662        // through the same three peer consts, so a rename on the
15663        // author-surface `(defcaixa … :contratos ((:de … :para …
15664        // :wit … :endpoint …)))` field lands in exactly one place.
15665        assert_eq!(
15666            WitTarget::Http {
15667                endpoint: "/charge"
15668            }
15669            .field_name(),
15670            Some(WitTarget::HTTP_FIELD_NAME),
15671        );
15672        assert_eq!(
15673            WitTarget::PubSub {
15674                subject: "events.x",
15675            }
15676            .field_name(),
15677            Some(WitTarget::PUBSUB_FIELD_NAME),
15678        );
15679        assert_eq!(
15680            WitTarget::Store {
15681                slot: "checkout/$order",
15682            }
15683            .field_name(),
15684            Some(WitTarget::STORE_FIELD_NAME),
15685        );
15686        // Capability arm carries no payload field — the diagnostic
15687        // never reports `expected: "capability"` because the gate's
15688        // Capability arm accepts no payload at all (it fires the
15689        // "expected: none" WrongTarget error instead), so the field-
15690        // name method returns None here rather than a placeholder.
15691        assert_eq!(WitTarget::Capability.field_name(), None);
15692
15693        // Peer const scalar values pinned so a rename on either side
15694        // (author-surface field name in the `(defcaixa …)` DSL, or
15695        // the diagnostic's `expected:` scalar) can't drift without
15696        // failing here first.
15697        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
15698        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
15699        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
15700    }
15701
15702    #[test]
15703    fn wit_target_payload_pins_per_variant() {
15704        // Pin the per-arm payload scalar single-sourced onto the
15705        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
15706        // [`WitTarget::payload`] — the peer per-half projection to
15707        // [`WitTarget::field_name`] on the paired sub-selector axis. The
15708        // three payload-carrying arms round-trip their author-declared
15709        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
15710        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
15711        // the payload-less [`WitTarget::Capability`] arm returns `None`.
15712        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
15713        // (c6ec2af) pin on the Component-0 projection axis, extended
15714        // onto the Component-1 projection axis so both per-half readers
15715        // on the paired dispatch carry their own byte-shape pin.
15716        assert_eq!(
15717            WitTarget::Http {
15718                endpoint: "/charge",
15719            }
15720            .payload(),
15721            Some("/charge"),
15722        );
15723        assert_eq!(
15724            WitTarget::PubSub {
15725                subject: "events.x",
15726            }
15727            .payload(),
15728            Some("events.x"),
15729        );
15730        assert_eq!(
15731            WitTarget::Store {
15732                slot: "checkout/$order",
15733            }
15734            .payload(),
15735            Some("checkout/$order"),
15736        );
15737        assert_eq!(WitTarget::Capability.payload(), None);
15738    }
15739
15740    #[test]
15741    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
15742        // Per-variant equivalence pin: for every arm of [`WitTarget`],
15743        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
15744        // byte-for-byte. Guards the drift surface where a future refactor
15745        // that split one accessor off the shared match onto its own
15746        // dispatch — a well-meaning "inline the pair back into per-half
15747        // fields for one crate-internal caller who only wanted one half"
15748        // or a scratch `impl` shadowing the derived projection — would
15749        // silently desynchronize [`WitTarget::payload`] from the
15750        // authoritative [`WitTarget::payload_pair`] dispatch, and every
15751        // downstream consumer that thinks "the payload half of the pair"
15752        // would drift from the diagnostic / graph consumers reading the
15753        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
15754        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
15755        // per-half projection pin (`gitrefspec_ref_pair_projects_
15756        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
15757        // FluxCD source-controller `spec.ref.<field>` axis — same "one
15758        // paired dispatch, both per-half projections agree byte-for-
15759        // byte" discipline extended onto the M3 `:contratos` payload-
15760        // arm surface.
15761        for variant in [
15762            WitTarget::Http {
15763                endpoint: "/charge",
15764            },
15765            WitTarget::PubSub {
15766                subject: "events.checkout.paid",
15767            },
15768            WitTarget::Store {
15769                slot: "checkout/$order",
15770            },
15771            WitTarget::Capability,
15772        ] {
15773            let via_projection = variant.payload();
15774            let via_pair = variant.payload_pair().map(|(_, p)| p);
15775            assert_eq!(
15776                via_projection, via_pair,
15777                "WitTarget::{variant:?} payload() must equal \
15778                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
15779                 regression that splits the two per-half projections off \
15780                 their shared match would silently desynchronize the \
15781                 payload accessor from the paired dispatch every \
15782                 diagnostic / graph consumer reads through",
15783            );
15784        }
15785    }
15786
15787    #[test]
15788    fn wit_target_http_endpoint_pins_per_variant() {
15789        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
15790        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
15791        // substrate-primitive per-arm post-projection accessor every
15792        // L7-HTTP-facing consumer routes through, sibling to the peer
15793        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
15794        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
15795        // arm round-trips its author-declared endpoint verbatim as
15796        // `Some("/charge")`; the three sibling arms
15797        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
15798        // [`WitTarget::Capability`]) each return `None` because they
15799        // carry no HTTP endpoint by definition. Same fail-before-pass-
15800        // after per-variant discipline as the sibling
15801        // `wit_target_payload_pins_per_variant` (5d6dc92) /
15802        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
15803        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
15804        // the peer pan-arm / per-half projection axes — extended onto
15805        // the per-arm HTTP-shape post-projection axis so a future
15806        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
15807        // [`WitTarget::Http`], a `Queue`-shaped peer of
15808        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
15809        // error on the sibling [`WitTarget::http_endpoint`] match arms
15810        // whose payload the L7-HTTP-shape accept-set is meant to bound.
15811        assert_eq!(
15812            WitTarget::Http {
15813                endpoint: "/charge",
15814            }
15815            .http_endpoint(),
15816            Some("/charge"),
15817        );
15818        assert_eq!(
15819            WitTarget::PubSub {
15820                subject: "events.checkout.paid",
15821            }
15822            .http_endpoint(),
15823            None,
15824        );
15825        assert_eq!(
15826            WitTarget::Store {
15827                slot: "checkout/$order",
15828            }
15829            .http_endpoint(),
15830            None,
15831        );
15832        assert_eq!(WitTarget::Capability.http_endpoint(), None);
15833    }
15834
15835    #[test]
15836    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
15837        // Per-variant coherence pin: for every arm of [`WitTarget`],
15838        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
15839        // arm (both project the same author-declared request-path
15840        // scalar), and returns `None` on every sibling arm regardless of
15841        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
15842        // Store carry their own payload the pan-arm accessor surfaces,
15843        // but that payload is not an HTTP endpoint — the per-arm
15844        // accessor must not leak it through the HTTP-shape channel).
15845        // Guards the drift surface where a future refactor that
15846        // conflated the per-arm HTTP projection with the pan-arm
15847        // [`WitTarget::payload`] projection — a well-meaning "one
15848        // accessor for the L7 branch, one for the graph" collapse that
15849        // routes both through the same 4-arm dispatch — would silently
15850        // widen the L7-HTTP-shape accept-set onto pub-sub / store
15851        // payloads at the caixa-mesh L7 emit branch, admitting a
15852        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
15853        // rule with the operator-side apply-time symptom (Cilium's
15854        // eBPF data-plane rejects every ingress edge whose L7 filter
15855        // doesn't match the wire-format HTTP request line) far from
15856        // the source refactor. Sibling to the peer
15857        // `wit_target_payload_matches_payload_pair_second_component_
15858        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
15859        // extended onto the per-arm HTTP specialization axis so both
15860        // the pan-arm and the per-arm projections carry their own
15861        // byte-shape coherence witness against the substrate's typed
15862        // arm-family accept-set.
15863        for variant in [
15864            WitTarget::Http {
15865                endpoint: "/charge",
15866            },
15867            WitTarget::PubSub {
15868                subject: "events.checkout.paid",
15869            },
15870            WitTarget::Store {
15871                slot: "checkout/$order",
15872            },
15873            WitTarget::Capability,
15874        ] {
15875            let per_arm = variant.http_endpoint();
15876            let pan_arm = variant.payload();
15877            if variant.is_http() {
15878                assert_eq!(
15879                    per_arm, pan_arm,
15880                    "WitTarget::{variant:?} http_endpoint() must equal \
15881                     payload() on the Http arm — a per-arm-vs-pan-arm \
15882                     split would silently drift the L7 emit branch's \
15883                     path-scalar source from the graph verb's payload \
15884                     scalar source",
15885                );
15886            } else {
15887                assert_eq!(
15888                    per_arm, None,
15889                    "WitTarget::{variant:?} http_endpoint() must return \
15890                     None on non-Http arms — a leak that surfaced a \
15891                     pub-sub :subject or a key/value :slot through the \
15892                     HTTP-endpoint accessor would silently widen the \
15893                     Cilium L7 HTTP `path:` rule accept-set onto \
15894                     protocol shapes Cilium's eBPF data-plane can't \
15895                     introspect",
15896                );
15897            }
15898        }
15899    }
15900
15901    #[test]
15902    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
15903        // Per-variant coherence pin: for every arm of [`WitTarget`],
15904        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
15905        // drift surface where a future extension of the
15906        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
15907        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
15908        // accessor to cover both peers) landed without a paired
15909        // extension of the [`gen_platform::IsVariant`]-derived
15910        // `is_http()` predicate's accept-set, or vice versa — a
15911        // regression that split the "which arms count as HTTP-shaped
15912        // for L7-path emission?" answer between two dispatch surfaces
15913        // the substrate ships. Sibling to the peer
15914        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
15915        // on the paired dispatch axis — extended onto the per-arm
15916        // predicate-vs-accessor coherence axis so the gen-platform
15917        // IsVariant predicate and the substrate-lifted per-arm
15918        // accessor carry one shared answer to "is this the HTTP arm?".
15919        for variant in [
15920            WitTarget::Http {
15921                endpoint: "/charge",
15922            },
15923            WitTarget::PubSub {
15924                subject: "events.checkout.paid",
15925            },
15926            WitTarget::Store {
15927                slot: "checkout/$order",
15928            },
15929            WitTarget::Capability,
15930        ] {
15931            assert_eq!(
15932                variant.http_endpoint().is_some(),
15933                variant.is_http(),
15934                "WitTarget::{variant:?} http_endpoint().is_some() must \
15935                 equal is_http() — a drift would split the L7 emit \
15936                 branch's arm-set gate from the substrate-derived \
15937                 shape-discrimination predicate on the same axis",
15938            );
15939        }
15940    }
15941
15942    #[test]
15943    fn wit_target_pubsub_subject_pins_per_variant() {
15944        // Fail-before-pass-after pin: the substrate-canonical per-arm
15945        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
15946        // is the single dispatch every future pub-sub-facing consumer
15947        // routes through, sibling to the peer [`WitContract::subject`]
15948        // (63e18a0) pre-projection scalar accessor on the raw-field
15949        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
15950        // post-projection per-arm accessor on the sibling HTTP-shape
15951        // axis. The [`WitTarget::PubSub`] arm round-trips its
15952        // author-declared subject verbatim as
15953        // `Some("events.checkout.paid")`; the three sibling arms each
15954        // return `None` because they carry no NATS-shaped subject by
15955        // definition. Same fail-before-pass-after per-variant discipline
15956        // as the sibling `wit_target_http_endpoint_pins_per_variant`
15957        // pin on the peer per-arm axis — extended onto the per-arm
15958        // pub-sub-shape post-projection axis so a future [`WitTarget`]
15959        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
15960        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
15961        // compile-time exhaustiveness error on the sibling
15962        // [`WitTarget::pubsub_subject`] match arms whose payload the
15963        // pub-sub-shape accept-set is meant to bound.
15964        assert_eq!(
15965            WitTarget::PubSub {
15966                subject: "events.checkout.paid",
15967            }
15968            .pubsub_subject(),
15969            Some("events.checkout.paid"),
15970        );
15971        assert_eq!(
15972            WitTarget::Http {
15973                endpoint: "/charge",
15974            }
15975            .pubsub_subject(),
15976            None,
15977        );
15978        assert_eq!(
15979            WitTarget::Store {
15980                slot: "checkout/$order",
15981            }
15982            .pubsub_subject(),
15983            None,
15984        );
15985        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
15986    }
15987
15988    #[test]
15989    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
15990        // Per-variant coherence pin: for every arm of [`WitTarget`],
15991        // `.pubsub_subject()` equals `.payload()` on the
15992        // [`WitTarget::PubSub`] arm (both project the same
15993        // author-declared subject scalar), and returns `None` on every
15994        // sibling arm regardless of whether [`WitTarget::payload`]
15995        // itself returns `Some` (Http / Store carry their own payload
15996        // the pan-arm accessor surfaces, but that payload is not a
15997        // pub-sub subject — the per-arm accessor must not leak it
15998        // through the pub-sub-shape channel). Sibling to the peer
15999        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
16000        // coherence pin on the per-arm HTTP-shape axis — extended onto
16001        // the per-arm pub-sub specialization axis so both per-arm
16002        // projections carry their own byte-shape coherence witness
16003        // against the substrate's typed arm-family accept-set.
16004        for variant in [
16005            WitTarget::Http {
16006                endpoint: "/charge",
16007            },
16008            WitTarget::PubSub {
16009                subject: "events.checkout.paid",
16010            },
16011            WitTarget::Store {
16012                slot: "checkout/$order",
16013            },
16014            WitTarget::Capability,
16015        ] {
16016            let per_arm = variant.pubsub_subject();
16017            let pan_arm = variant.payload();
16018            if variant.is_pubsub() {
16019                assert_eq!(
16020                    per_arm, pan_arm,
16021                    "WitTarget::{variant:?} pubsub_subject() must equal \
16022                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
16023                     split would silently drift the pub-sub-shape emit \
16024                     branch's subject-scalar source from the graph verb's \
16025                     payload scalar source",
16026                );
16027            } else {
16028                assert_eq!(
16029                    per_arm, None,
16030                    "WitTarget::{variant:?} pubsub_subject() must return \
16031                     None on non-PubSub arms — a leak that surfaced an \
16032                     HTTP :endpoint or a key/value :slot through the \
16033                     pub-sub-subject accessor would silently widen the \
16034                     downstream NATS-shape accept-set onto protocol \
16035                     shapes NATS servers can't route",
16036                );
16037            }
16038        }
16039    }
16040
16041    #[test]
16042    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
16043        // Per-variant coherence pin: for every arm of [`WitTarget`],
16044        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
16045        // drift surface where a future extension of the
16046        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
16047        // without a paired extension of the [`gen_platform::IsVariant`]-
16048        // derived `is_pubsub()` predicate's accept-set, or vice versa
16049        // — a regression that split the "which arms count as pub-sub-
16050        // shaped for subject emission?" answer between two dispatch
16051        // surfaces the substrate ships. Sibling to the peer
16052        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
16053        // pin on the per-arm HTTP-shape axis — extended onto the
16054        // per-arm pub-sub predicate-vs-accessor coherence axis so the
16055        // gen-platform IsVariant predicate and the substrate-lifted
16056        // per-arm accessor carry one shared answer to "is this the
16057        // PubSub arm?".
16058        for variant in [
16059            WitTarget::Http {
16060                endpoint: "/charge",
16061            },
16062            WitTarget::PubSub {
16063                subject: "events.checkout.paid",
16064            },
16065            WitTarget::Store {
16066                slot: "checkout/$order",
16067            },
16068            WitTarget::Capability,
16069        ] {
16070            assert_eq!(
16071                variant.pubsub_subject().is_some(),
16072                variant.is_pubsub(),
16073                "WitTarget::{variant:?} pubsub_subject().is_some() must \
16074                 equal is_pubsub() — a drift would split the pub-sub \
16075                 emit branch's arm-set gate from the substrate-derived \
16076                 shape-discrimination predicate on the same axis",
16077            );
16078        }
16079    }
16080
16081    #[test]
16082    fn wit_target_store_slot_pins_per_variant() {
16083        // Fail-before-pass-after pin: the substrate-canonical per-arm
16084        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
16085        // is the single dispatch every future store-facing consumer
16086        // routes through, sibling to the peer [`WitContract::slot`]
16087        // pre-projection scalar accessor on the raw-field axis and to
16088        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
16089        // [`WitTarget::pubsub_subject`] post-projection per-arm
16090        // accessors on the sibling per-payload-arm axes. The
16091        // [`WitTarget::Store`] arm round-trips its author-declared
16092        // slot verbatim as `Some("checkout/$order")`; the three
16093        // sibling arms each return `None` because they carry no
16094        // WASI-key/value slot by definition. Same fail-before-pass-
16095        // after per-variant discipline as the sibling
16096        // `wit_target_http_endpoint_pins_per_variant` +
16097        // `wit_target_pubsub_subject_pins_per_variant` pins on the
16098        // peer per-arm axes — extended onto the per-arm store-shape
16099        // post-projection axis so a future [`WitTarget`] variant
16100        // addition trips a compile-time exhaustiveness error on the
16101        // sibling [`WitTarget::store_slot`] match arms whose payload
16102        // the store-shape accept-set is meant to bound.
16103        assert_eq!(
16104            WitTarget::Store {
16105                slot: "checkout/$order",
16106            }
16107            .store_slot(),
16108            Some("checkout/$order"),
16109        );
16110        assert_eq!(
16111            WitTarget::Http {
16112                endpoint: "/charge",
16113            }
16114            .store_slot(),
16115            None,
16116        );
16117        assert_eq!(
16118            WitTarget::PubSub {
16119                subject: "events.checkout.paid",
16120            }
16121            .store_slot(),
16122            None,
16123        );
16124        assert_eq!(WitTarget::Capability.store_slot(), None);
16125    }
16126
16127    #[test]
16128    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
16129        // Per-variant coherence pin: for every arm of [`WitTarget`],
16130        // `.store_slot()` equals `.payload()` on the
16131        // [`WitTarget::Store`] arm (both project the same
16132        // author-declared slot scalar), and returns `None` on every
16133        // sibling arm regardless of whether [`WitTarget::payload`]
16134        // itself returns `Some`. Sibling to the peer
16135        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
16136        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
16137        // pins on the per-arm HTTP and PubSub axes — closes the
16138        // per-arm-vs-pan-arm byte-shape coherence trio across all
16139        // three payload arms.
16140        for variant in [
16141            WitTarget::Http {
16142                endpoint: "/charge",
16143            },
16144            WitTarget::PubSub {
16145                subject: "events.checkout.paid",
16146            },
16147            WitTarget::Store {
16148                slot: "checkout/$order",
16149            },
16150            WitTarget::Capability,
16151        ] {
16152            let per_arm = variant.store_slot();
16153            let pan_arm = variant.payload();
16154            if variant.is_store() {
16155                assert_eq!(
16156                    per_arm, pan_arm,
16157                    "WitTarget::{variant:?} store_slot() must equal \
16158                     payload() on the Store arm — a per-arm-vs-pan-arm \
16159                     split would silently drift the store-shape emit \
16160                     branch's slot-scalar source from the graph verb's \
16161                     payload scalar source",
16162                );
16163            } else {
16164                assert_eq!(
16165                    per_arm, None,
16166                    "WitTarget::{variant:?} store_slot() must return \
16167                     None on non-Store arms — a leak that surfaced an \
16168                     HTTP :endpoint or a NATS :subject through the \
16169                     key/value-slot accessor would silently widen the \
16170                     downstream WASI-key/value slot accept-set onto \
16171                     protocol shapes the kv backends can't route",
16172                );
16173            }
16174        }
16175    }
16176
16177    #[test]
16178    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
16179        // Per-variant coherence pin: for every arm of [`WitTarget`],
16180        // `.store_slot().is_some()` iff `.is_store()`. Guards the
16181        // drift surface where a future extension of the
16182        // [`WitTarget::store_slot`] accessor's accept-set landed
16183        // without a paired extension of the [`gen_platform::IsVariant`]-
16184        // derived `is_store()` predicate's accept-set. Sibling to the
16185        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
16186        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
16187        // pins — closes the per-arm predicate-vs-accessor coherence
16188        // trio across all three payload arms so the gen-platform
16189        // IsVariant predicate and the substrate-lifted per-arm
16190        // accessor carry one shared answer to "is this the Store arm?".
16191        for variant in [
16192            WitTarget::Http {
16193                endpoint: "/charge",
16194            },
16195            WitTarget::PubSub {
16196                subject: "events.checkout.paid",
16197            },
16198            WitTarget::Store {
16199                slot: "checkout/$order",
16200            },
16201            WitTarget::Capability,
16202        ] {
16203            assert_eq!(
16204                variant.store_slot().is_some(),
16205                variant.is_store(),
16206                "WitTarget::{variant:?} store_slot().is_some() must \
16207                 equal is_store() — a drift would split the store-shape \
16208                 emit branch's arm-set gate from the substrate-derived \
16209                 shape-discrimination predicate on the same axis",
16210            );
16211        }
16212    }
16213
16214    #[test]
16215    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
16216        // Fail-before-pass-after cross-axis pin on the trio
16217        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
16218        // payload-carrying arm of [`WitTarget`], exactly one per-arm
16219        // accessor returns `Some(payload)` and the two peers return
16220        // `None`; and on the payload-less [`WitTarget::Capability`]
16221        // arm, all three return `None`. Guards the drift surface where
16222        // a future extension of one per-arm accessor's accept-set (e.g.
16223        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
16224        // that widened `http_endpoint` to cover both peers without
16225        // narrowing the peer `pubsub_subject` / `store_slot` accept-
16226        // sets to keep the partition mutually exclusive) landed without
16227        // threading through the peer per-arm accessors — the resulting
16228        // silent overlap would land the same edge's payload on two
16229        // downstream per-shape emit branches at once, or leak a
16230        // pub-sub subject through the store-slot channel, at renderer
16231        // emit time far from the substrate primitive's arm-widening
16232        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
16233        // 3-way pin on the payload-field-name axis — extended onto the
16234        // per-arm-accessor payload-projection axis so the substrate-
16235        // owned partition invariant is load-bearing at every per-arm
16236        // consumer's read site.
16237        let payload_variants = [
16238            (
16239                WitTarget::Http {
16240                    endpoint: "/charge",
16241                },
16242                "http",
16243            ),
16244            (
16245                WitTarget::PubSub {
16246                    subject: "events.checkout.paid",
16247                },
16248                "pubsub",
16249            ),
16250            (
16251                WitTarget::Store {
16252                    slot: "checkout/$order",
16253                },
16254                "store",
16255            ),
16256        ];
16257        for (variant, own_arm_label) in payload_variants {
16258            let own_arm_hit = match own_arm_label {
16259                "http" => variant.is_http(),
16260                "pubsub" => variant.is_pubsub(),
16261                "store" => variant.is_store(),
16262                other => panic!("unknown own-arm label {other:?}"),
16263            };
16264            let per_arm_results = [
16265                ("http_endpoint", variant.http_endpoint()),
16266                ("pubsub_subject", variant.pubsub_subject()),
16267                ("store_slot", variant.store_slot()),
16268            ];
16269            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
16270            assert_eq!(
16271                some_count, 1,
16272                "WitTarget::{variant:?} must land exactly one per-arm \
16273                 post-projection accessor's Some result — the trio \
16274                 (http_endpoint, pubsub_subject, store_slot) must \
16275                 partition the payload arm-set; got {per_arm_results:?}",
16276            );
16277            assert!(
16278                own_arm_hit,
16279                "WitTarget::{variant:?} own-arm gen-platform predicate \
16280                 must return true on its own arm — a partition failure \
16281                 upstream of this pin",
16282            );
16283            assert!(
16284                variant.payload().is_some(),
16285                "WitTarget::{variant:?} pan-arm payload() must return \
16286                 Some on every payload-carrying arm the trio partitions",
16287            );
16288        }
16289        // The payload-less Capability arm must return None on every
16290        // per-arm accessor — the partition's terminal-fallback shape.
16291        let cap = WitTarget::Capability;
16292        assert_eq!(cap.http_endpoint(), None);
16293        assert_eq!(cap.pubsub_subject(), None);
16294        assert_eq!(cap.store_slot(), None);
16295        assert_eq!(
16296            cap.payload(),
16297            None,
16298            "WitTarget::Capability pan-arm payload() must return None — \
16299             the trio's payload-less-arm coherence witness",
16300        );
16301    }
16302
16303    #[test]
16304    fn wit_target_field_names_are_pairwise_distinct() {
16305        // Distinctness pin: if any two of the three payload-field-name
16306        // scalars ever collapse (e.g. an accidental `endpoint` copy-
16307        // paste over the `subject` const), the [`WitContract::target`]
16308        // gate's diagnostic would point authors at the wrong field —
16309        // an "expected `:endpoint`" error on a pub-sub edge would
16310        // silently misroute the fix. Same cross-axis-distinctness
16311        // discipline as the peer M3 `:placement :estrategia` variant-
16312        // discriminator scalar-value pins (cc8f749) applied to the
16313        // payload-field-name axis.
16314        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
16315        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
16316        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
16317    }
16318
16319    #[test]
16320    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
16321        // Fail-before-pass-after pin: the graph-verb payload column's
16322        // per-arm `{field}={payload}` byte-string is derived through the
16323        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
16324        // payload-carrying arms, not through a hand-rolled per-arm match
16325        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
16326        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16327        // inline. A future variant addition — the M4-and-later per-edge
16328        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
16329        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
16330        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
16331        // and both [`WitTarget::label`] (duplicate-`:contratos`
16332        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
16333        // payload column) pick up the new arm from the same dispatch.
16334        // Prior to this lift the graph verb open-coded the 4-arm match
16335        // in caixa-feira, so a variant addition would have to be threaded
16336        // through both projections in lockstep or the graph verb would
16337        // silently drop the new arm to `(capability-only)`.
16338        for variant in [
16339            WitTarget::Http {
16340                endpoint: "/charge",
16341            },
16342            WitTarget::PubSub {
16343                subject: "events.checkout.paid",
16344            },
16345            WitTarget::Store {
16346                slot: "checkout/$order",
16347            },
16348        ] {
16349            let (field, payload) = variant
16350                .payload_pair()
16351                .expect("payload arm must expose (field, payload)");
16352            assert_eq!(
16353                variant.graph_label(),
16354                format!("{field}={payload}"),
16355                "WitTarget::{variant:?} graph_label must route the \
16356                 `{{field}}={{payload}}` template through payload_pair — \
16357                 a regression to a hand-rolled per-arm match at the graph \
16358                 verb would silently disagree with a future variant \
16359                 addition landed only at payload_pair"
16360            );
16361        }
16362    }
16363
16364    #[test]
16365    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
16366        // Fail-before-pass-after pin on the payload-less arm: the graph
16367        // verb's `(capability-only)` byte-string routes through the
16368        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
16369        // [`WitTarget::Capability`] arm, not through an inline
16370        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
16371        // per-`:contratos` payload column. Peer of the sibling
16372        // [`wit_target_label_pins_per_variant_format`] Capability-arm
16373        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
16374        // extended here onto the third payload-less-arm consumer axis
16375        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
16376        // axis and the wrong-target diagnostic axis).
16377        assert_eq!(
16378            WitTarget::Capability.graph_label(),
16379            WitTarget::CAPABILITY_GRAPH_LABEL,
16380        );
16381        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
16382    }
16383
16384    #[test]
16385    fn wit_target_capability_graph_label_distinct_from_capability_label() {
16386        // Cross-consumer-axis distinctness pin: the graph-verb
16387        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
16388        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
16389        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
16390        // payload)`) surface the payload-less arm on two distinct
16391        // consumer axes; a collapse (an accidental rebrand that lands
16392        // one spelling on both consts, a copy-paste that unifies them
16393        // "for consistency") would silently merge the two byte-strings
16394        // and lose the vocabulary distinction the graph verb's
16395        // compact-column form and the diagnostic's descriptive-clause
16396        // form each carry on purpose. Peer of the sibling 4-way
16397        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
16398        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
16399        // extended here onto the cross-consumer-axis distinctness of the
16400        // two payload-less-arm consts.
16401        assert_ne!(
16402            WitTarget::CAPABILITY_GRAPH_LABEL,
16403            WitTarget::CAPABILITY_LABEL,
16404            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
16405             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
16406             diagnostic) must remain distinct — a collapse would silently \
16407             merge two consumer axes onto one spelling"
16408        );
16409    }
16410
16411    #[test]
16412    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
16413        // 4-way distinctness pin extending the sibling
16414        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
16415        // (which covers only the HTTP / PubSub / Store payload arms)
16416        // onto the fourth scalar the shared
16417        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
16418        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
16419        // (`"none"`), the payload-less Capability-arm rejection scalar.
16420        //
16421        // All four [`WitTarget::HTTP_FIELD_NAME`] /
16422        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16423        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
16424        // dispatch surface [`WitContract::target`] writes onto the
16425        // `ContratoWrongTarget::expected` field — the same `&'static
16426        // str` axis authors read as "this WIT world's shape admits
16427        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
16428        // downstream consumers rely on: an `expected: "endpoint"`
16429        // diagnostic on a Capability-shaped edge tells the author to
16430        // add a `:endpoint "…"` slot to a WIT world that admits none,
16431        // silently misrouting the fix. Until this pin landed the three
16432        // payload-arm consts were distinctness-guarded by the sibling
16433        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
16434        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
16435        // author-facing vocabulary shift from `"none"` to `"endpoint"`
16436        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
16437        // into per-shape peers) would have silently landed one
16438        // Capability-arm rejection on a payload-arm's `expected:` byte-
16439        // string and desynchronized the diagnostic from the author's
16440        // typed shape.
16441        //
16442        // Same 4-way pairwise-distinctness pin discipline as the peer
16443        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
16444        // (cc8f749) applies on the sibling M3 closed-set typed-enum
16445        // scalar-value dispatch axis; extends the pin trajectory the
16446        // sibling `wit_target_field_names_are_pairwise_distinct`
16447        // 3-way pin opened to cover the last unguarded corner on the
16448        // `ContratoWrongTarget::expected` scalar-value axis.
16449        //
16450        // Fail-before-pass-after locally verified by mutating
16451        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
16452        // — this pin fires as expected; restoring passes.
16453        let all = [
16454            WitTarget::HTTP_FIELD_NAME,
16455            WitTarget::PUBSUB_FIELD_NAME,
16456            WitTarget::STORE_FIELD_NAME,
16457            WitTarget::CAPABILITY_EXPECTED,
16458        ];
16459        for (i, a) in all.iter().enumerate() {
16460            for (j, b) in all.iter().enumerate() {
16461                if i != j {
16462                    assert_ne!(
16463                        a, b,
16464                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
16465                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
16466                         pairwise distinct — got duplicate {a:?} at indices \
16467                         {i} and {j}; all four scalars thread through the \
16468                         shared `AplicacaoError::ContratoWrongTarget::expected` \
16469                         &'static str axis, so a collapse silently misdirects \
16470                         the diagnostic on which typed shape the WIT world admits",
16471                    );
16472                }
16473            }
16474        }
16475    }
16476
16477    #[test]
16478    fn wit_target_is_variant_predicates_partition_the_arm_set() {
16479        // Fail-before-pass-after pin on the
16480        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
16481        // each of the four variants exactly one of the generated
16482        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
16483        // predicates returns `true` and the other three return
16484        // `false`. Prior to this derive the only production
16485        // arm-discriminator on [`WitTarget`] — the sync-cycle
16486        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
16487        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
16488        // the variant that expressed no compile-time link back to
16489        // the closed-set typed dispatch a future fifth
16490        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
16491        // split of [`WitTarget::PubSub`] into shape-specific peers,
16492        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
16493        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
16494        // to thread through in lockstep or the DFS exclusion would
16495        // silently disagree with the peer diagnostic templates on
16496        // which arms carry sync-versus-async semantics. Peer of the
16497        // sibling [`crate::CaixaKind`] (f5bba80),
16498        // [`PlacementStrategy`] (766ec63),
16499        // [`crate::supervisor::RestartStrategy`],
16500        // [`crate::supervisor::RestartPolicy`], and
16501        // [`crate::upgrade::UpgradeInstruction`] (915a934)
16502        // `IsVariant` derives on the sibling closed-set typed-enum
16503        // discriminator axes — extends the same one-typed-dispatch-
16504        // per-variant discipline onto the last unlifted closed-set
16505        // typed-enum discriminator on the caixa surface (the M3
16506        // mesh-slot per-`:contratos` target-arm axis), closing the
16507        // arm-discriminator convergence trajectory across every
16508        // closed-set typed enum in caixa-core.
16509        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
16510            (
16511                WitTarget::Http { endpoint: "/x" },
16512                [true, false, false, false],
16513            ),
16514            (
16515                WitTarget::PubSub {
16516                    subject: "events.x",
16517                },
16518                [false, true, false, false],
16519            ),
16520            (
16521                WitTarget::Store { slot: "kv/x" },
16522                [false, false, true, false],
16523            ),
16524            (WitTarget::Capability, [false, false, false, true]),
16525        ];
16526        for (variant, expected) in rows {
16527            let observed = [
16528                variant.is_http(),
16529                variant.is_pubsub(),
16530                variant.is_store(),
16531                variant.is_capability(),
16532            ];
16533            assert_eq!(
16534                observed, expected,
16535                "WitTarget::{variant:?} is_* predicates must partition \
16536                 the arm set (http, pubsub, store, capability); got {observed:?}"
16537            );
16538        }
16539    }
16540
16541    #[test]
16542    fn wit_target_is_variant_predicates_are_const_fn() {
16543        // The [`gen_platform::IsVariant`] derive emits `const fn`
16544        // predicates on the peer [`crate::CaixaKind`] +
16545        // [`crate::upgrade::UpgradeInstruction`] +
16546        // [`crate::supervisor::RestartStrategy`] +
16547        // [`crate::supervisor::RestartPolicy`] +
16548        // [`PlacementStrategy`] closed-set typed enums — pin the
16549        // same posture on [`WitTarget`] so a future accidental
16550        // downgrade to non-`const` (an added runtime helper reachable
16551        // only from a non-`const` context, a manual hand-rolled
16552        // `impl` that shadows the derive-generated method) trips at
16553        // caixa-core build time rather than surfacing as a downstream
16554        // `const`-context regression far from the derive declaration.
16555        //
16556        // Unlike the peer unit-variant enums (`CaixaKind` /
16557        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
16558        // whose `const` constructors need no arguments, the three
16559        // payload-carrying [`WitTarget`] arms are const-constructed
16560        // through `&'static str` payloads — the same `'static`
16561        // lifetime the closed-set typed enum's four-arm partition
16562        // pin above already threads through.
16563        //
16564        // The pin lives inside a `const { assert!(..) }` block so the
16565        // compiler enforces both halves (arm predicate is `const`-
16566        // callable AND returns `true` for the matching arm) at
16567        // caixa-core compile time — peer to the sibling
16568        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
16569        // typed enum arm-predicate const-callability axis.
16570        const {
16571            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
16572            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
16573            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
16574            assert!(WitTarget::Capability.is_capability());
16575        }
16576    }
16577
16578    #[test]
16579    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
16580        // Consumer-side pin on the sole production converge site:
16581        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
16582        // edges from the synchronous-subgraph DFS via the lifted
16583        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
16584        // predicate (rebound from the prior raw
16585        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
16586        // variant). Byte-equivalent today (`is_pubsub` is the
16587        // derive-generated `matches!(self, Self::PubSub { .. })` by
16588        // construction, the `#[is_variant(name = "pubsub")]` override
16589        // aliasing the auto-derived `is_pub_sub` back to the sibling
16590        // [`WitContract::is_pubsub`] name); pin the behavior so a
16591        // future accidental drift (a rebind onto a peer arm
16592        // predicate, a manual hand-rolled `impl` that shadows the
16593        // derive-generated method with different semantics, a peer
16594        // arm rename that shifts which variant carries sync-versus-
16595        // async semantics) trips at caixa-core test time rather than
16596        // at some downstream operator's runtime dispatch far from the
16597        // rebind commit.
16598        //
16599        // The fixture constructs a two-Servico Aplicacao with one
16600        // pub-sub edge that would close a sync-cycle if the DFS did
16601        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
16602        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
16603        // edge, which is not a cycle. A regression in the converge
16604        // (a rebind that reads the pub-sub arm as sync) would report
16605        // `AplicacaoError::ContratoCycle`.
16606        let s = AplicacaoSpec {
16607            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
16608            contratos: vec![
16609                // Pub-sub edge: DFS must skip via is_pubsub().
16610                WitContract {
16611                    de: "a".into(),
16612                    para: "b".into(),
16613                    wit: "nats:pub-sub".into(),
16614                    endpoint: None,
16615                    subject: Some("events.x".into()),
16616                    slot: None,
16617                },
16618                // HTTP edge: DFS must include.
16619                WitContract {
16620                    de: "b".into(),
16621                    para: "a".into(),
16622                    wit: "wasi:http/proxy".into(),
16623                    endpoint: Some("/x".into()),
16624                    subject: None,
16625                    slot: None,
16626                },
16627            ],
16628            politicas: MeshPolicy::default(),
16629            placement: Placement {
16630                estrategia: PlacementStrategy::Replicated,
16631                clusters: vec!["rio".into()],
16632                affinity: None,
16633                shard_key: None,
16634            },
16635            entrada: None,
16636        };
16637        s.validate()
16638            .expect("pub-sub edge must be excluded from sync-cycle DFS");
16639    }
16640
16641    #[test]
16642    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
16643        // Consumer-side pin: the same three peer consts thread through
16644        // both the [`WitTarget::label`] template (leading-`:` keyword
16645        // prefix in the duplicate-`:contratos` diagnostic) and the
16646        // [`WitContract::target`] gate's [`AplicacaoError::
16647        // ContratoMissingTarget`] `expected:` scalar (the field the
16648        // author needs to add). Pin both routes at once so a future
16649        // refactor can't accidentally split them onto separate string
16650        // literals — the "one place, everywhere reaches for it"
16651        // invariant the peer const set carries.
16652        let http_label = WitTarget::Http { endpoint: "/x" }.label();
16653        assert!(
16654            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
16655            "label must lead with :{} keyword (got {http_label:?})",
16656            WitTarget::HTTP_FIELD_NAME,
16657        );
16658
16659        let mut s = three_member_spec();
16660        s.contratos.push(WitContract {
16661            de: "cart".into(),
16662            para: "catalog".into(),
16663            wit: "kafka:topic".into(),
16664            endpoint: None,
16665            subject: None,
16666            slot: None,
16667        });
16668        match s.validate().unwrap_err() {
16669            AplicacaoError::ContratoMissingTarget { expected, .. } => {
16670                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
16671            }
16672            other => panic!("expected ContratoMissingTarget, got {other:?}"),
16673        }
16674    }
16675
16676    #[test]
16677    fn duplicate_pubsub_diagnostic_names_offending_subject() {
16678        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
16679        // on the pub-sub target axis: the duplicate-edge diagnostic
16680        // must name the `:subject` payload verbatim (not just the
16681        // `(de, para, wit)` triple). Prior to lifting the label onto
16682        // [`WitTarget::label`] the diagnostic derived the label from
16683        // raw [`WitContract`] `Option<String>` probes — a future
16684        // `WitTarget` variant addition (M4 per-edge WIT registry)
16685        // would silently fall through to the `Capability` "no
16686        // payload" default without a compiler warning. Pinning the
16687        // pub-sub arm's format closes the second of three
16688        // payload-carrying `WitTarget` arms this diagnostic threads
16689        // through.
16690        let mut s = three_member_spec();
16691        let pubsub = WitContract {
16692            de: "payment".into(),
16693            para: "cart".into(),
16694            wit: "nats:pub-sub".into(),
16695            endpoint: None,
16696            subject: Some("events.checkout.paid".into()),
16697            slot: None,
16698        };
16699        s.contratos.push(pubsub.clone());
16700        s.contratos.push(pubsub);
16701        let err = s.validate().unwrap_err();
16702        let msg = format!("{err}");
16703        assert!(
16704            msg.contains(":subject \"events.checkout.paid\""),
16705            "duplicate-pubsub diagnostic must name the offending \
16706             :subject payload (got: {msg:?})"
16707        );
16708    }
16709
16710    #[test]
16711    fn duplicate_store_diagnostic_names_offending_slot() {
16712        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
16713        // key-value target axis: the diagnostic must name the `:slot`
16714        // payload verbatim. Third of three payload-carrying
16715        // `WitTarget` arms this diagnostic threads through, closing
16716        // the per-arm label pin trilogy (`Http` — 6841,
16717        // `PubSub` + `Store` — this test + peer above).
16718        let mut s = three_member_spec();
16719        let store = WitContract {
16720            de: "cart".into(),
16721            para: "payment".into(),
16722            wit: "wasi:keyvalue/store".into(),
16723            endpoint: None,
16724            subject: None,
16725            slot: Some("checkout/$orderId".into()),
16726        };
16727        s.contratos
16728            .retain(|c| !(c.de == "cart" && c.para == "payment"));
16729        s.contratos.push(store.clone());
16730        s.contratos.push(store);
16731        let err = s.validate().unwrap_err();
16732        let msg = format!("{err}");
16733        assert!(
16734            msg.contains(":slot \"checkout/$orderId\""),
16735            "duplicate-store diagnostic must name the offending :slot \
16736             payload (got: {msg:?})"
16737        );
16738    }
16739
16740    #[test]
16741    fn rejects_entrada_path_without_leading_slash() {
16742        let mut s = three_member_spec();
16743        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
16744        let err = s.validate().unwrap_err();
16745        assert!(
16746            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
16747            "got {err:?}"
16748        );
16749    }
16750
16751    #[test]
16752    fn rejects_empty_entrada_path() {
16753        let mut s = three_member_spec();
16754        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
16755        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
16756    }
16757
16758    #[test]
16759    fn rejects_duplicate_entrada_paths() {
16760        let mut s = three_member_spec();
16761        s.entrada.as_mut().unwrap().paths = vec![
16762            "/api/cart".into(),
16763            "/api/products".into(),
16764            "/api/cart".into(),
16765        ];
16766        let err = s.validate().unwrap_err();
16767        assert!(
16768            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
16769            "got {err:?}"
16770        );
16771    }
16772
16773    #[test]
16774    fn rejects_zero_entrada_port() {
16775        let mut s = three_member_spec();
16776        s.entrada.as_mut().unwrap().port = 0;
16777        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
16778    }
16779
16780    // ── :entrada :paths value-shape gate ─────────────────────────────
16781    //
16782    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
16783    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
16784    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
16785    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
16786    // time now becomes a caixa-build-time `EntradaPathInvalid` with
16787    // the offending `:paths` entry named verbatim.
16788
16789    #[test]
16790    fn rejects_entrada_path_with_query() {
16791        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
16792        // silently passed validate and the Gateway API webhook
16793        // rejected it at apply time with no source citation.
16794        let mut s = three_member_spec();
16795        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
16796        let err = s.validate().unwrap_err();
16797        assert!(
16798            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16799                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
16800            "got {err:?}"
16801        );
16802    }
16803
16804    #[test]
16805    fn rejects_entrada_path_with_fragment() {
16806        let mut s = three_member_spec();
16807        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
16808        let err = s.validate().unwrap_err();
16809        assert!(
16810            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16811                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
16812            "got {err:?}"
16813        );
16814    }
16815
16816    #[test]
16817    fn rejects_entrada_path_with_space() {
16818        let mut s = three_member_spec();
16819        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
16820        let err = s.validate().unwrap_err();
16821        assert!(
16822            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16823                if path == "/api/my cart" && reason.contains("whitespace")),
16824            "got {err:?}"
16825        );
16826    }
16827
16828    #[test]
16829    fn rejects_entrada_path_with_tab() {
16830        let mut s = three_member_spec();
16831        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
16832        let err = s.validate().unwrap_err();
16833        assert!(
16834            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16835                if path == "/api/\tcart" && reason.contains("whitespace")),
16836            "got {err:?}"
16837        );
16838    }
16839
16840    #[test]
16841    fn rejects_entrada_path_with_control_char() {
16842        // 0x01 (SOH) — a non-whitespace control char surfaces the
16843        // distinct "control character" reason arm, separate from
16844        // the whitespace arm. Pinned so a future refactor that
16845        // collapses the two arms can't accidentally drop the more
16846        // self-locating diagnostic.
16847        let mut s = three_member_spec();
16848        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
16849        let err = s.validate().unwrap_err();
16850        assert!(
16851            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16852                if path == "/api/\x01cart" && reason.contains("control character")),
16853            "got {err:?}"
16854        );
16855    }
16856
16857    #[test]
16858    fn rejects_entrada_path_with_non_ascii() {
16859        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
16860        // unreserved-set rule rejects. The Gateway API webhook
16861        // rejects literal non-ASCII bytes; percent-encoding is the
16862        // only way to author non-ASCII in a path.
16863        let mut s = three_member_spec();
16864        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
16865        let err = s.validate().unwrap_err();
16866        assert!(
16867            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16868                if path == "/api/café" && reason.contains("non-ASCII")),
16869            "got {err:?}"
16870        );
16871    }
16872
16873    #[test]
16874    fn rejects_entrada_path_with_consecutive_slashes() {
16875        let mut s = three_member_spec();
16876        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
16877        let err = s.validate().unwrap_err();
16878        assert!(
16879            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16880                if path == "/api//cart" && reason.contains("consecutive `/`")),
16881            "got {err:?}"
16882        );
16883    }
16884
16885    #[test]
16886    fn rejects_entrada_path_with_dot_segment() {
16887        let mut s = three_member_spec();
16888        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
16889        let err = s.validate().unwrap_err();
16890        assert!(
16891            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16892                if path == "/api/./cart" && reason.contains("`.` segment")),
16893            "got {err:?}"
16894        );
16895    }
16896
16897    #[test]
16898    fn rejects_entrada_path_with_trailing_dot_segment() {
16899        // The bare `/.` and the trailing `/foo/.` are both rejected
16900        // by the Gateway API webhook; pinned separately so a future
16901        // narrowing that catches only the inner form surfaces here.
16902        let mut s = three_member_spec();
16903        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
16904        let err = s.validate().unwrap_err();
16905        assert!(
16906            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16907                if path == "/api/." && reason.contains("`.` segment")),
16908            "got {err:?}"
16909        );
16910    }
16911
16912    #[test]
16913    fn rejects_entrada_path_with_parent_segment() {
16914        let mut s = three_member_spec();
16915        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
16916        let err = s.validate().unwrap_err();
16917        assert!(
16918            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16919                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
16920            "got {err:?}"
16921        );
16922    }
16923
16924    #[test]
16925    fn rejects_entrada_path_with_trailing_parent_segment() {
16926        // Trailing `/..` — symmetric arm of the parent-segment rule,
16927        // pinned separately so a future relaxation that only checks
16928        // the inner form (`/../`) surfaces here.
16929        let mut s = three_member_spec();
16930        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
16931        let err = s.validate().unwrap_err();
16932        assert!(
16933            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16934                if path == "/api/.." && reason.contains("`..` parent-segment")),
16935            "got {err:?}"
16936        );
16937    }
16938
16939    #[test]
16940    fn rejects_entrada_path_too_long() {
16941        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
16942        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
16943        // ASCII-alphanumeric body so only the length rule fires.
16944        let mut s = three_member_spec();
16945        let big = format!("/api/{}", "a".repeat(1020));
16946        assert_eq!(big.len(), 1025);
16947        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
16948        let err = s.validate().unwrap_err();
16949        assert!(
16950            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
16951                if path == &big && reason.contains("max length of 1024")),
16952            "got {err:?}"
16953        );
16954    }
16955
16956    #[test]
16957    fn entrada_path_max_length_validates() {
16958        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
16959        // maxLength cap. Boundary pin: drift in the cap surfaces here
16960        // and at `rejects_entrada_path_too_long` simultaneously.
16961        let mut s = three_member_spec();
16962        let big = format!("/api/{}", "a".repeat(1019));
16963        assert_eq!(big.len(), 1024);
16964        s.entrada.as_mut().unwrap().paths = vec![big];
16965        s.validate().unwrap();
16966    }
16967
16968    #[test]
16969    fn entrada_accepts_canonical_paths() {
16970        // Positive-control sweep — every form the Gateway API
16971        // apiserver accepts must round-trip through validate. Covers
16972        // the root catch-all, plain paths, dot-prefixed segments
16973        // (hidden-file-style, distinct from `.` and `..` segments
16974        // which are rejected), digit-bearing segments, the canonical
16975        // route-template `:param` form (`:` is RFC 3986 reserved-set
16976        // valid in paths), trailing-slash form, percent-encoded
16977        // segments, and an interior `..` *substring* (`/foo..bar` is
16978        // not the `..` segment and is allowed).
16979        for path in [
16980            "/",
16981            "/api/cart",
16982            "/healthz",
16983            "/api/.config",
16984            "/v1/products",
16985            "/products/:id",
16986            "/api/cart/",
16987            "/api/caf%C3%A9",
16988            "/foo..bar",
16989            "/...",
16990        ] {
16991            let mut s = three_member_spec();
16992            s.entrada.as_mut().unwrap().paths = vec![path.into()];
16993            s.validate()
16994                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
16995        }
16996    }
16997
16998    #[test]
16999    fn entrada_path_empty_takes_precedence_over_invalid() {
17000        // Ordering pin: `EntradaPathEmpty` is the more self-locating
17001        // diagnostic on `""` and must lead — `validate_entrada_path`
17002        // is only reached after the empty-check fires at the call
17003        // site. (The predicate itself defends against direct
17004        // invocation by returning the same error on `""`.)
17005        let mut s = three_member_spec();
17006        s.entrada.as_mut().unwrap().paths = vec![String::new()];
17007        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
17008    }
17009
17010    #[test]
17011    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
17012        // Ordering pin: a path without a leading `/` surfaces the
17013        // narrower `EntradaPathNotAbsolute` diagnostic first; the
17014        // value-shape gate is only consulted on paths that already
17015        // satisfy the absolute-prefix invariant.
17016        let mut s = three_member_spec();
17017        // `bad path` would fire the whitespace rule under the
17018        // value-shape gate, but missing-leading-`/` is the more
17019        // self-locating diagnostic.
17020        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
17021        let err = s.validate().unwrap_err();
17022        assert!(
17023            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
17024            "got {err:?}"
17025        );
17026    }
17027
17028    #[test]
17029    fn entrada_path_invalid_fires_before_duplicate_check() {
17030        // Ordering pin: a malformed path on the *first* entry of a
17031        // would-be duplicate pair fires the value-shape gate before
17032        // the duplicate gate, mirroring the
17033        // `placement_cluster_invalid_fires_before_duplicate_check`
17034        // (6cbb900) pattern on the peer axis.
17035        let mut s = three_member_spec();
17036        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
17037        let err = s.validate().unwrap_err();
17038        assert!(
17039            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
17040            "got {err:?}"
17041        );
17042    }
17043
17044    #[test]
17045    fn entrada_path_diagnostic_carries_offending_path() {
17046        // Diagnostic-shape pin — the offending path + a non-empty
17047        // reason flow through verbatim so the author can grep their
17048        // caixa.lisp for `:paths` and fix it in one edit. Same shape
17049        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
17050        let mut s = three_member_spec();
17051        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
17052        let err = s.validate().unwrap_err();
17053        match err {
17054            AplicacaoError::EntradaPathInvalid { path, reason } => {
17055                assert_eq!(path, "/api?q=1");
17056                assert!(!reason.is_empty(), "reason field must be non-empty");
17057            }
17058            other => panic!("expected EntradaPathInvalid, got {other:?}"),
17059        }
17060    }
17061
17062    #[test]
17063    fn rejects_entrada_path_with_curly_brace_template_form() {
17064        // Per-axis pin on the shared `is_gateway_api_http_path`
17065        // reserved-byte arm: the canonical "I wrote an OpenAPI
17066        // path-template `{id}` instead of the Gateway API `:id` form"
17067        // footgun the K8s apiserver would otherwise catch at admission
17068        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
17069        // landing site, far from the caixa.lisp. Surfaces as
17070        // `EntradaPathInvalid` carrying the offending path verbatim
17071        // plus the canonical `%7B`/`%7D` percent-encoding remediation
17072        // — the substrate-side `gateway_api_http_path_rejects_every_
17073        // reserved_printable_ascii_byte` predicate-level sweep pins the
17074        // full eleven-byte set; this per-axis pin confirms the
17075        // diagnostic flows through to the `EntradaPathInvalid` variant.
17076        let mut s = three_member_spec();
17077        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
17078        let err = s.validate().unwrap_err();
17079        assert!(
17080            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17081                if path == "/api/cart/{id}"
17082                    && reason.contains("reserved character")
17083                    && reason.contains("'{'")
17084                    && reason.contains("%7B")),
17085            "got {err:?}"
17086        );
17087    }
17088
17089    #[test]
17090    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
17091        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
17092        // template_form` on the sibling `:contratos :endpoint` axis.
17093        // Same shared `is_gateway_api_http_path` reserved-byte arm
17094        // fires through `ContratoEndpointInvalid`, with the offending
17095        // endpoint + `:de` + `:para` + reason flowing through verbatim.
17096        // Pins that the lifted predicate's tightening lands on both
17097        // caller axes simultaneously — one source of truth for the
17098        // Gateway API HTTPPathMatch.value accepted set.
17099        let err = contrato_endpoint_err("/api/cart/{id}");
17100        assert!(
17101            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
17102                if endpoint == "/api/cart/{id}"
17103                    && reason.contains("reserved character")
17104                    && reason.contains("'{'")
17105                    && reason.contains("%7B")),
17106            "got {err:?}"
17107        );
17108    }
17109
17110    // ── :entrada :host value-shape gate ──────────────────────────────
17111    //
17112    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
17113    // the sibling `:host` axis. Every authoring footgun the K8s
17114    // Gateway API v1 apiserver would catch at admission time becomes
17115    // a caixa-build-time `EntradaHostInvalid` with the offending
17116    // `:host` named verbatim. Same diagnostic shape as
17117    // `MembroVersaoInvalid` (9888b13).
17118
17119    #[test]
17120    fn rejects_entrada_host_with_scheme() {
17121        // Fail-before-pass-after pin — pre-gate codebases silently
17122        // accepted `https://…` and the apiserver rejected it at apply
17123        // time with no source citation.
17124        let mut s = three_member_spec();
17125        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
17126        let err = s.validate().unwrap_err();
17127        assert!(
17128            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17129                if host == "https://checkout.quero.cloud"),
17130            "got {err:?}"
17131        );
17132    }
17133
17134    #[test]
17135    fn rejects_entrada_host_with_port() {
17136        // The `:8080` port suffix is the canonical "I forgot the port
17137        // belongs in `:entrada :port`" footgun. The top-level `:` arm
17138        // (introduced after the per-label loop-only impl silently
17139        // surfaced a deep "label \"cloud:8080\" contains invalid
17140        // character ':'" leak) names the canonical fix verbatim — the
17141        // `:entrada :port` slot.
17142        let mut s = three_member_spec();
17143        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
17144        let err = s.validate().unwrap_err();
17145        assert!(
17146            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17147                if host == "checkout.quero.cloud:8080"
17148                && reason.contains(":entrada :port")),
17149            "got {err:?}"
17150        );
17151    }
17152
17153    #[test]
17154    fn rejects_entrada_host_with_trailing_colon() {
17155        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
17156        // edit) — the per-label loop would land it as a deep
17157        // "label \"com:\" must start and end with an alphanumeric"
17158        // / "contains invalid character ':'" leak. The top-level
17159        // `:` arm pre-empts with the canonical `:port` slot
17160        // diagnostic.
17161        let mut s = three_member_spec();
17162        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
17163        let err = s.validate().unwrap_err();
17164        assert!(
17165            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17166                if host == "checkout.quero.cloud:"
17167                && reason.contains(":entrada :port")),
17168            "got {err:?}"
17169        );
17170    }
17171
17172    #[test]
17173    fn rejects_entrada_host_unbracketed_ipv6_literal() {
17174        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
17175        // literals across the board (peer with `rejects_entrada_host_
17176        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
17177        // Before this top-level `:` arm landed the per-label loop
17178        // surfaced a single-label byte-class diagnostic that named the
17179        // `:` byte but not the IP-literal prohibition. The top-level
17180        // `:` arm names both the `:port` slot and the IP-literal
17181        // prohibition verbatim, so an author whose `:host "2001:..."`
17182        // value lands here gets a self-locating fix either way.
17183        let mut s = three_member_spec();
17184        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
17185        let err = s.validate().unwrap_err();
17186        assert!(
17187            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17188                if host == "2001:db8::1"
17189                && reason.contains("IPv6")),
17190            "got {err:?}"
17191        );
17192    }
17193
17194    #[test]
17195    fn rejects_entrada_host_wildcard_with_port() {
17196        // Wildcard host with port suffix — the `*.` strip and the
17197        // per-label loop on `["foo", "quero", "cloud:8080"]` would
17198        // surface the deep byte-class leak. The top-level `:` arm sits
17199        // upstream of the `*.` strip, so it names the canonical `:port`
17200        // fix verbatim regardless of whether the host is wildcard-led.
17201        let mut s = three_member_spec();
17202        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
17203        let err = s.validate().unwrap_err();
17204        assert!(
17205            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17206                if host == "*.quero.cloud:8080"
17207                && reason.contains(":entrada :port")),
17208            "got {err:?}"
17209        );
17210    }
17211
17212    #[test]
17213    fn rejects_entrada_host_with_path() {
17214        let mut s = three_member_spec();
17215        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
17216        let err = s.validate().unwrap_err();
17217        assert!(
17218            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17219                if host == "checkout.quero.cloud/api"),
17220            "got {err:?}"
17221        );
17222    }
17223
17224    #[test]
17225    fn rejects_entrada_host_with_uppercase() {
17226        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
17227        // rejected, not silently lower-cased.
17228        let mut s = three_member_spec();
17229        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
17230        let err = s.validate().unwrap_err();
17231        assert!(
17232            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17233                if reason.contains("uppercase")),
17234            "got {err:?}"
17235        );
17236    }
17237
17238    #[test]
17239    fn rejects_entrada_host_with_underscore() {
17240        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
17241        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
17242        let mut s = three_member_spec();
17243        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
17244        let err = s.validate().unwrap_err();
17245        assert!(
17246            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17247                if reason.contains('_')),
17248            "got {err:?}"
17249        );
17250    }
17251
17252    #[test]
17253    fn rejects_entrada_host_ipv4_literal() {
17254        // Gateway API v1 explicitly forbids IP literals as Hostnames.
17255        let mut s = three_member_spec();
17256        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
17257        let err = s.validate().unwrap_err();
17258        assert!(
17259            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17260                if reason.contains("IPv4")),
17261            "got {err:?}"
17262        );
17263    }
17264
17265    #[test]
17266    fn rejects_entrada_host_with_trailing_dot() {
17267        // The Gateway API regex anchors at end-of-string with no
17268        // trailing `.` allowance — the FQDN root-dot form is rejected.
17269        let mut s = three_member_spec();
17270        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
17271        let err = s.validate().unwrap_err();
17272        assert!(
17273            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17274                if host == "checkout.quero.cloud."),
17275            "got {err:?}"
17276        );
17277    }
17278
17279    #[test]
17280    fn rejects_entrada_host_with_leading_dot() {
17281        let mut s = three_member_spec();
17282        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
17283        let err = s.validate().unwrap_err();
17284        assert!(
17285            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17286                if reason.contains("empty label")),
17287            "got {err:?}"
17288        );
17289    }
17290
17291    #[test]
17292    fn rejects_entrada_host_with_consecutive_dots() {
17293        let mut s = three_member_spec();
17294        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
17295        let err = s.validate().unwrap_err();
17296        assert!(
17297            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17298                if reason.contains("empty label")),
17299            "got {err:?}"
17300        );
17301    }
17302
17303    #[test]
17304    fn rejects_entrada_host_with_leading_hyphen_label() {
17305        let mut s = three_member_spec();
17306        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
17307        let err = s.validate().unwrap_err();
17308        assert!(
17309            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17310                if reason.contains("alphanumeric")),
17311            "got {err:?}"
17312        );
17313    }
17314
17315    #[test]
17316    fn rejects_entrada_host_with_trailing_hyphen_label() {
17317        let mut s = three_member_spec();
17318        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
17319        let err = s.validate().unwrap_err();
17320        assert!(
17321            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17322                if reason.contains("alphanumeric")),
17323            "got {err:?}"
17324        );
17325    }
17326
17327    #[test]
17328    fn rejects_entrada_host_with_inner_wildcard() {
17329        // Gateway API allows `*` only as the first label (`*.foo`);
17330        // any inner or trailing `*` is rejected.
17331        let mut s = three_member_spec();
17332        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
17333        let err = s.validate().unwrap_err();
17334        assert!(
17335            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17336                if reason.contains("wildcard")),
17337            "got {err:?}"
17338        );
17339    }
17340
17341    #[test]
17342    fn rejects_entrada_host_bare_wildcard() {
17343        // `*.` with no domain is meaningless; Gateway API rejects it.
17344        let mut s = three_member_spec();
17345        s.entrada.as_mut().unwrap().host = "*.".into();
17346        let err = s.validate().unwrap_err();
17347        assert!(
17348            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17349                if reason.contains("wildcard")),
17350            "got {err:?}"
17351        );
17352    }
17353
17354    #[test]
17355    fn rejects_entrada_host_with_whitespace() {
17356        let mut s = three_member_spec();
17357        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
17358        let err = s.validate().unwrap_err();
17359        assert!(
17360            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17361                if reason.contains("whitespace")),
17362            "got {err:?}"
17363        );
17364    }
17365
17366    #[test]
17367    fn rejects_entrada_host_space_names_offending_byte() {
17368        // Embedded space in the `:entrada :host` axis surfaces the
17369        // byte-naming diagnostic through the lifted
17370        // `find_ascii_whitespace_byte` predicate. Peer with the
17371        // sibling `parse_rejects_leading_whitespace` pins on
17372        // `supervisor::duration_codec` (a7ae622) — same "the
17373        // diagnostic carries the offending byte's `0x{b:02x}` shape"
17374        // discipline extended from the shared duration codec to the
17375        // Gateway API v1 Hostname axis.
17376        let mut s = three_member_spec();
17377        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
17378        let err = s.validate().unwrap_err();
17379        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17380            panic!("expected EntradaHostInvalid, got {err:?}");
17381        };
17382        assert!(
17383            reason.contains("ASCII whitespace byte"),
17384            "expected byte-naming diagnostic, got {reason:?}"
17385        );
17386        assert!(
17387            reason.contains("0x20"),
17388            "expected offending space byte 0x20, got {reason:?}"
17389        );
17390    }
17391
17392    #[test]
17393    fn rejects_entrada_host_tab_names_offending_byte() {
17394        // Embedded tab byte in the `:entrada :host` axis — the
17395        // canonical paste-from-YAML-block-scalar / paste-from-
17396        // indented-doc footgun. Pins that the lifted predicate covers
17397        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
17398        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
17399        // not just the leading-space case the pre-lift `.bytes().any`
17400        // arm's opaque "must not contain whitespace" reason already
17401        // covered. Peer with `parse_rejects_tab_byte` on
17402        // `supervisor::duration_codec` (a7ae622).
17403        let mut s = three_member_spec();
17404        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
17405        let err = s.validate().unwrap_err();
17406        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17407            panic!("expected EntradaHostInvalid, got {err:?}");
17408        };
17409        assert!(
17410            reason.contains("ASCII whitespace byte"),
17411            "expected byte-naming diagnostic, got {reason:?}"
17412        );
17413        assert!(
17414            reason.contains("0x09"),
17415            "expected offending tab byte 0x09, got {reason:?}"
17416        );
17417    }
17418
17419    #[test]
17420    fn rejects_entrada_host_lf_names_offending_byte() {
17421        // Embedded LF byte in the `:entrada :host` axis — the
17422        // canonical paste-from-shell-heredoc / paste-from-multiline-
17423        // doc footgun the caixa-mesh YAML emitter would silently
17424        // reinterpret at the Gateway API v1 HTTPRoute admission
17425        // layer (an embedded LF byte in a YAML plain scalar either
17426        // truncates the value at the emitter or crashes the parser
17427        // on the k8s-apiserver side). Pins the third representative
17428        // of the full ASCII-whitespace set through the shared
17429        // predicate.
17430        let mut s = three_member_spec();
17431        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
17432        let err = s.validate().unwrap_err();
17433        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17434            panic!("expected EntradaHostInvalid, got {err:?}");
17435        };
17436        assert!(
17437            reason.contains("ASCII whitespace byte"),
17438            "expected byte-naming diagnostic, got {reason:?}"
17439        );
17440        assert!(
17441            reason.contains("0x0a"),
17442            "expected offending LF byte 0x0a, got {reason:?}"
17443        );
17444    }
17445
17446    #[test]
17447    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
17448        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
17449        // axis — the canonical paste-from-typography /
17450        // paste-from-word-processor footgun. Before the non-ASCII
17451        // Unicode `White_Space` scan lifted through the shared
17452        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
17453        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
17454        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
17455        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
17456        // with the far-from-source `label "…" must start and end
17457        // with an alphanumeric` diagnostic — burying the
17458        // paste-from-typography origin under a label-shape leak.
17459        // Peer with the sibling non-ASCII-whitespace pins at
17460        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
17461        // — 1b75b38), `limits::parse_duration`,
17462        // `limits::parse_millicores`, and the shared duration codec
17463        // — same "the diagnostic carries the offending Unicode
17464        // codepoint's `U+XXXX` shape" discipline extended from every
17465        // typed-magnitude codec to the Gateway API v1 Hostname axis.
17466        let mut s = three_member_spec();
17467        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
17468        let err = s.validate().unwrap_err();
17469        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17470            panic!("expected EntradaHostInvalid, got {err:?}");
17471        };
17472        assert!(
17473            reason.contains("non-ASCII Unicode whitespace character"),
17474            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17475        );
17476        assert!(
17477            reason.contains("U+00A0"),
17478            "expected offending NBSP codepoint U+00A0, got {reason:?}"
17479        );
17480    }
17481
17482    #[test]
17483    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
17484        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
17485        // `:entrada :host` axis — the canonical paste-from-web-doc /
17486        // paste-from-published-HTML footgun. `char::is_whitespace`
17487        // returns true for `U+2028` per the Unicode `White_Space`
17488        // property, so `str::trim` at any downstream site would
17489        // silently strip it — same drift class as NBSP but on a
17490        // different codepoint region. Pins the second representative
17491        // (non-Latin-1 `char::is_whitespace` member) through the
17492        // shared predicate. Peer with
17493        // `parse_byte_size_rejects_internal_line_separator` on
17494        // `limits::parse_byte_size` (1b75b38).
17495        let mut s = three_member_spec();
17496        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
17497        let err = s.validate().unwrap_err();
17498        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17499            panic!("expected EntradaHostInvalid, got {err:?}");
17500        };
17501        assert!(
17502            reason.contains("non-ASCII Unicode whitespace character"),
17503            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17504        );
17505        assert!(
17506            reason.contains("U+2028"),
17507            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
17508        );
17509    }
17510
17511    #[test]
17512    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
17513        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
17514        // labels in the `:entrada :host` axis — the canonical
17515        // paste-from-CJK-typography footgun (CJK IMEs default to
17516        // full-width whitespace when the space bar is pressed in
17517        // Japanese / Chinese input modes). Pins the third
17518        // representative of the non-ASCII Unicode `White_Space` set
17519        // through the shared predicate: the CJK block, distinct from
17520        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
17521        // SEPARATOR `U+2028` — covering the same axis breadth the
17522        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
17523        // (1b75b38) pins on `limits::parse_byte_size`.
17524        let mut s = three_member_spec();
17525        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
17526        let err = s.validate().unwrap_err();
17527        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
17528            panic!("expected EntradaHostInvalid, got {err:?}");
17529        };
17530        assert!(
17531            reason.contains("non-ASCII Unicode whitespace character"),
17532            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
17533        );
17534        assert!(
17535            reason.contains("U+3000"),
17536            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
17537        );
17538    }
17539
17540    #[test]
17541    fn rejects_entrada_host_too_long() {
17542        // Total length cap = 253; build a 254-byte host out of two
17543        // 63-byte labels + one 62-byte label + dots.
17544        let mut s = three_member_spec();
17545        let big = format!(
17546            "{}.{}.{}.{}",
17547            "a".repeat(63),
17548            "b".repeat(63),
17549            "c".repeat(63),
17550            "d".repeat(254 - 63 * 3 - 3)
17551        );
17552        assert_eq!(big.len(), 254);
17553        s.entrada.as_mut().unwrap().host = big;
17554        let err = s.validate().unwrap_err();
17555        assert!(
17556            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17557                if reason.contains("max length of 253")),
17558            "got {err:?}"
17559        );
17560    }
17561
17562    #[test]
17563    fn rejects_entrada_host_label_too_long() {
17564        let mut s = three_member_spec();
17565        // 64-byte label — one over the per-label cap.
17566        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
17567        let err = s.validate().unwrap_err();
17568        assert!(
17569            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17570                if reason.contains("label max length of 63")),
17571            "got {err:?}"
17572        );
17573    }
17574
17575    #[test]
17576    fn entrada_host_diagnostic_carries_offending_host() {
17577        // Diagnostic-shape pin — the offending host + a non-empty
17578        // reason flow through verbatim so the author can grep their
17579        // caixa.lisp for `:host "<host>"` and fix it in one edit.
17580        let mut s = three_member_spec();
17581        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
17582        let err = s.validate().unwrap_err();
17583        match err {
17584            AplicacaoError::EntradaHostInvalid { host, reason } => {
17585                assert_eq!(host, "checkout.quero.cloud:8080");
17586                assert!(!reason.is_empty(), "reason field must be non-empty");
17587            }
17588            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17589        }
17590    }
17591
17592    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
17593    // substrate primitive that folds the fourteen
17594    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
17595    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
17596    // one dispatch — peer with the sixteen equivalence pins the
17597    // [`crate::LayoutError`] `_violation` constructor family carries in
17598    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
17599    // fixture host + reason are fixed `&'static str`s so both fields of
17600    // both constructed variants pin verbatim: the `host` axis is pinned
17601    // through the shared `host.to_string()` wrap (the ctor's uniform
17602    // one-slot construction) and the `reason` axis is pinned through
17603    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
17604    // routing). Any future regression on the lift (an extra field
17605    // introduced without updating the ctor, a diverging string
17606    // conversion at either arm) surfaces at this pin's diagnostic
17607    // rather than at a per-wire-up struct-literal reintroduction.
17608    #[test]
17609    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
17610        let host = "checkout.quero.cloud:8080";
17611        let reason = "sample reason text";
17612        assert_eq!(
17613            AplicacaoError::entrada_host_invalid(host, reason),
17614            AplicacaoError::EntradaHostInvalid {
17615                host: host.to_string(),
17616                reason: reason.to_string(),
17617            },
17618            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
17619        );
17620    }
17621
17622    // Routing pin — the ctor's `host: &str` argument threads through
17623    // `.to_string()` verbatim on the `host` field, so the constructed
17624    // variant carries the offending host bytes without any wrapper-
17625    // side transformation (no `.to_ascii_lowercase()` normalization,
17626    // no `.trim()` strip, no truncation) — the same "diagnostic carries
17627    // the offending value verbatim so the author can grep their
17628    // caixa.lisp" discipline every peer typed-slot ctor at this
17629    // altitude carries.
17630    #[test]
17631    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
17632        // Uppercase + trailing whitespace + port suffix — three
17633        // wrapper-side transformations the ctor must *not* apply.
17634        let host = " Checkout.quero.CLOUD:8080 ";
17635        let err = AplicacaoError::entrada_host_invalid(host, "sample");
17636        match err {
17637            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
17638                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
17639            }
17640            other => panic!("expected EntradaHostInvalid, got {other:?}"),
17641        }
17642    }
17643
17644    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
17645    // `&str` literals and `format!(…)` outputs identically and both
17646    // route through `Into::into` verbatim onto the `reason` field.
17647    // Pins both codepaths against the same host to prove the two
17648    // shapes the fourteen wire-up sites use at their per-arm diagnostic
17649    // (ten `&str` literals — some with `.to_string()` at the caller,
17650    // some without — plus four `format!(…)` outputs) each produce
17651    // byte-equal `reason` fields against the same offending host.
17652    #[test]
17653    fn entrada_host_invalid_ctor_routes_reason_through_into() {
17654        let host = "checkout.quero.cloud";
17655        // `&str` literal — the ctor's `impl Into<String>` accepts it
17656        // without a caller-side `.to_string()`.
17657        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
17658        // Owned `String` from `format!` — the peer `format!(…)`-shaped
17659        // wire-up arm.
17660        let from_format =
17661            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
17662        // `String` from `.to_string()` on a literal — the peer
17663        // `"literal".to_string()`-shaped wire-up arm the pre-lift
17664        // sites carried.
17665        let from_to_string =
17666            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
17667        match (&from_literal, &from_format, &from_to_string) {
17668            (
17669                AplicacaoError::EntradaHostInvalid {
17670                    reason: r_lit,
17671                    host: h_lit,
17672                },
17673                AplicacaoError::EntradaHostInvalid {
17674                    reason: r_fmt,
17675                    host: h_fmt,
17676                },
17677                AplicacaoError::EntradaHostInvalid {
17678                    reason: r_ts,
17679                    host: h_ts,
17680                },
17681            ) => {
17682                assert_eq!(r_lit, "literal reason text");
17683                assert_eq!(r_fmt, "literal reason text");
17684                assert_eq!(r_ts, "literal reason text");
17685                assert_eq!(h_lit, host);
17686                assert_eq!(h_fmt, host);
17687                assert_eq!(h_ts, host);
17688            }
17689            _ => panic!("expected three EntradaHostInvalid variants"),
17690        }
17691        // Cross-arm equivalence — the three shapes must produce
17692        // byte-equal `AplicacaoError` values, so the fourteen wire-up
17693        // sites' mixed per-arm shapes fold onto one canonical form.
17694        assert_eq!(from_literal, from_format);
17695        assert_eq!(from_literal, from_to_string);
17696    }
17697
17698    // Equivalence pins for the six sibling
17699    // [`aplicacao_field_reason_ctors!`]-generated constructors that
17700    // fold the peer `{ <field>: String, reason: String }` variants
17701    // onto the same substrate-primitive family
17702    // `entrada_host_invalid` (17dd504) already carries pins for.
17703    // Each ctor's fixture pair (a fixed `&'static str` value and a
17704    // fixed `&'static str` reason) pins both fields verbatim so any
17705    // future regression on the macro (an extra field introduced
17706    // without updating the macro, a diverging string conversion at
17707    // either arm, a field-name typo on one variant that dropped it
17708    // off the shared shape) surfaces at the affected variant's pin
17709    // rather than at a per-wire-up struct-literal reintroduction. Peer
17710    // discipline of the sixteen `LayoutError` _violation ctor pins in
17711    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
17712    // and the paired
17713    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
17714    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
17715    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
17716    // (8580068) equivalence pins on the sibling `AplicacaoError`
17717    // ctor macros.
17718    #[test]
17719    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
17720        let caixa = "cart-svc";
17721        let reason = "sample reason text";
17722        assert_eq!(
17723            AplicacaoError::membro_caixa_invalid(caixa, reason),
17724            AplicacaoError::MembroCaixaInvalid {
17725                caixa: caixa.to_string(),
17726                reason: reason.to_string(),
17727            },
17728        );
17729    }
17730
17731    #[test]
17732    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
17733        let para = "checkout";
17734        let reason = "sample reason text";
17735        assert_eq!(
17736            AplicacaoError::entrada_para_invalid(para, reason),
17737            AplicacaoError::EntradaParaInvalid {
17738                para: para.to_string(),
17739                reason: reason.to_string(),
17740            },
17741        );
17742    }
17743
17744    #[test]
17745    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
17746        let path = "/api/cart";
17747        let reason = "sample reason text";
17748        assert_eq!(
17749            AplicacaoError::entrada_path_invalid(path, reason),
17750            AplicacaoError::EntradaPathInvalid {
17751                path: path.to_string(),
17752                reason: reason.to_string(),
17753            },
17754        );
17755    }
17756
17757    #[test]
17758    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
17759        let cluster = "rio";
17760        let reason = "sample reason text";
17761        assert_eq!(
17762            AplicacaoError::placement_cluster_invalid(cluster, reason),
17763            AplicacaoError::PlacementClusterInvalid {
17764                cluster: cluster.to_string(),
17765                reason: reason.to_string(),
17766            },
17767        );
17768    }
17769
17770    #[test]
17771    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
17772        let affinity = "data-locality";
17773        let reason = "sample reason text";
17774        assert_eq!(
17775            AplicacaoError::placement_affinity_invalid(affinity, reason),
17776            AplicacaoError::PlacementAffinityInvalid {
17777                affinity: affinity.to_string(),
17778                reason: reason.to_string(),
17779            },
17780        );
17781    }
17782
17783    #[test]
17784    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
17785        let shard_key = "tenantId";
17786        let reason = "sample reason text";
17787        assert_eq!(
17788            AplicacaoError::shard_key_invalid(shard_key, reason),
17789            AplicacaoError::ShardKeyInvalid {
17790                shard_key: shard_key.to_string(),
17791                reason: reason.to_string(),
17792            },
17793        );
17794    }
17795
17796    // Pin the three-slot per-`:contratos <slot>` sibling of the
17797    // two-slot `aplicacao_field_reason_ctors!` family — the sole
17798    // per-axis ctor carrying the extra `slot: &'static str` axis-tag
17799    // distinguishing the two-arm `:de` / `:para` cascade. Sweeps both
17800    // canonical author-side slot tags through the ctor and asserts
17801    // byte-equality against the pre-lift struct-literal shape so no
17802    // per-arm wrapper transformation drifts in against the sole
17803    // in-crate wire-up.
17804    #[test]
17805    fn contrato_caixa_invalid_ctor_matches_struct_literal_wrap() {
17806        let caixa = "cart-svc";
17807        let reason = "sample reason text";
17808        for slot in [
17809            crate::render::CONTRATO_AUTHOR_KEY_DE,
17810            crate::render::CONTRATO_AUTHOR_KEY_PARA,
17811        ] {
17812            assert_eq!(
17813                AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
17814                AplicacaoError::ContratoCaixaInvalid {
17815                    slot,
17816                    caixa: caixa.to_string(),
17817                    reason: reason.to_string(),
17818                },
17819            );
17820        }
17821    }
17822
17823    // The `reason: impl Into<String>` bound accepts both a `&str`
17824    // literal and a `format!(…)` owned-`String` output verbatim,
17825    // matching the peer `aplicacao_field_reason_ctors!` family's
17826    // reason-axis invariance so the sole in-crate wire-up's
17827    // `require_valid_dns_1123_label`-delivered owned-`String` return
17828    // and any future `&str` literal caller land on the same variant.
17829    #[test]
17830    fn contrato_caixa_invalid_ctor_routes_reason_through_into_uniformly() {
17831        let via_literal = "literal reason text";
17832        let via_format = format!("{} reason text", "literal");
17833        for slot in [
17834            crate::render::CONTRATO_AUTHOR_KEY_DE,
17835            crate::render::CONTRATO_AUTHOR_KEY_PARA,
17836        ] {
17837            assert_eq!(
17838                AplicacaoError::contrato_caixa_invalid(slot, "c", via_literal),
17839                AplicacaoError::contrato_caixa_invalid(slot, "c", via_format.clone()),
17840            );
17841        }
17842    }
17843
17844    // Cross-family invariance pin — the six sibling ctors and
17845    // `entrada_host_invalid` all route `reason: impl Into<String>` +
17846    // `<field>: &str` verbatim onto their respective typed variants
17847    // through the shared [`aplicacao_field_reason_ctors!`] macro.
17848    // Sweeps a fixture pair (`&str` literal, `format!` output) against
17849    // every ctor to pin that no per-arm wrapper transformation drifted
17850    // in against the uniform macro-generated body.
17851    #[test]
17852    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
17853        let via_literal = "literal reason text";
17854        let via_format = format!("{} reason text", "literal");
17855        assert_eq!(
17856            AplicacaoError::membro_caixa_invalid("m", via_literal),
17857            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
17858        );
17859        assert_eq!(
17860            AplicacaoError::entrada_para_invalid("p", via_literal),
17861            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
17862        );
17863        assert_eq!(
17864            AplicacaoError::entrada_path_invalid("/a", via_literal),
17865            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
17866        );
17867        assert_eq!(
17868            AplicacaoError::placement_cluster_invalid("c", via_literal),
17869            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
17870        );
17871        assert_eq!(
17872            AplicacaoError::placement_affinity_invalid("a", via_literal),
17873            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
17874        );
17875        assert_eq!(
17876            AplicacaoError::shard_key_invalid("k", via_literal),
17877            AplicacaoError::shard_key_invalid("k", via_format.clone()),
17878        );
17879        assert_eq!(
17880            AplicacaoError::entrada_host_invalid("h", via_literal),
17881            AplicacaoError::entrada_host_invalid("h", via_format),
17882        );
17883    }
17884
17885    #[test]
17886    fn entrada_host_empty_takes_precedence_over_invalid() {
17887        // Ordering pin: `EmptyEntradaHost` is the more self-locating
17888        // diagnostic on `""` and must lead — `validate_entrada_host`
17889        // is only reached after the empty-check fires at the call
17890        // site. (The predicate itself defends against direct
17891        // invocation by returning the same error on `""`.)
17892        let mut s = three_member_spec();
17893        s.entrada.as_mut().unwrap().host = String::new();
17894        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
17895    }
17896
17897    #[test]
17898    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
17899        // Ordering pin: a missing :para member is the more
17900        // self-locating diagnostic and fires before the host gate.
17901        let mut s = three_member_spec();
17902        let e = s.entrada.as_mut().unwrap();
17903        e.para = "ghost".into();
17904        e.host = "BAD HOST".into();
17905        let err = s.validate().unwrap_err();
17906        assert!(
17907            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
17908            "got {err:?}"
17909        );
17910    }
17911
17912    #[test]
17913    fn entrada_host_invalid_fires_before_port_zero() {
17914        // Ordering pin: the host gate fires before the port gate so
17915        // a malformed host is named even when the port is also wrong.
17916        let mut s = three_member_spec();
17917        let e = s.entrada.as_mut().unwrap();
17918        e.host = "Checkout.quero.cloud".into();
17919        e.port = 0;
17920        let err = s.validate().unwrap_err();
17921        assert!(
17922            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17923                if host == "Checkout.quero.cloud"),
17924            "got {err:?}"
17925        );
17926    }
17927
17928    #[test]
17929    fn entrada_accepts_canonical_hosts() {
17930        // Positive-control sweep — every form the Gateway API
17931        // apiserver accepts must round-trip through validate. Covers
17932        // a plain DNS subdomain, a leading wildcard, a single-label
17933        // host (cluster-internal), a max-length-edge label, a
17934        // hyphen-bearing label, and a Punycode IDN label.
17935        for host in [
17936            "checkout.quero.cloud",
17937            "*.quero.cloud",
17938            "checkout",
17939            // 63-byte label — exactly the per-label cap.
17940            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
17941            "foo-bar.quero.cloud",
17942            // Punycode IDN — valid because the author pre-encoded.
17943            "xn--bcher-kva.example.com",
17944        ] {
17945            let mut s = three_member_spec();
17946            s.entrada.as_mut().unwrap().host = host.into();
17947            s.validate()
17948                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
17949        }
17950    }
17951
17952    #[test]
17953    fn entrada_host_max_length_validates() {
17954        // 253-byte host is the cap exactly — must validate. Build a
17955        // 253-byte host out of three 63-byte labels + one 61-byte
17956        // label + 3 dots = 252 bytes, then pad one byte to 253.
17957        let mut s = three_member_spec();
17958        let host = format!(
17959            "{}.{}.{}.{}",
17960            "a".repeat(63),
17961            "b".repeat(63),
17962            "c".repeat(63),
17963            "d".repeat(253 - 63 * 3 - 3)
17964        );
17965        assert_eq!(host.len(), 253);
17966        s.entrada.as_mut().unwrap().host = host;
17967        s.validate().unwrap();
17968    }
17969
17970    #[test]
17971    fn entrada_host_total_length_cap_threads_lifted_render_const() {
17972        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
17973        // total-length gate now reads the K8s Gateway API v1 Hostname
17974        // `maxLength: 253` cap from the lifted
17975        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
17976        // of truth — the same constant every future Gateway-API-Hostname
17977        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
17978        // materializer's per-host validator, the future per-`Certificate`
17979        // SAN emitter for cert-manager, the multi-`:entrada`
17980        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
17981        // from. Before the lift, the aplicacao-side reader consumed a
17982        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
17983        // 253-byte value as the peer render-side canonical bounds
17984        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
17985        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
17986        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
17987        // module boundary — a future 253-byte drift on either side would
17988        // silently split into two axes' worth of admission-schema mismatch
17989        // without a build-time signal. Pin the cap through a fresh 254-
17990        // byte host that hits the total-length arm, then read the reason
17991        // for the exact byte count the shared constant carries: any future
17992        // regression on the lift (a private alias reintroduced, a hard-
17993        // coded literal at the arm, a mismatch between the aplicacao-side
17994        // and render-side canonicals) surfaces as this pin's diagnostic
17995        // failing to match, not as a per-cluster admission rejection far
17996        // from the caixa.lisp source line.
17997        let mut s = three_member_spec();
17998        let over_cap = format!(
17999            "{}.{}.{}.{}",
18000            "a".repeat(63),
18001            "b".repeat(63),
18002            "c".repeat(63),
18003            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
18004        );
18005        assert_eq!(
18006            over_cap.len(),
18007            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
18008        );
18009        s.entrada.as_mut().unwrap().host = over_cap;
18010        let err = s.validate().unwrap_err();
18011        match err {
18012            AplicacaoError::EntradaHostInvalid { reason, .. } => {
18013                let needle = format!(
18014                    "max length of {} bytes",
18015                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
18016                );
18017                assert!(
18018                    reason.contains(&needle),
18019                    "diagnostic must name the lifted \
18020                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
18021                );
18022            }
18023            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18024        }
18025    }
18026
18027    #[test]
18028    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
18029        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
18030        // on the per-label-cap axis. Before the lift, the aplicacao-side
18031        // per-label arm consumed a private const alias
18032        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
18033        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
18034        // split from it at the module boundary — every `.`-separated
18035        // label in a Gateway API v1 Hostname is a DNS-1123 label under
18036        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
18037        // so the private alias's 63 and the canonical const's 63 were
18038        // pinning the same underlying rule twice. Pin the cap through a
18039        // 64-byte label that hits the per-label arm, then read the reason
18040        // for the exact byte count the shared constant carries: any
18041        // future drift on either side (a private alias reintroduced, a
18042        // hard-coded literal at the arm, a mismatch between the two
18043        // 63-byte pins) surfaces at this pin's diagnostic rather than at
18044        // a per-cluster admission rejection whose "field is invalid"
18045        // opacity misframes the root cause.
18046        let mut s = three_member_spec();
18047        let over_cap_label = format!(
18048            "{}.quero.cloud",
18049            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
18050        );
18051        s.entrada.as_mut().unwrap().host = over_cap_label;
18052        let err = s.validate().unwrap_err();
18053        match err {
18054            AplicacaoError::EntradaHostInvalid { reason, .. } => {
18055                let needle = format!(
18056                    "label max length of {} bytes",
18057                    crate::render::DNS_1123_LABEL_MAX_LEN,
18058                );
18059                assert!(
18060                    reason.contains(&needle),
18061                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
18062                     cap verbatim on the per-label arm, got: {reason:?}",
18063                );
18064            }
18065            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18066        }
18067    }
18068
18069    #[test]
18070    fn entrada_with_empty_paths_validates() {
18071        // Empty `:paths` is the documented "match every path" form;
18072        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
18073        let mut s = three_member_spec();
18074        s.entrada.as_mut().unwrap().paths = vec![];
18075        s.validate().unwrap();
18076    }
18077
18078    #[test]
18079    fn entrada_root_path_validates() {
18080        // The author-supplied bare-root `:entrada :paths` entry is the
18081        // same byte-shape the peer emit-side catch-all constant
18082        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
18083        // the author's `:paths` list is empty — sweeping the test-side
18084        // probe literal onto the lifted const closes the two-axis pin
18085        // (author-side admit + emit-side canonical fallback) around
18086        // one `&'static str`, so a future rebrand of the catch-all
18087        // reaches both consumers by construction. Peer to
18088        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
18089        // on the canonical-literal pin surface.
18090        let mut s = three_member_spec();
18091        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
18092        s.validate().unwrap();
18093    }
18094
18095    #[test]
18096    fn placement_strategy_variants_round_trip() {
18097        for s in [
18098            PlacementStrategy::SingleNode,
18099            PlacementStrategy::Replicated,
18100            PlacementStrategy::Sharded,
18101        ] {
18102            let p = Placement {
18103                estrategia: s,
18104                clusters: vec!["rio".into()],
18105                affinity: None,
18106                // Route the paired `:shard-key` fixture-builder through the
18107                // typed cross-slot invariant predicate
18108                // [`PlacementStrategy::requires_shard_key`] rather than the
18109                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
18110                // arm-identity predicate — the two answer the same
18111                // question under today's closed accept-set but a future
18112                // arm addition that consumed `:shard-key` under a
18113                // non-`Sharded` name would silently mis-attach the
18114                // fixture's `:shard-key` if the builder read through the
18115                // arm-identity predicate. The cross-slot-invariant
18116                // predicate migrates through one caixa-core edit on any
18117                // future arm addition; the fixture keeps producing a
18118                // `validate()`-passing round-trip by construction.
18119                shard_key: if s.requires_shard_key() {
18120                    Some("$key".into())
18121                } else {
18122                    None
18123                },
18124            };
18125            let json = serde_json::to_string(&p).unwrap();
18126            let back: Placement = serde_json::from_str(&json).unwrap();
18127            assert_eq!(back, p);
18128        }
18129    }
18130
18131    #[test]
18132    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
18133        // The fail-before-pass-after pin: pre-lift there was no
18134        // single-source binding between the [`PlacementStrategy`]
18135        // variant name the `Serialize` derive emits and the byte-
18136        // string every downstream cluster-side dispatcher (the
18137        // `lareira-fleet-programs` aggregator's per-entry strategy
18138        // branch, the future `app-operator` reconciler, the M3
18139        // Adaptive compression pass's per-strategy weighting) probes
18140        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
18141        // future `#[serde(rename_all = "kebab-case")]` attribute on
18142        // the enum — or a variant rename in the source — would
18143        // silently rebrand the emitted scalar under one spelling
18144        // while every downstream dispatcher still probed the other,
18145        // with the failure surfacing at the aggregator's dispatch
18146        // step or the operator's reconcile posture (workloads coming
18147        // up under the `default()` `Replicated` arm rather than the
18148        // typed slot's declared strategy) far from the source
18149        // rebrand commit and with no field naming the drift. Pinning
18150        // the two paths (the `Serialize` derive's serialized string
18151        // AND the [`PlacementStrategy::as_str`] helper) to the same
18152        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
18153        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
18154        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
18155        // makes any future drift on either endpoint fail here at
18156        // caixa-core build time.
18157        for (variant, expected) in [
18158            (
18159                PlacementStrategy::SingleNode,
18160                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18161            ),
18162            (
18163                PlacementStrategy::Replicated,
18164                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18165            ),
18166            (
18167                PlacementStrategy::Sharded,
18168                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18169            ),
18170        ] {
18171            let json = serde_json::to_string(&variant).unwrap();
18172            assert_eq!(
18173                json,
18174                format!("\"{expected}\""),
18175                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
18176            );
18177            assert_eq!(
18178                variant.as_str(),
18179                expected,
18180                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
18181                 M3_PLACEMENT_ESTRATEGIA_* constant"
18182            );
18183        }
18184    }
18185
18186    #[test]
18187    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
18188        // Cross-arm drift-detection pin on the M3
18189        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
18190        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
18191        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
18192        // scalar-value pentad: a future collapse of two canonical
18193        // variant byte-strings onto the same value (an accidental
18194        // copy-paste flip of
18195        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
18196        // read `"SingleNode"`, a per-arm rebrand that lands one const
18197        // without touching its paired peer) would silently reroute
18198        // every downstream operator's per-strategy dispatch onto the
18199        // sibling arm's reconcile branch and pass every
18200        // propagation-probe test that expected only the stale arm's
18201        // value — a `Replicated`-declared Aplicacao would come up
18202        // under the `SingleNode` primary-and-standby reconcile
18203        // posture, so every-cluster active-active workload would
18204        // silently collapse onto one-cluster-runs-at-a-time takeover
18205        // semantics against its declared strategy, with no field
18206        // naming the strategy-value drift root cause. Peer of the
18207        // sibling
18208        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
18209        // (09ffb2d) /
18210        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
18211        // (ccdf955) /
18212        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
18213        // (d739850) distinctness pins on the sibling OTP-shape /
18214        // caixa-kind closed-set typed-enum discriminator axes — the
18215        // fourth (and structurally the M3 mesh-primitive-defining)
18216        // closed-set typed-enum axis to converge on the same
18217        // "pairwise-distinct-by-construction" discipline.
18218        //
18219        // Fail-before-pass-after locally verified by mutating
18220        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
18221        // also read `"SingleNode"` — this pin fires as expected;
18222        // restoring passes.
18223        let all = [
18224            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18225            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18226            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18227        ];
18228        for (i, a) in all.iter().enumerate() {
18229            for (j, b) in all.iter().enumerate() {
18230                if i != j {
18231                    assert_ne!(
18232                        a, b,
18233                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
18234                         distinct — got duplicate {a:?} at indices {i} and {j}",
18235                    );
18236                }
18237            }
18238        }
18239    }
18240
18241    #[test]
18242    fn placement_strategy_display_routes_through_as_str_helper() {
18243        // The fail-before-pass-after pin: pre-lift the sibling
18244        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
18245        // / [`crate::supervisor::RestartPolicy`] both carried a stable
18246        // [`std::fmt::Display`] surface via their
18247        // `#[discriminant(also_display)]` gen-platform derive, but
18248        // [`PlacementStrategy`] did not — every consumer reaching for
18249        // a strategy byte-string past the wire format had to pick
18250        // between three paths ([`PlacementStrategy::as_str`], the
18251        // `Serialize` derive's serialized string, or `format!("{v:?}")`
18252        // on the `Debug` derive), any two of which a future variant
18253        // rename or `#[serde(rename_all = "kebab-case")]` attribute
18254        // would silently desynchronize. Wiring [`std::fmt::Display`]
18255        // through [`PlacementStrategy::as_str`] closes the third path:
18256        // every `format!("{v}")` call reaches the same lifted
18257        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
18258        // and the [`PlacementStrategy::as_str`] helper already route
18259        // through, so a future variant rename lands at exactly one
18260        // place. Pin the routing here so a future
18261        // `impl std::fmt::Display for PlacementStrategy` reimplementation
18262        // that hand-rolls the arms instead of delegating to
18263        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
18264        for variant in [
18265            PlacementStrategy::SingleNode,
18266            PlacementStrategy::Replicated,
18267            PlacementStrategy::Sharded,
18268        ] {
18269            assert_eq!(
18270                variant.to_string(),
18271                variant.as_str(),
18272                "PlacementStrategy::{variant:?} Display must route through \
18273                 PlacementStrategy::as_str (single source of truth: the lifted \
18274                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
18275            );
18276        }
18277    }
18278
18279    #[test]
18280    fn placement_strategy_display_matches_serialized_wire_byte_string() {
18281        // The fail-before-pass-after pin on the second half of the
18282        // three-path convergence: `Display` (user-facing text) agrees
18283        // byte-for-byte with the `Serialize` derive's wire format
18284        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
18285        // scalar) on every variant. Pre-lift the two paths were
18286        // structurally independent — a future
18287        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
18288        // would silently rebrand the emitted wire scalar
18289        // (`single-node`, `replicated`, `sharded`) while every consumer
18290        // that pretty-prints the strategy (the M3 diagnostic templates,
18291        // the future `feira app graph` per-Aplicacao strategy line,
18292        // the future M4 CR materializer's admission-webhook rejection
18293        // body) would still emit the TitleCase form the `as_str` /
18294        // `Display` route returns, with the mismatch surfacing at
18295        // consumer parse time / operator dispatch time far from the
18296        // source rebrand commit. Pin the two paths byte-for-byte here
18297        // so any future serde-attribute or variant-rename drift is a
18298        // caixa-core-build-time test failure at this call, not a
18299        // silent per-consumer dispatch miss.
18300        for variant in [
18301            PlacementStrategy::SingleNode,
18302            PlacementStrategy::Replicated,
18303            PlacementStrategy::Sharded,
18304        ] {
18305            let wire = serde_json::to_string(&variant).unwrap();
18306            // Strip the outer `"…"` the JSON string form carries — the
18307            // wire scalar the K8s / YAML apiserver consumes is the
18308            // enclosed byte-string, not the quote wrapper.
18309            let unquoted = wire
18310                .strip_prefix('"')
18311                .and_then(|s| s.strip_suffix('"'))
18312                .expect("serialized PlacementStrategy is a JSON string");
18313            assert_eq!(
18314                variant.to_string(),
18315                unquoted,
18316                "PlacementStrategy::{variant:?} Display byte-string must match the \
18317                 Serialize derive's wire byte-string (three-path convergence: \
18318                 Display + as_str + Serialize all resolve to the same \
18319                 M3_PLACEMENT_ESTRATEGIA_* const)"
18320            );
18321        }
18322    }
18323
18324    #[test]
18325    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
18326        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18327        // derive on [`PlacementStrategy`]: for each of the three variants
18328        // exactly one of the generated `is_single_node` / `is_replicated`
18329        // / `is_sharded` predicates returns `true` and the other two
18330        // return `false`. Prior to this derive the three per-arm
18331        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
18332        // (the `placement_strategy_variants_round_trip` fixture, the
18333        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
18334        // fixture, and the
18335        // `validate_placement_reads_through_lifted_estrategia_accessor`
18336        // fixture) each open-coded a per-arm PartialEq compare against
18337        // the enum variant — three sites that expressed no compile-time
18338        // link back to the closed-set typed dispatch a future fourth
18339        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
18340        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
18341        // would have to thread through in lockstep or one fixture would
18342        // silently disagree with the others on which arms consume the
18343        // `:shard-key` axis. Peer of the sibling
18344        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
18345        // / [`crate::supervisor::RestartPolicy`] /
18346        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
18347        // the sibling closed-set typed-enum discriminator axes — extends
18348        // the same one-typed-dispatch-per-variant discipline onto the
18349        // fifth (and only remaining) closed-set typed-enum discriminator
18350        // on the caixa surface, closing the axis on the M3 mesh-slot
18351        // family.
18352        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
18353            (PlacementStrategy::SingleNode, [true, false, false]),
18354            (PlacementStrategy::Replicated, [false, true, false]),
18355            (PlacementStrategy::Sharded, [false, false, true]),
18356        ];
18357        for (variant, expected) in rows {
18358            let observed = [
18359                variant.is_single_node(),
18360                variant.is_replicated(),
18361                variant.is_sharded(),
18362            ];
18363            assert_eq!(
18364                observed, expected,
18365                "PlacementStrategy::{variant:?} is_* predicates must partition \
18366                 the arm set (single_node, replicated, sharded); got {observed:?}"
18367            );
18368        }
18369    }
18370
18371    #[test]
18372    fn placement_strategy_is_variant_predicates_are_const_fn() {
18373        // The [`gen_platform::IsVariant`] derive emits `const fn`
18374        // predicates on the peer [`crate::CaixaKind`] +
18375        // [`crate::upgrade::UpgradeInstruction`] +
18376        // [`crate::supervisor::RestartStrategy`] +
18377        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
18378        // pin the same posture on [`PlacementStrategy`] so a future
18379        // accidental downgrade to non-`const` (an added runtime helper
18380        // reachable only from a non-`const` context, a manual hand-rolled
18381        // `impl` that shadows the derive-generated method) trips at
18382        // caixa-core build time rather than surfacing as a downstream
18383        // `const`-context regression far from the derive declaration.
18384        //
18385        // The pin lives inside a `const { assert!(..) }` block so the
18386        // compiler enforces both halves (arm predicate is `const`-
18387        // callable AND returns `true` for the matching arm) at
18388        // caixa-core compile time — peer to the sibling
18389        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
18390        // pins on the closed-set typed enum arm-predicate const-
18391        // callability axis.
18392        const {
18393            assert!(PlacementStrategy::SingleNode.is_single_node());
18394            assert!(PlacementStrategy::Replicated.is_replicated());
18395            assert!(PlacementStrategy::Sharded.is_sharded());
18396        }
18397    }
18398
18399    #[test]
18400    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
18401        // Fail-before-pass-after pin on the substrate-lifted
18402        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
18403        // per-arm predicate: for each variant in the closed accept-set the
18404        // predicate returns `true` iff the variant consumes the paired
18405        // [`Placement::shard_key`] axis under
18406        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
18407        // partition. Today the accept-set is the singleton `{Sharded}` —
18408        // `Sharded` is the Akka-style hash-keyed distribution arm
18409        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
18410        // §II.1) and `Replicated` (active-active) refuse the axis through
18411        // [`AplicacaoError::ShardKeyOnNonSharded`].
18412        //
18413        // Pins the per-arm truth-table so a future arm addition (an
18414        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
18415        // roadmap names, a `WeightedShard` promotion the future M5
18416        // adaptive-placement engine acknowledges) that landed a variant
18417        // without extending this predicate's arm-set would surface as a
18418        // caixa-core build-time exhaustiveness error at the
18419        // `match self { … }` arm-fan below rather than a silent per-consumer
18420        // mis-classification at renderer emit time. The paired
18421        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
18422        // predicate stays a distinct question — arm-identity (which the
18423        // sibling
18424        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
18425        // pin already locks) is not cross-slot-invariant consumption; today
18426        // they trip on the same singleton but the pair migrates through
18427        // one caixa-core edit on any future arm addition.
18428        //
18429        // Peer of the sibling per-arm classifier pins
18430        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
18431        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
18432        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
18433        // derived paired predicate on the post-projection typed-view axis
18434        // — same "per-arm semantic-classification predicate paired with
18435        // the arm-identity predicate the derive already emits" discipline
18436        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
18437        // `:placement :shard-key` cross-slot-invariant axis.
18438        let rows: [(PlacementStrategy, bool); 3] = [
18439            (PlacementStrategy::SingleNode, false),
18440            (PlacementStrategy::Replicated, false),
18441            (PlacementStrategy::Sharded, true),
18442        ];
18443        for (variant, expected) in rows {
18444            assert_eq!(
18445                variant.requires_shard_key(),
18446                expected,
18447                "PlacementStrategy::{variant:?}.requires_shard_key() must \
18448                 be {expected} (the substrate-canonical cross-slot invariant \
18449                 on the :placement :shard-key axis; today `Sharded` is the \
18450                 singleton consuming arm — MESH-COMPOSITION §II.4)",
18451            );
18452        }
18453    }
18454
18455    #[test]
18456    fn placement_strategy_requires_shard_key_is_const_fn() {
18457        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
18458        // invariant per-arm predicate is declared `#[must_use] pub const
18459        // fn` — pin the `const`-eval posture here so a future accidental
18460        // downgrade to non-`const` (an added runtime helper reachable
18461        // only from a non-`const` context, a manual hand-rolled `impl`
18462        // that shadows the current three-arm `match self { … }` dispatch)
18463        // trips at caixa-core build time rather than surfacing as a
18464        // downstream `const`-context regression far from the declaration.
18465        // Same shape as the sibling
18466        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
18467        // the peer [`gen_platform::IsVariant`]-derived arm-identity
18468        // predicate axis, but here the load-bearing assertions live in
18469        // module-scope `const _: () = assert!(…)` items so a violation
18470        // fails at compile time (const-eval trip) rather than test time —
18471        // strictly stronger than the runtime `assert!(CONST)` pattern the
18472        // sibling pin uses, and side-steps the
18473        // `clippy::assertions_on_constants` lint the runtime pattern
18474        // otherwise accumulates on the module baseline.
18475        //
18476        // The test body simply witnesses that the module-scope items
18477        // compiled and the runtime dispatch agrees with the const-eval
18478        // dispatch on every arm — the runtime read gives the test a
18479        // failure surface (rather than an empty test body clippy would
18480        // flag as a no-op).
18481        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
18482        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
18483        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
18484        assert_eq!(
18485            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
18486            [
18487                PlacementStrategy::SingleNode.requires_shard_key(),
18488                PlacementStrategy::Replicated.requires_shard_key(),
18489                PlacementStrategy::Sharded.requires_shard_key(),
18490            ],
18491            "runtime and const-eval dispatch on \
18492             PlacementStrategy::requires_shard_key must agree on every arm",
18493        );
18494    }
18495
18496    #[test]
18497    fn placement_estrategia_accessor_is_const_fn() {
18498        // The [`Placement::estrategia`] per-`:placement` distribution-
18499        // strategy `Copy`-return scalar accessor is declared
18500        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
18501        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
18502        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
18503        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
18504        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
18505        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
18506        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
18507        // [`RateLimit`], every one a `pub const fn`). Pin the
18508        // `const`-eval posture here so a future accidental downgrade to
18509        // non-`const` (an added runtime helper reachable only from a
18510        // non-`const` context, a slot promotion to a non-`Copy` return
18511        // that would silently drop the `const` qualifier, a manual
18512        // hand-rolled shadow) trips at caixa-core build time rather
18513        // than surfacing as a downstream `const`-context regression far
18514        // from the declaration.
18515        //
18516        // Same shape as the sibling
18517        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
18518        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
18519        // predicate axis — the load-bearing witness lives in the
18520        // module-scope `const fn` wrapper `estrategia_via_const_fn`
18521        // below: a body that calls [`Placement::estrategia`] under a
18522        // `const fn` signature is well-formed only when the callee is
18523        // itself `const fn`, so any future accidental downgrade of
18524        // [`Placement::estrategia`] to non-`const` fails at caixa-core
18525        // build time (const-eval E0015 / E0658 depending on the arm),
18526        // strictly stronger than a runtime `assert!(CONST)` and
18527        // side-stepping the destructor-in-const restriction that
18528        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
18529        // items on `Placement`'s `Vec<String>` / `Option<String>`
18530        // carriers.
18531        //
18532        // The runtime body witnesses that the const-eval-shaped
18533        // wrapper agrees with a direct call on every closed-set arm.
18534        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
18535            p.estrategia()
18536        }
18537        for estrategia in [
18538            PlacementStrategy::SingleNode,
18539            PlacementStrategy::Replicated,
18540            PlacementStrategy::Sharded,
18541        ] {
18542            let placement = Placement {
18543                estrategia,
18544                clusters: Vec::new(),
18545                affinity: None,
18546                shard_key: None,
18547            };
18548            assert_eq!(
18549                estrategia_via_const_fn(&placement),
18550                placement.estrategia(),
18551                "const-fn-wrapped and direct dispatch on \
18552                 Placement::estrategia must agree for {estrategia:?}",
18553            );
18554        }
18555    }
18556
18557    #[test]
18558    fn entrada_port_accessor_is_const_fn() {
18559        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
18560        // scalar accessor is declared `#[must_use] pub const fn` —
18561        // matching the peer M3 mesh-slot `Copy`-return accessor family
18562        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
18563        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
18564        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
18565        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
18566        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
18567        // [`RateLimit::window`] on the sibling [`RateLimit`], the
18568        // sibling per-`:placement` [`Placement::estrategia`] pinned by
18569        // [`placement_estrategia_accessor_is_const_fn`] above — every
18570        // one a `pub const fn`). Pin the `const`-eval posture here so
18571        // a future accidental downgrade to non-`const` (an added
18572        // runtime helper reachable only from a non-`const` context, an
18573        // `Option<u16>`-shape migration once the substrate grows
18574        // per-`:membros` heterogeneous listener ports that would
18575        // silently drop the `const` qualifier, a manual hand-rolled
18576        // shadow) trips at caixa-core build time rather than surfacing
18577        // as a downstream `const`-context regression far from the
18578        // declaration.
18579        //
18580        // Same shape as the sibling
18581        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
18582        // load-bearing witness lives in the module-scope `const fn`
18583        // wrapper `port_via_const_fn`: a body that calls
18584        // [`Entrada::port`] under a `const fn` signature is well-formed
18585        // only when the callee is itself `const fn`, side-stepping the
18586        // destructor-in-const restriction that would otherwise block a
18587        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
18588        // `String` / `Vec<String>` carriers.
18589        //
18590        // The runtime body sweeps a representative port set spanning
18591        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
18592        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
18593        // ceiling — the const-fn-wrapped call must agree with a direct
18594        // call on every fixture (a violation trips the test) and every
18595        // returned scalar must byte-equal the input `port` (a violation
18596        // means the accessor stopped being a raw field-return copy).
18597        const fn port_via_const_fn(e: &Entrada) -> u16 {
18598            e.port()
18599        }
18600        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
18601            let entrada = Entrada {
18602                host: String::new(),
18603                para: String::new(),
18604                port,
18605                paths: Vec::new(),
18606            };
18607            assert_eq!(
18608                port_via_const_fn(&entrada),
18609                entrada.port(),
18610                "const-fn-wrapped and direct dispatch on Entrada::port \
18611                 must agree for port={port}",
18612            );
18613            assert_eq!(
18614                entrada.port(),
18615                port,
18616                "Entrada::port must return the storage-side u16 verbatim \
18617                 for port={port}",
18618            );
18619        }
18620    }
18621
18622    #[test]
18623    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
18624        // Load-bearing cross-slot-partition pin closing the loop between
18625        // the substrate-lifted
18626        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
18627        // the closed-set typed enum and the actual
18628        // [`AplicacaoSpec::validate_placement`] runtime behavior across
18629        // the paired `:placement :shard-key` axis: every validated
18630        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
18631        // satisfies `placement.shard_key().is_some() ==
18632        // placement.estrategia().requires_shard_key()`. The four-cell
18633        // shape witness sweeps every combination of (variant in the
18634        // closed accept-set, `:shard-key` Some/None) and pins:
18635        //
18636        //   * variant.requires_shard_key() && shard_key.is_some() →
18637        //     validate() passes; the paired shape is the sole
18638        //     `requires_shard_key` arm-family accepted shape.
18639        //   * variant.requires_shard_key() && shard_key.is_none() →
18640        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
18641        //     the paired shape is the refused missing-key shape on
18642        //     Sharded-family arms.
18643        //   * !variant.requires_shard_key() && shard_key.is_some() →
18644        //     validate() fails with
18645        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
18646        //     is the refused declared-but-inert shape on non-Sharded-
18647        //     family arms.
18648        //   * !variant.requires_shard_key() && shard_key.is_none() →
18649        //     validate() passes; the paired shape is the sole
18650        //     non-`requires_shard_key` arm-family accepted shape.
18651        //
18652        // The compile-time-exhaustive `match p.estrategia()` dispatch at
18653        // [`AplicacaoSpec::validate_placement`] preserves its structural
18654        // arm-fan (a future arm addition still surfaces a build-time
18655        // exhaustiveness error there); this pin closes the semantic loop
18656        // between the arm-fan's shape-gate cascades and the substrate-
18657        // canonical predicate every downstream consumer of the paired
18658        // shape reads through. Fail-before-pass-after locally verified by
18659        // mutating the predicate's `Sharded => true` arm to `false` — the
18660        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
18661        // `validate() must pass` assertion; restoring passes. Same "close
18662        // the loop between the typed predicate and the runtime behavior"
18663        // discipline as the sibling
18664        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
18665        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
18666        // per-arm classifier axis.
18667        for variant in [
18668            PlacementStrategy::SingleNode,
18669            PlacementStrategy::Replicated,
18670            PlacementStrategy::Sharded,
18671        ] {
18672            for present in [false, true] {
18673                let mut spec = three_member_spec();
18674                spec.placement.estrategia = variant;
18675                spec.placement.shard_key = present.then(|| "tenantId".into());
18676                let expects_ok = variant.requires_shard_key() == present;
18677                let result = spec.validate();
18678                match (expects_ok, &result) {
18679                    (true, Ok(())) => {}
18680                    (false, Err(err)) => {
18681                        // Cross-check the refusal diagnostic names the
18682                        // right cell of the four-cell shape witness — the
18683                        // `requires_shard_key && !present` cell must trip
18684                        // [`AplicacaoError::ShardedWithoutKey`]; the
18685                        // `!requires_shard_key && present` cell must trip
18686                        // [`AplicacaoError::ShardKeyOnNonSharded`].
18687                        match (variant.requires_shard_key(), present, err) {
18688                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
18689                            (
18690                                false,
18691                                true,
18692                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
18693                            ) => {
18694                                assert_eq!(
18695                                    *e, variant,
18696                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
18697                                     the paired PlacementStrategy",
18698                                );
18699                            }
18700                            _ => panic!(
18701                                "unexpected refusal for estrategia={variant:?} \
18702                                 present={present}: {err:?}"
18703                            ),
18704                        }
18705                    }
18706                    (true, Err(err)) => panic!(
18707                        "validate() must pass for estrategia={variant:?} \
18708                         present={present} (requires_shard_key={} == present={present}), \
18709                         got {err:?}",
18710                        variant.requires_shard_key(),
18711                    ),
18712                    (false, Ok(())) => panic!(
18713                        "validate() must fail for estrategia={variant:?} \
18714                         present={present} (requires_shard_key={} != present={present})",
18715                        variant.requires_shard_key(),
18716                    ),
18717                }
18718            }
18719        }
18720    }
18721
18722    #[test]
18723    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
18724        // Pin the M3 diagnostic template routes through the typed
18725        // [`PlacementStrategy`] Display byte-string (rebound from the
18726        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
18727        // routes emitted identical bytes (the `Debug` derive on a
18728        // unit variant emits the variant name verbatim, exactly what
18729        // `as_str` returns), but the two paths were structurally
18730        // independent — a future `#[serde(rename_all = "…")]`
18731        // attribute or variant rename would coordinate the wire /
18732        // `Display` / `as_str` triple through the lifted const but
18733        // leave the `Debug` route on the compiler-derived variant name,
18734        // silently desynchronizing the diagnostic byte-string from the
18735        // wire byte-string. Rebinding the template onto `Display`
18736        // ties the diagnostic to the same lifted
18737        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
18738        // emits — drift becomes structurally impossible. Pin the
18739        // byte-string here so a future edit that reverts the template
18740        // to `{estrategia:?}` is caught at caixa-core test time, not
18741        // at consumer dispatch time.
18742        for (variant, expected_scalar) in [
18743            (
18744                PlacementStrategy::SingleNode,
18745                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18746            ),
18747            (
18748                PlacementStrategy::Replicated,
18749                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18750            ),
18751            (
18752                PlacementStrategy::Sharded,
18753                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18754            ),
18755        ] {
18756            let err = AplicacaoError::PlacementWithoutClusters {
18757                estrategia: variant,
18758            };
18759            let msg = err.to_string();
18760            assert!(
18761                msg.starts_with(&format!(":placement {expected_scalar} requires")),
18762                "PlacementWithoutClusters diagnostic for {variant:?} must open \
18763                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
18764            );
18765        }
18766    }
18767
18768    #[test]
18769    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
18770        // Peer of
18771        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
18772        // on the second M3 diagnostic that carries the typed
18773        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
18774        // diagnostics now route the strategy scalar through the same
18775        // [`std::fmt::Display`] surface, tying the diagnostic
18776        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
18777        // const set the wire format also emits. The two non-Sharded
18778        // arms are exercised here (the diagnostic exists to flag a
18779        // `:shard-key` slot the current strategy will never consume);
18780        // the peer `Sharded` arm never reaches this diagnostic (the
18781        // `Sharded` strategy consumes `:shard-key` — the
18782        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
18783        // slot instead).
18784        for (variant, expected_scalar) in [
18785            (
18786                PlacementStrategy::SingleNode,
18787                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18788            ),
18789            (
18790                PlacementStrategy::Replicated,
18791                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18792            ),
18793        ] {
18794            let err = AplicacaoError::ShardKeyOnNonSharded {
18795                estrategia: variant,
18796                shard_key: "$tenantId".into(),
18797            };
18798            let msg = err.to_string();
18799            assert!(
18800                msg.starts_with(&format!(":placement {expected_scalar} carries")),
18801                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
18802                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
18803            );
18804        }
18805    }
18806
18807    #[test]
18808    fn placement_strategy_all_enumerates_every_variant_once() {
18809        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
18810        // exhaustive-iteration surface: every variant appears exactly
18811        // once, and the slice length matches the arm count of the
18812        // closed set. Every consumer that walks the accepted-strategy
18813        // set (a future `feira app placement --list` CLI-side surfacing,
18814        // a future M4 admission-webhook's rejection body naming the
18815        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
18816        // reverse-projection consumers that iterate the accept-set for
18817        // a "did you mean" hint) reads through this slice, so a future
18818        // variant addition (an `Anycast` mesh-anycast arm the
18819        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
18820        // grows the enum but forgets to grow [`Self::ALL`] silently
18821        // truncates every downstream consumer's accept-set at the same
18822        // pre-addition boundary — this pin fails at caixa-core build
18823        // time on the pairwise-distinct + arm-count invariants.
18824        //
18825        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
18826        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
18827        // pins on the peer closed-set typed-enum axes.
18828        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
18829        assert_eq!(
18830            all.len(),
18831            3,
18832            "PlacementStrategy::ALL must enumerate every variant of the \
18833             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
18834        );
18835        for (i, a) in all.iter().enumerate() {
18836            for (j, b) in all.iter().enumerate() {
18837                if i != j {
18838                    assert_ne!(
18839                        a, b,
18840                        "PlacementStrategy::ALL must carry every variant exactly \
18841                         once — got duplicate {a:?} at indices {i} and {j}"
18842                    );
18843                }
18844            }
18845        }
18846        for variant in [
18847            PlacementStrategy::SingleNode,
18848            PlacementStrategy::Replicated,
18849            PlacementStrategy::Sharded,
18850        ] {
18851            assert!(
18852                all.contains(&variant),
18853                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
18854                 addition that grows the enum but forgets to grow the ALL slice \
18855                 silently truncates every downstream consumer's accept-set at the \
18856                 pre-addition boundary"
18857            );
18858        }
18859    }
18860
18861    #[test]
18862    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
18863        // Fail-before-pass-after pin on the forward accept-set of the
18864        // [`PlacementStrategy::from_wire`] reverse projection: every
18865        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
18866        // constant the [`PlacementStrategy::as_str`] emitter walks
18867        // parses back to its paired variant. Any future arm addition
18868        // that grows the emitter's `as_str` match but forgets to grow
18869        // the parser's `from_str` match silently splits the two halves
18870        // of the round-trip — the wire byte-string one non-serde
18871        // consumer parses from the one the emitter wrote — with the
18872        // failure surfacing at parse time far from the rebrand commit.
18873        // Pinning the three-arm accept-set here catches the drift at
18874        // caixa-core build time.
18875        //
18876        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
18877        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
18878        // closed-set typed-enum `str → Self` axes.
18879        for (wire, expected) in [
18880            (
18881                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18882                PlacementStrategy::SingleNode,
18883            ),
18884            (
18885                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18886                PlacementStrategy::Replicated,
18887            ),
18888            (
18889                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18890                PlacementStrategy::Sharded,
18891            ),
18892        ] {
18893            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
18894                panic!(
18895                    "PlacementStrategy::from_wire({wire:?}) must accept every \
18896                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
18897                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
18898                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
18899                )
18900            });
18901            assert_eq!(
18902                parsed, expected,
18903                "PlacementStrategy::from_wire({wire:?}) must return \
18904                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
18905            );
18906        }
18907    }
18908
18909    #[test]
18910    fn placement_strategy_from_wire_round_trips_through_as_str() {
18911        // Fail-before-pass-after pin on the closed round-trip between
18912        // the forward [`PlacementStrategy::as_str`] emitter and the
18913        // reverse [`PlacementStrategy::from_wire`] parser: for every
18914        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
18915        // output must return exactly the same variant. Any per-arm
18916        // divergence — a future arm added to `as_str` but not
18917        // `from_str`, an accidental copy-paste flip in one but not the
18918        // other — silently splits the emit and parse halves and the
18919        // failure surfaces at consumer parse time far from the drift
18920        // site. The `ALL`-iterating shape means a future variant
18921        // addition picks up the coverage by construction.
18922        //
18923        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
18924        // [`crate::CaixaKind::from_wire`] and the
18925        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
18926        // sibling round-trip pin on [`RateLimitUnit`].
18927        for &variant in PlacementStrategy::ALL {
18928            let wire = variant.as_str();
18929            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
18930                panic!(
18931                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
18932                     must be Some({variant:?}) — the two halves of the round-trip \
18933                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
18934                     got None on wire byte-string {wire:?}"
18935                )
18936            });
18937            assert_eq!(
18938                parsed, variant,
18939                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
18940                 must round-trip to the same variant; got {parsed:?}"
18941            );
18942        }
18943    }
18944
18945    #[test]
18946    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
18947        // Fail-before-pass-after pin on the closed-set refusal
18948        // discipline of [`PlacementStrategy::from_wire`]: every
18949        // byte-string outside the three-arm accept-set returns `None`
18950        // rather than silently collapsing onto the [`Default`]
18951        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
18952        // exercised here sweeps the load-bearing drift shapes: the
18953        // empty string (a stripped serde-attribute drift), an all-
18954        // whitespace string (the canonical text-editor accidental
18955        // padding shape), the lowercased kebab-case forms a future
18956        // `#[serde(rename_all = "kebab-case")]` attribute would emit
18957        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
18958        // coincidentally match the accepted canonical scalars, so only
18959        // `"single-node"` fires as a refusal, but pinning the case-
18960        // sensitivity of the accepted arms via the peer [`SingleNode`]
18961        // assertion in the round-trip pin makes the discipline
18962        // structurally clear), the lowercased single-word forms
18963        // (`"singlenode"`), the padded canonical scalar
18964        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
18965        // (`"Sharded\n"`), and a pointer-different `&'static str` that
18966        // happens to alias a canonical byte-string by content but not
18967        // by identity (validated implicitly by the emitter's routing
18968        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
18969        // identity a paired [`crate::assert_str_reexport_identity`] pin
18970        // in caixa-core's per-const declaration surface would catch).
18971        //
18972        // Peer of the sibling
18973        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
18974        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
18975        for bad in [
18976            "",
18977            " ",
18978            "\n",
18979            "\t",
18980            "single-node",
18981            "singlenode",
18982            "SingleNodes",
18983            "single_node",
18984            "single node",
18985            "SINGLENODE",
18986            "SingleNode ",
18987            " SingleNode",
18988            " Sharded ",
18989            "Sharded\n",
18990            "replicated ",
18991            "sharded",
18992            "REPLICATED",
18993            "Anycast",
18994            "Global",
18995            "?",
18996        ] {
18997            assert!(
18998                PlacementStrategy::from_wire(bad).is_none(),
18999                "PlacementStrategy::from_wire({bad:?}) must return None — the \
19000                 parser's accept-set is exactly the three PlacementStrategy::as_str \
19001                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
19002                 is outside that closed set"
19003            );
19004        }
19005    }
19006
19007    #[test]
19008    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
19009        // Fail-before-pass-after pin on the third path of the four-path
19010        // convergence: `from_str` (the reverse projection) inverts the
19011        // `Serialize` derive's wire byte-string on every variant.
19012        // Together with the pre-existing three-path convergence
19013        // (`Display` + `as_str` + `Serialize` all resolve to the same
19014        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
19015        // the peer
19016        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
19017        // this closes the round-trip: the wire byte-string the
19018        // `Serialize` derive emits parses back to the same variant
19019        // through `from_str`, so any future serde-attribute or variant-
19020        // rename drift on the emit half now surfaces as a matched drift
19021        // on the parse half at caixa-core build time — the two halves
19022        // migrate as a unit through the lifted consts on any future
19023        // rename, and the round-trip cannot silently split.
19024        //
19025        // Peer of the sibling
19026        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
19027        // wire-format pin — extends the three-path convergence
19028        // (`Display` + `as_str` + `Serialize`) onto the fourth path
19029        // (`from_str`), closing the `str ↔ Self` round-trip on the
19030        // M3 `:placement :estrategia` closed-set axis.
19031        for &variant in PlacementStrategy::ALL {
19032            let wire = serde_json::to_string(&variant).unwrap();
19033            let unquoted = wire
19034                .strip_prefix('"')
19035                .and_then(|s| s.strip_suffix('"'))
19036                .expect("serialized PlacementStrategy is a JSON string");
19037            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
19038                panic!(
19039                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
19040                     Serialize derive's wire byte-string for \
19041                     PlacementStrategy::{variant:?} — the four-path convergence \
19042                     (Display + as_str + Serialize + from_str) resolves through \
19043                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
19044                )
19045            });
19046            assert_eq!(
19047                parsed, variant,
19048                "PlacementStrategy::from_wire of the Serialize derive's wire \
19049                 byte-string for PlacementStrategy::{variant:?} must round-trip \
19050                 to the same variant; got {parsed:?}"
19051            );
19052        }
19053    }
19054
19055    #[test]
19056    fn rejects_zero_policy_timeout() {
19057        let mut s = three_member_spec();
19058        s.politicas.timeout = Some(Duration::ZERO);
19059        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
19060    }
19061
19062    #[test]
19063    fn rejects_zero_policy_retries() {
19064        let mut s = three_member_spec();
19065        s.politicas.retries = Some(0);
19066        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
19067    }
19068
19069    #[test]
19070    fn rejects_policy_retries_above_cap() {
19071        // The fail-before-pass-after pin: `Some(11)` is structurally
19072        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
19073        // passed validate on every pre-gate codebase because the
19074        // typed slot's only check was the zero-floor arm. The
19075        // thundering-herd amplification vector only surfaced at the
19076        // runtime substrate (Envoy / Cilium L7 retry overlay)
19077        // far from the source caixa.lisp with no field naming the
19078        // offending policy.
19079        let mut s = three_member_spec();
19080        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
19081        assert_eq!(
19082            s.validate().unwrap_err(),
19083            AplicacaoError::PolicyRetriesExceedsCap {
19084                retries: POLICY_RETRIES_MAX + 1
19085            }
19086        );
19087    }
19088
19089    #[test]
19090    fn rejects_policy_retries_far_above_cap() {
19091        // The `u32::MAX` worst case — the four-billion-retry policy
19092        // a typo (`(:retries 4294967295)`) or struct-literal
19093        // copy-paste lands in the slot. Pin the cap arm's coverage
19094        // explicitly across the full `u32` overflow so a future
19095        // relaxation that drops the upper bound surfaces here.
19096        let mut s = three_member_spec();
19097        s.politicas.retries = Some(u32::MAX);
19098        assert_eq!(
19099            s.validate().unwrap_err(),
19100            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
19101        );
19102    }
19103
19104    #[test]
19105    fn accepts_policy_retries_at_cap() {
19106        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
19107        // must validate. The cap is inclusive on the top edge,
19108        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
19109        // discipline on the sibling [`crate::LimitsSpec::memory`]
19110        // axis. Pin the boundary explicitly so a future off-by-one
19111        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
19112        // surfaces here as a test failure rather than a silent
19113        // contract narrowing.
19114        let mut s = three_member_spec();
19115        s.politicas.retries = Some(POLICY_RETRIES_MAX);
19116        s.validate()
19117            .expect("retries == POLICY_RETRIES_MAX must validate");
19118    }
19119
19120    #[test]
19121    fn accepts_policy_retries_typical_values() {
19122        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
19123        // every value in the validated set must pass. The
19124        // Envoy / Istio production-playbook recommendation band
19125        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
19126        // (`maxRetries ≤ 10`) both lie within this set.
19127        for r in 1..=POLICY_RETRIES_MAX {
19128            let mut s = three_member_spec();
19129            s.politicas.retries = Some(r);
19130            s.validate()
19131                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
19132        }
19133    }
19134
19135    #[test]
19136    fn policy_retries_zero_takes_precedence_over_cap() {
19137        // The cross-arm ordering pin: `Some(0)` is structurally
19138        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
19139        // (cap), but the zero-floor diagnostic is the more
19140        // self-locating one (it directly names the omit-axis
19141        // remediation), so the validate gate must fire on zero
19142        // first. Pin the order so a future refactor that reorders
19143        // the arms surfaces here as a test failure rather than a
19144        // silent diagnostic regression. Same shape every other
19145        // zero-then-shape ordering on this surface uses
19146        // ([`AplicacaoError::PolicyTimeoutZero`] then
19147        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
19148        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
19149        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
19150        let mut s = three_member_spec();
19151        s.politicas.retries = Some(0);
19152        assert_eq!(
19153            s.validate().unwrap_err(),
19154            AplicacaoError::PolicyRetriesZero,
19155            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
19156        );
19157    }
19158
19159    #[test]
19160    fn policy_retries_cap_diagnostic_carries_offending_value() {
19161        // The diagnostic-shape pin: the offending `u32` is carried
19162        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
19163        // variant so the surfaced error message names the value the
19164        // author wrote (`":politicas :retries (47) exceeds the
19165        // mesh-policy ceiling …"`), not just the cap. Same
19166        // self-locating diagnostic shape every other typed-cap arm
19167        // on this surface carries
19168        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
19169        // offending byte count verbatim).
19170        let mut s = three_member_spec();
19171        s.politicas.retries = Some(47);
19172        let err = s.validate().unwrap_err();
19173        assert!(
19174            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
19175            "got {err:?}"
19176        );
19177        let msg = err.to_string();
19178        assert!(
19179            msg.contains("47"),
19180            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
19181        );
19182    }
19183
19184    #[test]
19185    fn policy_retries_cap_is_aws_app_mesh_aligned() {
19186        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
19187        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
19188        // schema cap — the only upstream mesh-policy schema that
19189        // documents an explicit hard cap. Pinning the literal value
19190        // here surfaces a future drift (a relaxation to 20, a
19191        // tightening to 5) as a deliberate test edit, not a silent
19192        // contract narrowing.
19193        assert_eq!(POLICY_RETRIES_MAX, 10);
19194    }
19195
19196    #[test]
19197    fn rejects_circuit_breaker_zero_max_failures() {
19198        let mut s = three_member_spec();
19199        s.politicas.circuit_breaker = Some(CircuitBreaker {
19200            max_failures: 0,
19201            window: Duration::from_secs(60),
19202        });
19203        assert_eq!(
19204            s.validate().unwrap_err(),
19205            AplicacaoError::PolicyBreakerZeroFailures
19206        );
19207    }
19208
19209    #[test]
19210    fn rejects_circuit_breaker_max_failures_above_cap() {
19211        // The fail-before-pass-after pin: `1001` is structurally one
19212        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
19213        // silently passed validate on every pre-gate codebase
19214        // because the typed slot's only check was the zero-floor
19215        // arm. The breaker-no-op vector only surfaced at the runtime
19216        // substrate (Envoy / Cilium L7 outlier-detection overlay)
19217        // far from the source caixa.lisp with no field naming the
19218        // offending policy.
19219        let mut s = three_member_spec();
19220        s.politicas.circuit_breaker = Some(CircuitBreaker {
19221            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19222            window: Duration::from_secs(60),
19223        });
19224        assert_eq!(
19225            s.validate().unwrap_err(),
19226            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19227                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19228            }
19229        );
19230    }
19231
19232    #[test]
19233    fn rejects_circuit_breaker_max_failures_far_above_cap() {
19234        // The `u32::MAX` worst case — the four-billion-failure
19235        // threshold a typo (`(:max-failures 4294967295)`) or a
19236        // struct-literal copy-paste lands in the slot. Pin the cap
19237        // arm's coverage explicitly across the full `u32` overflow
19238        // so a future relaxation that drops the upper bound surfaces
19239        // here.
19240        let mut s = three_member_spec();
19241        s.politicas.circuit_breaker = Some(CircuitBreaker {
19242            max_failures: u32::MAX,
19243            window: Duration::from_secs(60),
19244        });
19245        assert_eq!(
19246            s.validate().unwrap_err(),
19247            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19248                max_failures: u32::MAX,
19249            }
19250        );
19251    }
19252
19253    #[test]
19254    fn accepts_circuit_breaker_max_failures_at_cap() {
19255        // The boundary value — exactly
19256        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
19257        // cap is inclusive on the top edge, matching the
19258        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
19259        // discipline on the sibling capped axes. Pin the boundary
19260        // explicitly so a future off-by-one tightening
19261        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
19262        // surfaces here as a test failure rather than a silent
19263        // contract narrowing.
19264        let mut s = three_member_spec();
19265        s.politicas.circuit_breaker = Some(CircuitBreaker {
19266            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
19267            window: Duration::from_secs(60),
19268        });
19269        s.validate()
19270            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
19271    }
19272
19273    #[test]
19274    fn accepts_circuit_breaker_max_failures_typical_values() {
19275        // The documented production-playbook band positive-control
19276        // sweep — every value Hystrix / Istio / Envoy / Polly /
19277        // Resilience4j recommend (5..=50) must pass, plus a sweep
19278        // through the hyperscale band (100, 500, 1000) the cap
19279        // accepts. Pin the inclusive validated set explicitly so a
19280        // future tightening of the ceiling surfaces here.
19281        //
19282        // Clears the fixture's `:retries` (which is `Some(3)`) so this
19283        // per-axis sweep is pure: the sibling cross-axis
19284        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
19285        // gate rejects any `max_failures <= retries` pair, so the
19286        // `max_failures = 1` boundary at the head of the sweep would
19287        // otherwise trip on the fixture-inherited retry policy rather
19288        // than the per-axis boundary this test names. Same discipline
19289        // the sibling per-axis `accepts_circuit_breaker_window_*`
19290        // sweeps take against the fixture's `:timeout` for the
19291        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
19292        // cross-axis arm.
19293        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
19294            let mut s = three_member_spec();
19295            s.politicas.retries = None;
19296            s.politicas.circuit_breaker = Some(CircuitBreaker {
19297                max_failures: n,
19298                window: Duration::from_secs(60),
19299            });
19300            s.validate()
19301                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
19302        }
19303    }
19304
19305    #[test]
19306    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
19307        // The cross-arm ordering pin: `0` is structurally outside
19308        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
19309        // (cap), but the zero-floor diagnostic is the more
19310        // self-locating one (it directly names the omit-axis
19311        // remediation), so the validate gate must fire on zero
19312        // first. Same shape every other zero-then-shape ordering on
19313        // this surface uses
19314        // ([`AplicacaoError::PolicyRetriesZero`] then
19315        // [`AplicacaoError::PolicyRetriesExceedsCap`];
19316        // [`AplicacaoError::PolicyTimeoutZero`] then
19317        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
19318        let mut s = three_member_spec();
19319        s.politicas.circuit_breaker = Some(CircuitBreaker {
19320            max_failures: 0,
19321            window: Duration::from_secs(60),
19322        });
19323        assert_eq!(
19324            s.validate().unwrap_err(),
19325            AplicacaoError::PolicyBreakerZeroFailures,
19326            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
19327        );
19328    }
19329
19330    #[test]
19331    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
19332        // The cross-arm ordering pin between the cap and the
19333        // sibling `:window` gates (zero-window, canonical-window).
19334        // A breaker carrying both an over-cap `max_failures` AND a
19335        // structurally invalid window (zero, sub-ms) must surface
19336        // the cap diagnostic first — the cap arm is wired
19337        // immediately after the zero-failure arm and strictly
19338        // before the window arms, so the offending value the
19339        // diagnostic names matches the order the author would
19340        // discover the gates by reading top-to-bottom through
19341        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
19342        // future refactor that reorders the arms surfaces here as a
19343        // test failure rather than a silent diagnostic regression.
19344        let mut s = three_member_spec();
19345        s.politicas.circuit_breaker = Some(CircuitBreaker {
19346            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19347            window: Duration::ZERO,
19348        });
19349        assert_eq!(
19350            s.validate().unwrap_err(),
19351            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19352                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19353            },
19354            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
19355        );
19356    }
19357
19358    #[test]
19359    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
19360        // The diagnostic-shape pin: the offending `u32` is carried
19361        // verbatim into the
19362        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
19363        // variant so the surfaced error message names the value the
19364        // author wrote (`":politicas :circuit-breaker :max-failures
19365        // (50000) exceeds the mesh-policy ceiling …"`), not just
19366        // the cap. Same self-locating diagnostic shape every other
19367        // typed-cap arm on this surface carries
19368        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
19369        // offending retry count verbatim,
19370        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
19371        // offending byte count verbatim).
19372        let mut s = three_member_spec();
19373        s.politicas.circuit_breaker = Some(CircuitBreaker {
19374            max_failures: 50_000,
19375            window: Duration::from_secs(60),
19376        });
19377        let err = s.validate().unwrap_err();
19378        assert!(
19379            matches!(
19380                err,
19381                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19382                    max_failures: 50_000
19383                }
19384            ),
19385            "got {err:?}"
19386        );
19387        let msg = err.to_string();
19388        assert!(
19389            msg.contains("50000"),
19390            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
19391        );
19392    }
19393
19394    #[test]
19395    fn policy_breaker_max_failures_cap_pins_canonical_value() {
19396        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
19397        // value at 1000 — an order of magnitude above every
19398        // documented production-playbook recommendation band
19399        // (Hystrix `requestVolumeThreshold` default 20, Istio
19400        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
19401        // `outlier_detection.consecutive_5xx` default 5, Polly /
19402        // Resilience4j typical 5..=50) and below the
19403        // clearly-pathological "effectively no protection" floor
19404        // (10_000, 100_000, u32::MAX). Pinning the literal value
19405        // here surfaces a future drift (a relaxation to 10_000, a
19406        // tightening to 100) as a deliberate test edit, not a
19407        // silent contract narrowing.
19408        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
19409    }
19410
19411    #[test]
19412    fn rejects_circuit_breaker_zero_window() {
19413        let mut s = three_member_spec();
19414        s.politicas.circuit_breaker = Some(CircuitBreaker {
19415            max_failures: 5,
19416            window: Duration::ZERO,
19417        });
19418        assert_eq!(
19419            s.validate().unwrap_err(),
19420            AplicacaoError::PolicyBreakerZeroWindow
19421        );
19422    }
19423
19424    #[test]
19425    fn rejects_zero_rate_limit() {
19426        let mut s = three_member_spec();
19427        s.politicas.rate_limit = Some(RateLimit {
19428            rate: 0,
19429            window: Duration::from_secs(1),
19430        });
19431        assert_eq!(
19432            s.validate().unwrap_err(),
19433            AplicacaoError::PolicyRateLimitZero
19434        );
19435    }
19436
19437    #[test]
19438    fn rejects_rate_limit_zero_window() {
19439        // `RateLimit { rate: 100, window: Duration::ZERO }` is
19440        // constructible programmatically (the typed `Duration` field
19441        // imposes no nonzero invariant) but renders through
19442        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
19443        // codec's `parse` rejects as `unknown rate-limit window unit
19444        // "0s"`. Until this validate-time gate landed the typed slot
19445        // accepted the value silently and the round-trip break only
19446        // surfaced at deserialize time (potentially in a downstream
19447        // consumer that never re-validates). Pin the rejection at
19448        // `AplicacaoSpec::validate` so the typed slot's valid set
19449        // matches the codec's round-trippable set structurally.
19450        let mut s = three_member_spec();
19451        s.politicas.rate_limit = Some(RateLimit {
19452            rate: 100,
19453            window: Duration::ZERO,
19454        });
19455        assert_eq!(
19456            s.validate().unwrap_err(),
19457            AplicacaoError::PolicyRateLimitWindowNotCanonical {
19458                window: Duration::ZERO
19459            }
19460        );
19461    }
19462
19463    #[test]
19464    fn rejects_rate_limit_arbitrary_seconds_window() {
19465        // 45 seconds is a valid `Duration` but not one of the three
19466        // canonical rate-limit windows the codec round-trips
19467        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
19468        // refuses on round-trip — same round-trip-break shape the
19469        // zero-window arm above pins, with a non-zero magnitude to
19470        // guard against a future "reject only zero" half-measure.
19471        let mut s = three_member_spec();
19472        let window = Duration::from_secs(45);
19473        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
19474        assert_eq!(
19475            s.validate().unwrap_err(),
19476            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19477        );
19478    }
19479
19480    #[test]
19481    fn rejects_rate_limit_two_minute_window() {
19482        // 120 seconds = 2 minutes is a "looks-canonical" but
19483        // not-canonical window: it's a clean integer multiple of the
19484        // minute unit, but the codec only round-trips the
19485        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
19486        // A `Duration::from_secs(120)` window renders as `"100/120s"`
19487        // which the parser rejects. Pinning this case rules out a
19488        // future "accept any clean multiple of s/m/h" relaxation
19489        // that would silently break the codec contract.
19490        let mut s = three_member_spec();
19491        let window = Duration::from_secs(120);
19492        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
19493        assert_eq!(
19494            s.validate().unwrap_err(),
19495            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19496        );
19497    }
19498
19499    #[test]
19500    fn rejects_rate_limit_subsecond_window() {
19501        // A sub-second window (e.g. 500ms) is a valid `Duration` but
19502        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
19503        // Pin the rejection so a future relaxation can't silently
19504        // admit fractional-second windows that the codec can't
19505        // round-trip.
19506        let mut s = three_member_spec();
19507        let window = Duration::from_millis(500);
19508        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
19509        assert_eq!(
19510            s.validate().unwrap_err(),
19511            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
19512        );
19513    }
19514
19515    #[test]
19516    fn rejects_policy_rate_limit_above_cap() {
19517        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
19518        // is structurally one past the cap and silently passed
19519        // validate on every pre-gate codebase because the typed slot's
19520        // only `rate` check was the zero-floor arm. The no-op-limiter
19521        // shape only surfaced at the runtime substrate (Envoy's
19522        // `local_rate_limit.token_bucket.max_tokens`, the future
19523        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
19524        // with no field naming the offending policy.
19525        let mut s = three_member_spec();
19526        s.politicas.rate_limit = Some(RateLimit {
19527            rate: POLICY_RATE_LIMIT_MAX + 1,
19528            window: Duration::from_secs(1),
19529        });
19530        assert_eq!(
19531            s.validate().unwrap_err(),
19532            AplicacaoError::PolicyRateLimitExceedsCap {
19533                rate: POLICY_RATE_LIMIT_MAX + 1
19534            }
19535        );
19536    }
19537
19538    #[test]
19539    fn rejects_policy_rate_limit_far_above_cap() {
19540        // The `u32::MAX` worst case — the four-billion-token rate-limit
19541        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
19542        // copy-paste lands in the slot. Pin the cap arm's coverage
19543        // explicitly across the full `u32` overflow so a future
19544        // relaxation that drops the upper bound surfaces here. Peer to
19545        // `rejects_policy_retries_far_above_cap` on the sibling
19546        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
19547        // on the sibling `:max-failures` axis.
19548        let mut s = three_member_spec();
19549        s.politicas.rate_limit = Some(RateLimit {
19550            rate: u32::MAX,
19551            window: Duration::from_secs(1),
19552        });
19553        assert_eq!(
19554            s.validate().unwrap_err(),
19555            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
19556        );
19557    }
19558
19559    #[test]
19560    fn accepts_policy_rate_limit_at_cap() {
19561        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
19562        // must validate. The cap is inclusive on the top edge, matching
19563        // every other typed upper bound in this crate
19564        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
19565        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
19566        // across all three canonical windows so a future off-by-one
19567        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
19568        // window-conditional cap surfaces here as a test failure rather
19569        // than a silent contract narrowing.
19570        for secs in [1u64, 60, 3600] {
19571            let mut s = three_member_spec();
19572            s.politicas.rate_limit = Some(RateLimit {
19573                rate: POLICY_RATE_LIMIT_MAX,
19574                window: Duration::from_secs(secs),
19575            });
19576            s.validate().unwrap_or_else(|e| {
19577                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
19578            });
19579        }
19580    }
19581
19582    #[test]
19583    fn accepts_policy_rate_limit_typical_values() {
19584        // The documented production-playbook recommendation band —
19585        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
19586        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
19587        // Enterprise ~1M per-hour. Every value in the validated set
19588        // must pass; pin the band explicitly so a future tightening
19589        // surfaces here.
19590        //
19591        // Clears the fixture's `:retries` (which is `Some(3)`) so this
19592        // per-axis sweep is pure: the sibling cross-axis
19593        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
19594        // rejects any `rate <= retries` pair, so the `rate = 1`
19595        // boundary at the head of the sweep would otherwise trip on the
19596        // fixture-inherited retry policy rather than the per-axis
19597        // boundary this test names. Same discipline the sibling per-axis
19598        // `accepts_circuit_breaker_max_failures_typical_values` sweep
19599        // takes against the fixture's `:retries` for the peer cross-axis
19600        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
19601        // arm.
19602        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
19603            for secs in [1u64, 60, 3600] {
19604                let mut s = three_member_spec();
19605                s.politicas.retries = None;
19606                s.politicas.rate_limit = Some(RateLimit {
19607                    rate,
19608                    window: Duration::from_secs(secs),
19609                });
19610                s.validate().unwrap_or_else(|e| {
19611                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
19612                });
19613            }
19614        }
19615    }
19616
19617    #[test]
19618    fn policy_rate_limit_zero_takes_precedence_over_cap() {
19619        // The cross-arm ordering pin: `rate == 0` is structurally
19620        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
19621        // (cap), but the zero-floor diagnostic is the more
19622        // self-locating one (it directly names the omit-axis
19623        // remediation). Pin the order so a future refactor that
19624        // reorders the arms surfaces here as a test failure rather
19625        // than a silent diagnostic regression. Same shape every other
19626        // zero-then-cap ordering on this surface uses
19627        // ([`AplicacaoError::PolicyRetriesZero`] then
19628        // [`AplicacaoError::PolicyRetriesExceedsCap`];
19629        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
19630        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
19631        let mut s = three_member_spec();
19632        s.politicas.rate_limit = Some(RateLimit {
19633            rate: 0,
19634            window: Duration::from_secs(1),
19635        });
19636        assert_eq!(
19637            s.validate().unwrap_err(),
19638            AplicacaoError::PolicyRateLimitZero,
19639            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
19640        );
19641    }
19642
19643    #[test]
19644    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
19645        // Two-axis-bad pin: rate above cap *and* window non-canonical.
19646        // The validate gate must fire on the rate cap first — the
19647        // amplification-shape (no-op limiter) diagnostic is the more
19648        // fundamental one; the window-canonical diagnostic is the
19649        // narrower codec-round-trip shape. Pin the ordering so a future
19650        // refactor that reorders the rate-then-window check arms
19651        // surfaces here as a test failure rather than a silent
19652        // diagnostic regression.
19653        let mut s = three_member_spec();
19654        s.politicas.rate_limit = Some(RateLimit {
19655            rate: POLICY_RATE_LIMIT_MAX + 1,
19656            window: Duration::from_secs(45),
19657        });
19658        assert_eq!(
19659            s.validate().unwrap_err(),
19660            AplicacaoError::PolicyRateLimitExceedsCap {
19661                rate: POLICY_RATE_LIMIT_MAX + 1
19662            },
19663            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
19664        );
19665    }
19666
19667    #[test]
19668    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
19669        // The diagnostic-shape pin: the offending `u32` is carried
19670        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
19671        // variant so the surfaced error message names the value the
19672        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
19673        // the mesh-policy ceiling …"`), not just the cap. Same
19674        // self-locating diagnostic shape every other typed-cap arm on
19675        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
19676        // carries the offending retries count verbatim,
19677        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
19678        // the offending failure count verbatim).
19679        let mut s = three_member_spec();
19680        s.politicas.rate_limit = Some(RateLimit {
19681            rate: 5_000_000,
19682            window: Duration::from_secs(1),
19683        });
19684        let err = s.validate().unwrap_err();
19685        assert!(
19686            matches!(
19687                err,
19688                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
19689            ),
19690            "got {err:?}"
19691        );
19692        let msg = err.to_string();
19693        assert!(
19694            msg.contains("5000000"),
19695            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
19696        );
19697    }
19698
19699    #[test]
19700    fn policy_rate_limit_cap_pins_canonical_value() {
19701        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
19702        // 1_000_000 — two-to-three orders of magnitude above every
19703        // documented production-playbook recommendation band (Envoy /
19704        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
19705        // Gateway 10_000..=100_000 per-minute) and below the
19706        // clearly-pathological "paste-from-binary blob" floor
19707        // (100_000_000, u32::MAX). Pinning the literal value here
19708        // surfaces a future drift (a relaxation to 10_000_000, a
19709        // tightening to 100_000) as a deliberate test edit, not a
19710        // silent contract narrowing.
19711        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
19712    }
19713
19714    #[test]
19715    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
19716        // Both axes are invalid here: rate == 0 *and* window is
19717        // non-canonical. The validate gate must fire on rate first
19718        // (matching the existing `rejects_zero_rate_limit` ordering),
19719        // so the existing diagnostic continues to lead with the
19720        // simpler "zero rate" framing. Pinning the order of checks
19721        // so a future refactor that reorders the arms surfaces here
19722        // as a test failure rather than a silent diagnostic
19723        // regression.
19724        let mut s = three_member_spec();
19725        s.politicas.rate_limit = Some(RateLimit {
19726            rate: 0,
19727            window: Duration::from_secs(45),
19728        });
19729        assert_eq!(
19730            s.validate().unwrap_err(),
19731            AplicacaoError::PolicyRateLimitZero
19732        );
19733    }
19734
19735    #[test]
19736    fn rate_limit_canonical_windows_validate() {
19737        // The three canonical windows the codec round-trips
19738        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
19739        // unchanged. Pin the full canonical set as a positive case
19740        // (the existing `rate_limit_round_trip_seconds` /
19741        // `rate_limit_round_trip_minutes` tests pin the
19742        // serialize-then-deserialize property at the codec layer; this
19743        // test pins the validate-side complement so a future tightening
19744        // of the canonical set — e.g. dropping `:hour` — surfaces here
19745        // as a test failure rather than a silent contract narrowing).
19746        for secs in [1u64, 60, 3600] {
19747            let mut s = three_member_spec();
19748            s.politicas.rate_limit = Some(RateLimit {
19749                rate: 100,
19750                window: Duration::from_secs(secs),
19751            });
19752            s.validate().expect("canonical window must validate");
19753        }
19754    }
19755
19756    #[test]
19757    fn rate_limit_validated_value_round_trips_through_codec() {
19758        // The structural property the validate gate enforces:
19759        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
19760        // losslessly through the `rate_limit_codec` (serialize → string
19761        // → deserialize → equal value). Pin this end-to-end so a future
19762        // change to either side (the validate gate's accepted window
19763        // set, the codec's parse/render unit set) that breaks the
19764        // alignment surfaces here. The previous-state shape (typed
19765        // slot accepts arbitrary `Duration`, codec only round-trips
19766        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
19767        // window — the validate gate now forecloses that.
19768        for secs in [1u64, 60, 3600] {
19769            let mut s = three_member_spec();
19770            s.politicas.rate_limit = Some(RateLimit {
19771                rate: 250,
19772                window: Duration::from_secs(secs),
19773            });
19774            s.validate().unwrap();
19775            let json = serde_json::to_string(&s.politicas).unwrap();
19776            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19777            assert_eq!(
19778                back.rate_limit, s.politicas.rate_limit,
19779                "every validated :rate-limit must round-trip losslessly through the codec"
19780            );
19781        }
19782    }
19783
19784    #[test]
19785    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
19786        // The hour-window canonical form (`"<n>/h"`) was missing from
19787        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
19788        // pair. Now that the validate gate pins 3600s as part of the
19789        // canonical set, pin its serialize-side render shape too so
19790        // the third leg of the s/m/h tripod is explicitly tested.
19791        let policy = MeshPolicy {
19792            rate_limit: Some(RateLimit {
19793                rate: 10000,
19794                window: Duration::from_secs(3600),
19795            }),
19796            ..Default::default()
19797        };
19798        let json = serde_json::to_string(&policy).unwrap();
19799        assert!(
19800            json.contains("\"10000/h\""),
19801            "hour-window canonical form must render with `h` suffix (got: {json})"
19802        );
19803        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19804        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
19805    }
19806
19807    #[test]
19808    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
19809        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
19810        // typed accessor's accepted-window set against the codec's
19811        // accepted set explicitly. A future addition to the codec
19812        // (e.g. accepting `:day`/`:week` as authoring units) must be
19813        // accompanied by a parallel addition here, and a regression
19814        // that drops one of the three canonical units from either
19815        // side surfaces as a test failure. The accessor is the
19816        // single source of truth for the canonical-window set —
19817        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
19818        // gate and [`rate_limit_codec::render`]'s canonical arm both
19819        // read through it — this test enshrines that its
19820        // `Duration → Option<RateLimitUnit>` projection matches the
19821        // codec's parse / render arms' accepted-window set exactly.
19822        //
19823        // Predecessor: this pin previously read the module-private
19824        // free helper `is_canonical_rate_limit_window` — a delegate
19825        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
19826        // — but the helper had no production consumers left after the
19827        // validate-gate migration onto [`RateLimit::canonical_unit`]
19828        // and was deleted; the closed-set arm-window bijection now
19829        // lives on exactly one typed dispatch on the substrate
19830        // primitive.
19831        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
19832            RateLimit { rate: 1, window }.canonical_unit()
19833        };
19834        assert!(canonical_unit(Duration::from_secs(1)).is_some());
19835        assert!(canonical_unit(Duration::from_secs(60)).is_some());
19836        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
19837        // Non-canonical windows the accessor rejects.
19838        assert!(canonical_unit(Duration::ZERO).is_none());
19839        assert!(canonical_unit(Duration::from_secs(2)).is_none());
19840        assert!(canonical_unit(Duration::from_secs(30)).is_none());
19841        assert!(canonical_unit(Duration::from_secs(120)).is_none());
19842        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
19843        // Sub-second windows: even `Duration::from_millis(1000)` is
19844        // exactly 1s and accepted; `Duration::from_millis(500)` is
19845        // sub-second and rejected.
19846        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
19847        assert!(canonical_unit(Duration::from_millis(500)).is_none());
19848        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
19849    }
19850
19851    #[test]
19852    fn rate_limit_unit_table_projections_are_mutual_inverses() {
19853        // Bidirection pin against the closed-set typed enum
19854        // [`RateLimitUnit`] arm-table (the canonical
19855        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
19856        // of the rate-limit unit surface reads from). The two
19857        // projection directions [`RateLimitUnit::from_suffix`] /
19858        // [`RateLimitUnit::window`] (str → Duration, exposed as one
19859        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
19860        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
19861        // (Duration → str, exposed as one typed dispatch through
19862        // [`RateLimit::canonical_unit`] composed with
19863        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
19864        // codec's parse arm ([`rate_limit_codec::parse`] via
19865        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
19866        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
19867        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
19868        // via [`RateLimit::canonical_unit`]) all key off. A future
19869        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
19870        // sub-second window) is one variant + one arm per method on the
19871        // closed-set enum; the compiler-enforced exhaustiveness on
19872        // every consumer's `match self` arms picks it up by
19873        // construction. This pin enshrines that both projection
19874        // directions agree on every canonical arm row and neither
19875        // leaks a spurious entry the other doesn't recognize.
19876        //
19877        // Predecessor: this test previously read the two vestigial
19878        // module-private free helpers `rate_limit_window_unit` and
19879        // `rate_limit_window_from_unit` on the `Duration → &str` and
19880        // `&str → Duration` axes; the former was deleted after its
19881        // sole production consumer ([`rate_limit_codec::render`])
19882        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
19883        // the latter is folded here into the substrate primitive
19884        // [`RateLimitUnit::window_from_suffix`] so both projection
19885        // directions live on the closed-set enum's arm-table.
19886        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
19887            let window = super::RateLimitUnit::window_from_suffix(unit)
19888                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
19889            assert_eq!(
19890                window,
19891                Duration::from_secs(secs),
19892                "unit {unit:?} must resolve to {secs}s"
19893            );
19894            let projected_suffix = RateLimit { rate: 1, window }
19895                .canonical_unit()
19896                .map(super::RateLimitUnit::as_suffix);
19897            assert_eq!(
19898                projected_suffix,
19899                Some(unit),
19900                "Duration({secs}s) must render as {unit:?} \
19901                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
19902            );
19903        }
19904        // Non-table units yield None on the `unit → Duration`
19905        // projection — a future `"d"` addition to the table would
19906        // flip this arm; today it pins the current three-row table's
19907        // rejection semantics.
19908        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
19909        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
19910        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
19911        // Non-table Durations yield None on the `Duration → unit`
19912        // projection — pins that the two projections agree on the
19913        // "not in the table" semantic too, so a drift where the
19914        // parse-side accepts a value the render-side can't emit is
19915        // a build error at the two-arm pair, not a silent codec
19916        // round-trip break.
19917        let projected_suffix = |window: Duration| -> Option<&'static str> {
19918            RateLimit { rate: 1, window }
19919                .canonical_unit()
19920                .map(super::RateLimitUnit::as_suffix)
19921        };
19922        assert!(projected_suffix(Duration::from_secs(2)).is_none());
19923        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
19924        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
19925    }
19926
19927    #[test]
19928    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
19929        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
19930        // substrate-primitive `&str → Duration` associated method the
19931        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
19932        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
19933        // to the same [`Duration`] the two-step composition
19934        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
19935        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
19936        // `"MIN"`) must project to [`None`] on both paths. A future
19937        // implementation of `window_from_suffix` that took a shortcut
19938        // through a per-suffix `match` table (bypassing the arm-table's
19939        // `Self::from_suffix` scan and the arm-table's `Self::window`
19940        // dispatch) would silently split the accept-set — the parse
19941        // arm would accept a suffix the enum's arm-table doesn't know,
19942        // or reject a suffix the enum's arm-table does; this pin
19943        // surfaces that drift at caixa-core build time rather than at a
19944        // downstream serde round-trip audit on a live `MeshPolicy`.
19945        //
19946        // Same byte-parity discipline the sibling
19947        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
19948        // pin carries on the peer `Duration → RateLimitUnit` axis via
19949        // [`RateLimit::canonical_unit`], and the peer
19950        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
19951        // carries on the bidirectional arm-table axis — extended here
19952        // onto the fifth (and last unlifted) projection axis on the
19953        // closed-set enum's arm-table.
19954        let composition = |suffix: &str| -> Option<Duration> {
19955            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
19956        };
19957        for suffix in ["s", "m", "h"] {
19958            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
19959            let via_composition = composition(suffix);
19960            assert_eq!(
19961                via_method, via_composition,
19962                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
19963                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
19964                 method must delegate to the arm-table's two typed dispatches, \
19965                 not shortcut through a per-suffix match table"
19966            );
19967            assert!(
19968                via_method.is_some(),
19969                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
19970                 RateLimitUnit::window_from_suffix"
19971            );
19972        }
19973        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
19974            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
19975            let via_composition = composition(suffix);
19976            assert_eq!(
19977                via_method, via_composition,
19978                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
19979                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
19980                 axis too"
19981            );
19982            assert!(
19983                via_method.is_none(),
19984                "non-arm suffix {suffix:?} must project to None via \
19985                 RateLimitUnit::window_from_suffix — a future extension that \
19986                 accepted this suffix without a corresponding arm on the enum \
19987                 would split the codec's parse-accepted set from the enum's \
19988                 arm-table"
19989            );
19990        }
19991        // And the codec's parse arm now reads through this method: a
19992        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
19993        // the same `Duration` the method returns for its unit, closing
19994        // the two-consumer drift surface (the codec's parse arm and the
19995        // enum's arm-table) with one typed dispatch on the substrate
19996        // primitive.
19997        for suffix in ["s", "m", "h"] {
19998            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
19999            let mp: MeshPolicy = serde_json::from_str(&wire)
20000                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
20001            let parsed = mp.rate_limit().expect("rate_limit payload present");
20002            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
20003                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
20004            assert_eq!(
20005                parsed.window(),
20006                via_method,
20007                "codec parse arm on {wire:?} must resolve the window through \
20008                 RateLimitUnit::window_from_suffix, not a divergent path"
20009            );
20010        }
20011    }
20012
20013    #[test]
20014    fn rate_limit_unit_all_enumerates_every_arm_once() {
20015        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
20016        // enumerate every arm of the closed-set enum exactly once, in
20017        // the canonical shortest-to-longest window order (Second before
20018        // Minute before Hour) — the same order the sibling
20019        // [`crate::supervisor::RestartStrategy`] /
20020        // [`crate::supervisor::RestartPolicy`] /
20021        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
20022        // typed enums carry (the arm declared first is the arm listed
20023        // first). A future variant addition that extends the enum
20024        // without appending to [`RateLimitUnit::ALL`] leaves the
20025        // exhaustive iteration surface silently short one arm — the
20026        // codec's parse arm would then reject the new suffix even
20027        // though the enum knows it. This pin closes the drift.
20028        assert_eq!(
20029            super::RateLimitUnit::ALL,
20030            &[
20031                super::RateLimitUnit::Second,
20032                super::RateLimitUnit::Minute,
20033                super::RateLimitUnit::Hour,
20034            ],
20035            "RateLimitUnit::ALL must enumerate every arm exactly once, \
20036             in canonical shortest-to-longest window order"
20037        );
20038    }
20039
20040    #[test]
20041    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
20042        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
20043        // every arm's [`RateLimitUnit::as_suffix`] output must parse
20044        // back through [`RateLimitUnit::from_suffix`] to the same
20045        // variant. A future arm addition that lands `as_suffix` but
20046        // forgets `from_suffix` (`from_suffix` iterates
20047        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
20048        // is the load-bearing carrier of the round-trip; the sibling
20049        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
20050        // the `ALL` half) trips here at caixa-core build time rather
20051        // than surfacing as a codec round-trip miss (a `render` emit
20052        // that lands a suffix the paired `parse` cannot decode).
20053        for unit in super::RateLimitUnit::ALL {
20054            let suffix = unit.as_suffix();
20055            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
20056                panic!(
20057                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
20058                     RateLimitUnit::as_suffix output — got None for {unit:?}"
20059                )
20060            });
20061            assert_eq!(
20062                parsed, *unit,
20063                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
20064                 must return RateLimitUnit::{unit:?}"
20065            );
20066        }
20067    }
20068
20069    #[test]
20070    fn rate_limit_unit_from_window_and_window_round_trip() {
20071        // Total round-trip pin on the `(from_window, window)` pair:
20072        // every arm's [`RateLimitUnit::window`] output must parse back
20073        // through [`RateLimitUnit::from_window`] to the same variant.
20074        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
20075        // on the peer `Duration` axis — the two round-trip pins
20076        // together enshrine that both projections of the typed
20077        // canonical-unit bijection are total on the arm-set.
20078        for unit in super::RateLimitUnit::ALL {
20079            let window = unit.window();
20080            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
20081                panic!(
20082                    "RateLimitUnit::from_window({window:?}) must accept every \
20083                     RateLimitUnit::window output — got None for {unit:?}"
20084                )
20085            });
20086            assert_eq!(
20087                parsed, *unit,
20088                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
20089                 must return RateLimitUnit::{unit:?}"
20090            );
20091        }
20092    }
20093
20094    #[test]
20095    fn rate_limit_unit_from_window_accessor_is_const_fn() {
20096        // Fail-before-pass-after pin: witnesses the
20097        // [`RateLimitUnit::from_window`] `const`-eval posture via a
20098        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
20099        // -> Option<RateLimitUnit>` whose body calls
20100        // `RateLimitUnit::from_window(window)`, well-formed only when
20101        // the callee is itself `const fn` (any future downgrade to
20102        // non-`const` fails at caixa-core build time with E0015 `cannot
20103        // call non-const function`, strictly stronger than a runtime
20104        // `assert!`, side-stepping the destructor-in-const restriction
20105        // that blocks direct `const _: Option<RateLimitUnit> =
20106        // RateLimitUnit::from_window(...)` items on `Duration`'s
20107        // carrier). The runtime body sweeps every closed-set
20108        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
20109        // rejection sample (`Duration::from_millis(500)` sub-second
20110        // residue) and asserts the wrapped and direct dispatches agree
20111        // — a violation means the wrapper stopped compiling under a
20112        // future `const`-posture downgrade, or the reverse resolver's
20113        // arm-set silently split from the peer `Self::window` emitter's
20114        // arm-set. Peer of the sibling
20115        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
20116        // (152c868) /
20117        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
20118        // (152c868) /
20119        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
20120        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
20121        // `const`-eval-surface pins on the peer M2 / M3 substrate-
20122        // primitive `Copy`-return accessor axes, extended onto the
20123        // reverse `Duration → RateLimitUnit` projection axis on the
20124        // M3 mesh-slot rate-limit closed-set typed enum.
20125        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
20126            super::RateLimitUnit::from_window(window)
20127        }
20128        for unit in super::RateLimitUnit::ALL {
20129            let window = unit.window();
20130            let via_wrapper = from_window_via_const_fn(window);
20131            let direct = super::RateLimitUnit::from_window(window);
20132            assert_eq!(
20133                via_wrapper, direct,
20134                "RateLimitUnit::from_window({window:?}) via const fn \
20135                 wrapper must agree with direct dispatch for {unit:?}"
20136            );
20137            assert_eq!(
20138                via_wrapper,
20139                Some(*unit),
20140                "RateLimitUnit::from_window({window:?}) via const fn \
20141                 wrapper must return Some({unit:?}) for the peer \
20142                 window() output"
20143            );
20144        }
20145        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
20146        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
20147    }
20148
20149    #[test]
20150    fn rate_limit_unit_from_window_composes_through_window_accessor() {
20151        // Composition-witness pin on the routing-through-peer discipline:
20152        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
20153        // through the peer `pub const fn` [`RateLimitUnit::window`]
20154        // canonical-`Duration` projection rather than a hand-authored
20155        // per-arm second-magnitude literal — a future arm-magnitude edit
20156        // on the sibling `window()` accessor (a `Second → 2s` typo, a
20157        // `Hour → 3599s` off-by-one) must therefore reach this reverse
20158        // resolver by construction. A pin that hard-coded the three
20159        // second-magnitudes here would silently split from the peer
20160        // emitter on any such edit; instead, this pin asserts the
20161        // composition invariant `from_window(u.window()) == Some(u)`
20162        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
20163        // arm — a violation means either the peer `Self::window`
20164        // accessor drifted (breaking every downstream consumer that
20165        // reads through it), or the reverse resolver stopped routing
20166        // through the peer (introducing a hand-authored literal that
20167        // silently disagrees with the emitter). Either failure is a
20168        // caixa-core-build-time surface, not a downstream renderer
20169        // round-trip regression.
20170        //
20171        // Peer of the sibling
20172        // [`crate::render::assert_str_reexport_identity`] discipline on
20173        // the substrate-primitive `&'static str` re-export axis and the
20174        // [`rate_limit_unit_from_window_and_window_round_trip`]
20175        // round-trip pin on the peer projection direction; extends the
20176        // one-canonical-dispatch-per-projection discipline onto the
20177        // reverse-resolver's per-arm probe axis.
20178        for unit in super::RateLimitUnit::ALL {
20179            let window_via_peer = unit.window();
20180            let resolved = super::RateLimitUnit::from_window(window_via_peer);
20181            assert_eq!(
20182                resolved,
20183                Some(*unit),
20184                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
20185                 must return Some({unit:?}) — the reverse resolver's per-arm \
20186                 probes must route through the peer `Self::window` accessor \
20187                 so any future arm-magnitude edit reaches both projection \
20188                 directions by construction"
20189            );
20190        }
20191    }
20192
20193    #[test]
20194    fn rate_limit_canonical_unit_accessor_is_const_fn() {
20195        // Fail-before-pass-after pin: witnesses the
20196        // [`RateLimit::canonical_unit`] `const`-eval posture via a
20197        // `const fn` wrapper
20198        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
20199        // whose body calls `rl.canonical_unit()`, well-formed only when
20200        // the callee is itself `const fn` (any future downgrade to
20201        // non-`const` fails at caixa-core build time with E0015 `cannot
20202        // call non-const method`). The runtime body sweeps every
20203        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
20204        // constructs a typed [`RateLimit`] with the peer `Self::window`
20205        // canonical `Duration`, then asserts both the wrapper and the
20206        // direct dispatch agree and both return `Some(unit)`. Composes
20207        // with the sibling
20208        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
20209        // typed [`RateLimit`] projection layer's `const`-posture is
20210        // load-bearing on the reverse resolver's `const`-posture, and
20211        // both must migrate together (a downgrade of either surface
20212        // splits the paired `const`-eval-surface pass on the M3
20213        // mesh-slot rate-limit `Duration ↔ Self` bijection).
20214        const fn canonical_unit_via_const_fn(
20215            rl: &super::RateLimit,
20216        ) -> Option<super::RateLimitUnit> {
20217            rl.canonical_unit()
20218        }
20219        for unit in super::RateLimitUnit::ALL {
20220            let rl = super::RateLimit {
20221                rate: 1,
20222                window: unit.window(),
20223            };
20224            let via_wrapper = canonical_unit_via_const_fn(&rl);
20225            let direct = rl.canonical_unit();
20226            assert_eq!(
20227                via_wrapper, direct,
20228                "RateLimit::canonical_unit() via const fn wrapper must \
20229                 agree with direct dispatch for {unit:?}"
20230            );
20231            assert_eq!(
20232                via_wrapper,
20233                Some(*unit),
20234                "RateLimit::canonical_unit() via const fn wrapper must \
20235                 return Some({unit:?}) for a RateLimit whose window is \
20236                 the peer RateLimitUnit::{unit:?}.window() output"
20237            );
20238        }
20239    }
20240
20241    #[test]
20242    fn rate_limit_unit_projections_are_pairwise_distinct() {
20243        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
20244        // [`RateLimitUnit::window`] outputs must be pairwise distinct
20245        // across every arm — an accidental copy-paste flip that
20246        // reroutes one arm's suffix or window to also match another
20247        // silently collapses two arms onto one, so
20248        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
20249        // (both using `find` on `Self::ALL`) would return whichever
20250        // arm the linear scan lands on first — a match-arm-ordering-
20251        // dependent outcome the closed-set typed-enum shape is meant
20252        // to rule out structurally. Peer of the sibling
20253        // `caixa_kind_wire_consts_are_pairwise_distinct` /
20254        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
20255        // other closed-set typed-enum discriminator axes.
20256        let all = super::RateLimitUnit::ALL;
20257        for (i, a) in all.iter().enumerate() {
20258            for (j, b) in all.iter().enumerate() {
20259                if i != j {
20260                    assert_ne!(
20261                        a.as_suffix(),
20262                        b.as_suffix(),
20263                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
20264                         must be distinct — a collision silently collapses two \
20265                         arms onto one under from_suffix's linear scan"
20266                    );
20267                    assert_ne!(
20268                        a.window(),
20269                        b.window(),
20270                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
20271                         must be distinct — a collision silently collapses two \
20272                         arms onto one under from_window's linear scan"
20273                    );
20274                }
20275            }
20276        }
20277    }
20278
20279    #[test]
20280    fn rate_limit_unit_display_routes_through_as_suffix() {
20281        // Route pin: [`std::fmt::Display`] must byte-equal
20282        // [`RateLimitUnit::as_suffix`] on every arm — the single
20283        // source of truth for the canonical suffix. A future
20284        // reimplementation that hand-rolls the arms instead of
20285        // delegating to [`RateLimitUnit::as_suffix`] would silently
20286        // desynchronize `format!("{u}")` from the codec's parse arm
20287        // (which uses `as_suffix` to compare suffixes). Peer of the
20288        // sibling `caixa_kind_display_routes_through_as_str_helper` /
20289        // `placement_strategy_display_routes_through_as_str_helper`
20290        // pins on the peer closed-set typed-enum Display axes.
20291        for unit in super::RateLimitUnit::ALL {
20292            assert_eq!(
20293                unit.to_string(),
20294                unit.as_suffix(),
20295                "RateLimitUnit::{unit:?} Display must route through \
20296                 as_suffix (single source of truth: the canonical suffix \
20297                 the codec parses and renders)"
20298            );
20299        }
20300    }
20301
20302    #[test]
20303    fn rate_limit_unit_from_window_rejects_non_canonical() {
20304        // Rejection pin on the parser's accept-set: any Duration
20305        // outside the three-arm [`RateLimitUnit::window`] output set
20306        // (sub-second residue, or a second-magnitude outside `{1, 60,
20307        // 3600}`) must return `None`. A future accidental widening of
20308        // the accept-set (rounding down sub-second residue to the
20309        // nearest arm, admitting `Duration::from_secs(30)` as a
20310        // half-minute unit) would silently drift the parser's accept-
20311        // set from the emitter's — a validated slot with a
20312        // non-canonical window would then round-trip through the
20313        // codec to a canonical form the author never wrote.
20314        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
20315        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
20316        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
20317        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
20318        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
20319        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
20320        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
20321    }
20322
20323    #[test]
20324    fn rate_limit_unit_from_suffix_rejects_unknown() {
20325        // Rejection pin on the suffix parser's accept-set: any string
20326        // outside the three-arm [`RateLimitUnit::as_suffix`] output
20327        // set must return `None`. Peer of the sibling
20328        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
20329        // the [`crate::CaixaKind`] `from_wire` accept-set.
20330        for bad in [
20331            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
20332            " s",
20333        ] {
20334            assert!(
20335                super::RateLimitUnit::from_suffix(bad).is_none(),
20336                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
20337                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
20338                 outputs"
20339            );
20340        }
20341    }
20342
20343    #[test]
20344    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
20345        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
20346        // every canonical `:window` magnitude the validate gate
20347        // accepts must map to the paired [`RateLimitUnit`] arm through
20348        // this accessor. A future validate-gate rebrand that widened
20349        // the accepted-window set without extending [`RateLimitUnit`]
20350        // would silently split the accessor's `Some`-return set from
20351        // the validate gate's accept-set — a slot that satisfies
20352        // validate would land at the accessor with `None`, so a
20353        // consumer past validate that pattern-matches on the returned
20354        // `Some` would silently miss the newly-accepted magnitude.
20355        for (window_secs, expected) in [
20356            (1u64, super::RateLimitUnit::Second),
20357            (60, super::RateLimitUnit::Minute),
20358            (3600, super::RateLimitUnit::Hour),
20359        ] {
20360            let rl = RateLimit {
20361                rate: 100,
20362                window: Duration::from_secs(window_secs),
20363            };
20364            assert_eq!(
20365                rl.canonical_unit(),
20366                Some(expected),
20367                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
20368                 must return Some({expected:?})"
20369            );
20370        }
20371        // Non-canonical windows the validate gate rejects also return
20372        // None here — the accessor is the typed-enum projection of
20373        // the sibling `is_canonical_rate_limit_window` predicate.
20374        let bad = RateLimit {
20375            rate: 100,
20376            window: Duration::from_secs(30),
20377        };
20378        assert!(
20379            bad.canonical_unit().is_none(),
20380            "RateLimit with a non-canonical window must return None from \
20381             canonical_unit — the validate gate rejects the same set"
20382        );
20383    }
20384
20385    #[test]
20386    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
20387        // Fail-before-pass-after byte-parity pin: for every canonical
20388        // window the [`rate_limit_codec::render`] arm's emitted string
20389        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
20390        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
20391        // the vestigial free helper [`rate_limit_window_unit`] (a
20392        // `find_map`-walked `Duration → &'static str` delegate) onto the
20393        // substrate primitive [`RateLimit::canonical_unit`] typed method
20394        // (a closed-set `match self.window` arm on
20395        // [`RateLimitUnit::from_window`], projected through
20396        // [`RateLimitUnit::as_suffix`] via the enum's
20397        // [`std::fmt::Display`] impl). A future re-routing of the render
20398        // arm through a differently-computed unit projection would break
20399        // this pin at build time rather than as a silent per-consumer
20400        // codec round-trip drift far from the substrate primitive edit.
20401        //
20402        // Sibling to the peer
20403        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
20404        // on the free-helper axis: that pin locks the two projections
20405        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
20406        // on the closed-set arm table; this pin locks the codec's render
20407        // arm reads through the typed accessor rather than the free
20408        // helper. Two production consumers of the canonical-unit axis
20409        // now key off one typed dispatch on the substrate primitive.
20410        for (window_secs, unit) in [
20411            (1u64, super::RateLimitUnit::Second),
20412            (60, super::RateLimitUnit::Minute),
20413            (3600, super::RateLimitUnit::Hour),
20414        ] {
20415            let rl = RateLimit {
20416                rate: 42,
20417                window: Duration::from_secs(window_secs),
20418            };
20419            let policy = MeshPolicy {
20420                rate_limit: Some(rl),
20421                ..Default::default()
20422            };
20423            let json = serde_json::to_string(&policy).unwrap();
20424            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
20425            assert!(
20426                json.contains(&expected),
20427                "rate_limit_codec::render must emit {expected} (via \
20428                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
20429                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
20430            );
20431            // And the accessor route resolves to the same typed unit
20432            // the render arm's Display formatting is asked to produce —
20433            // so a future edit that split the two paths (one through
20434            // the accessor, one through a re-introduced free helper)
20435            // trips this pin.
20436            assert_eq!(
20437                rl.canonical_unit(),
20438                Some(unit),
20439                "RateLimit::canonical_unit must return Some({unit:?}) for a \
20440                 {window_secs}s window; the codec render arm reads the same \
20441                 typed unit through this accessor"
20442            );
20443        }
20444    }
20445
20446    #[test]
20447    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
20448        // Fail-before-pass-after byte-parity pin on the validate gate's
20449        // canonical-window shape probe: every non-canonical `:window`
20450        // the free-helper predicate [`is_canonical_rate_limit_window`]
20451        // rejects is also rejected by the substrate primitive
20452        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
20453        // gate now reads through, and vice versa on the accepted set
20454        // (the three canonical windows). Locks the migration from the
20455        // free helper onto the substrate primitive: a future re-routing
20456        // of one of the two paths through a differently-computed unit
20457        // projection would silently split the codec's accepted set from
20458        // the validate gate's accepted set — a two-consumer drift the
20459        // codec-round-trip pin
20460        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
20461        // above closes on the render arm and this pin closes on the
20462        // validate arm.
20463        for canonical_window_secs in [1u64, 60, 3600] {
20464            let mut s = three_member_spec();
20465            let rl = RateLimit {
20466                rate: 100,
20467                window: Duration::from_secs(canonical_window_secs),
20468            };
20469            s.politicas.rate_limit = Some(rl);
20470            assert!(
20471                s.validate().is_ok(),
20472                "canonical {canonical_window_secs}s window must pass \
20473                 validate_politicas — the validate gate now reads \
20474                 RateLimit::canonical_unit().is_none() and the accessor \
20475                 returns Some on every canonical arm"
20476            );
20477            assert!(
20478                rl.canonical_unit().is_some(),
20479                "canonical {canonical_window_secs}s window must resolve to \
20480                 Some on RateLimit::canonical_unit — the validate gate reads \
20481                 this accessor directly"
20482            );
20483        }
20484        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
20485            let mut s = three_member_spec();
20486            let rl = RateLimit {
20487                rate: 100,
20488                window: Duration::from_secs(non_canonical_window_secs),
20489            };
20490            s.politicas.rate_limit = Some(rl);
20491            assert_eq!(
20492                s.validate().unwrap_err(),
20493                AplicacaoError::PolicyRateLimitWindowNotCanonical {
20494                    window: rl.window(),
20495                },
20496                "non-canonical {non_canonical_window_secs}s window must be \
20497                 rejected by validate_politicas — the validate gate now \
20498                 keys off RateLimit::canonical_unit().is_none()"
20499            );
20500            assert!(
20501                rl.canonical_unit().is_none(),
20502                "non-canonical {non_canonical_window_secs}s window must \
20503                 resolve to None on RateLimit::canonical_unit — the two \
20504                 paths (the free helper the validate gate previously read \
20505                 and the substrate primitive the validate gate now reads) \
20506                 must agree on the same rejected set"
20507            );
20508        }
20509        // And the substrate-primitive [`RateLimit::canonical_unit`]
20510        // accessor's accepted-window set matches the codec's parse arm's
20511        // accepted-suffix set on every canonical / non-canonical shape,
20512        // so a future silent drift between the codec's accepted set and
20513        // the validate gate's accepted set is a build error at test time
20514        // (both consumers key off the same closed-set enum's `match self`
20515        // arms). The predecessor free helper `is_canonical_rate_limit_window`
20516        // — a delegate that composed [`RateLimitUnit::from_window`] with
20517        // `.is_some()` — was deleted after this migration; the
20518        // canonical-window set now lives on exactly one typed dispatch
20519        // on the substrate primitive.
20520        for (secs, expected) in [
20521            (1u64, true),
20522            (60, true),
20523            (3600, true),
20524            (2, false),
20525            (30, false),
20526            (86_400, false),
20527        ] {
20528            let window = Duration::from_secs(secs);
20529            let rl = RateLimit { rate: 1, window };
20530            assert_eq!(
20531                rl.canonical_unit().is_some(),
20532                expected,
20533                "RateLimit::canonical_unit().is_some() must agree with the \
20534                 codec-accepted canonical-window set on {secs}s"
20535            );
20536            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
20537                1 => "s",
20538                60 => "m",
20539                3600 => "h",
20540                _ => return,
20541            })
20542            .is_some_and(|d| d == window);
20543            if expected {
20544                assert!(
20545                    suffix_from_axis,
20546                    "the codec's `&str → Duration` axis \
20547                     ({secs}s) must round-trip to the same Duration the \
20548                     substrate primitive's accessor returns Some on"
20549                );
20550            }
20551        }
20552    }
20553
20554    #[test]
20555    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
20556        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
20557        // derive: for each of the three variants, exactly one of the
20558        // generated `is_second` / `is_minute` / `is_hour` predicates
20559        // returns `true` and the other two return `false`. Peer of
20560        // the sibling
20561        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
20562        // sibling `IsVariant`-derived closed-set typed-enum pins.
20563        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
20564            (super::RateLimitUnit::Second, [true, false, false]),
20565            (super::RateLimitUnit::Minute, [false, true, false]),
20566            (super::RateLimitUnit::Hour, [false, false, true]),
20567        ];
20568        for (variant, expected) in rows {
20569            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
20570            assert_eq!(
20571                observed, expected,
20572                "RateLimitUnit::{variant:?} is_* predicates must partition \
20573                 the arm set (second, minute, hour); got {observed:?}"
20574            );
20575        }
20576    }
20577
20578    #[test]
20579    fn rejects_policy_timeout_sub_millisecond() {
20580        // A purely sub-millisecond `Duration` (`from_micros(500)` =
20581        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
20582        // arm passes — but `as_millis() == 0`, so the shared codec's
20583        // `render` arm returns the literal `"0s"`, which the
20584        // codec's `parse` arm then deserializes as `Duration::ZERO`
20585        // and the `PolicyTimeoutZero` zero-floor gate would reject
20586        // on re-validate. Pin the rejection at the typed slot's
20587        // canonical-floor gate so the round-trip break surfaces at
20588        // validate time, naming the offending `Duration`, rather
20589        // than at the next serialize → deserialize round-trip far
20590        // from the source `caixa.lisp`.
20591        let mut s = three_member_spec();
20592        let timeout = Duration::from_micros(500);
20593        s.politicas.timeout = Some(timeout);
20594        assert_eq!(
20595            s.validate().unwrap_err(),
20596            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
20597        );
20598    }
20599
20600    #[test]
20601    fn rejects_policy_timeout_non_integer_millisecond() {
20602        // A `Duration` with non-integer-millisecond residue
20603        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
20604        // through the shared codec's `render` arm as `"1ms"` (the
20605        // `as_millis()` floor truncates), which the codec's `parse`
20606        // arm then deserializes as `Duration::from_millis(1)` =
20607        // 1_000_000 ns — silently *different* from the original.
20608        // Pin the rejection so this round-trip break surfaces at
20609        // validate time, where the offending `Duration` is named,
20610        // rather than as a silent value-laundered round-trip on the
20611        // next codec round-trip.
20612        let mut s = three_member_spec();
20613        let timeout = Duration::from_micros(1500);
20614        s.politicas.timeout = Some(timeout);
20615        assert_eq!(
20616            s.validate().unwrap_err(),
20617            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
20618        );
20619    }
20620
20621    #[test]
20622    fn accepts_policy_timeout_integer_millisecond_forms() {
20623        // The codec's accepted set — integer multiples of 1ms — is
20624        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
20625        // `1h` all pass the canonical gate. Pin the canonical-forms
20626        // sweep so a future tightening of the codec's grammar (e.g.
20627        // dropping `:ms`) surfaces here as a test failure rather
20628        // than a silent contract narrowing on the typed slot.
20629        for timeout in [
20630            Duration::from_millis(1),
20631            Duration::from_millis(500),
20632            Duration::from_millis(1500),
20633            Duration::from_secs(30),
20634            Duration::from_secs(120),
20635            Duration::from_secs(3600),
20636        ] {
20637            let mut s = three_member_spec();
20638            s.politicas.timeout = Some(timeout);
20639            s.validate()
20640                .expect("integer-millisecond :timeout must validate");
20641        }
20642    }
20643
20644    #[test]
20645    fn policy_timeout_zero_takes_precedence_over_canonical() {
20646        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
20647        // pass the canonical-millisecond gate; the more self-locating
20648        // `PolicyTimeoutZero` arm (which names the omit-axis
20649        // remediation directly) must fire first. Pin the ordering so
20650        // a future refactor that reorders the arms surfaces here as a
20651        // test failure rather than a silent diagnostic regression.
20652        let mut s = three_member_spec();
20653        s.politicas.timeout = Some(Duration::ZERO);
20654        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
20655    }
20656
20657    #[test]
20658    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
20659        // The diagnostic envelope carries the offending `Duration`
20660        // verbatim so the author can grep their `caixa.lisp` for
20661        // `:timeout "<value>"` and fix it in one edit. Same
20662        // diagnostic shape every other typed-slot canonical-form
20663        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
20664        // peer `:rate-limit :window` axis.
20665        let mut s = three_member_spec();
20666        let timeout = Duration::from_nanos(1_000_001);
20667        s.politicas.timeout = Some(timeout);
20668        match s.validate().unwrap_err() {
20669            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
20670                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
20671            }
20672            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
20673        }
20674    }
20675
20676    #[test]
20677    fn rejects_policy_timeout_above_cap() {
20678        // The fail-before-pass-after pin: 3601s = 1h + 1s is
20679        // structurally one canonical-tick past the
20680        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
20681        // integer-millisecond magnitude the canonical-form arm above
20682        // accepts cleanly, that the codec round-trips losslessly as
20683        // `"3601s"`, and that silently passed validate on every
20684        // pre-gate codebase because the typed slot's only checks were
20685        // the zero-floor and canonical-form arms. The mesh-level
20686        // deadline degenerates only at the runtime substrate (Envoy
20687        // / Cilium L7 timeout overlay) far from the source
20688        // `caixa.lisp` with no field naming the offending policy.
20689        let mut s = three_member_spec();
20690        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
20691        s.politicas.timeout = Some(timeout);
20692        assert_eq!(
20693            s.validate().unwrap_err(),
20694            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20695        );
20696    }
20697
20698    #[test]
20699    fn rejects_policy_timeout_one_millisecond_above_cap() {
20700        // Boundary case: exactly 1ms past the cap (the granularity
20701        // the canonical-form gate enforces). Catches a future
20702        // "strictly less than" half-measure and pins the diagnostic
20703        // to name the offending `Duration` verbatim. Peer of
20704        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
20705        // boundary pin on the sibling `:limits :memory` top edge.
20706        let mut s = three_member_spec();
20707        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
20708        s.politicas.timeout = Some(timeout);
20709        assert_eq!(
20710            s.validate().unwrap_err(),
20711            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20712        );
20713    }
20714
20715    #[test]
20716    fn rejects_policy_timeout_far_above_cap() {
20717        // The "obvious authoring footgun" case: a `(:timeout "24h")`
20718        // or `(:timeout "86400s")` — values the canonical-form arm
20719        // accepts as integer-millisecond magnitudes, the codec
20720        // round-trips losslessly through serde, but the mesh-level
20721        // policy cannot honor (a 24-hour synchronous-`:contratos`
20722        // deadline is operationally indistinguishable from
20723        // omit-the-axis). Until this gate landed validate accepted
20724        // it. Pin both common above-cap values (24h, 7d) so a future
20725        // relaxation that drops the upper bound surfaces here.
20726        for timeout in [
20727            Duration::from_secs(86_400),    // 24h
20728            Duration::from_secs(604_800),   // 7d
20729            Duration::from_secs(1_000_000), // ~11.5 days
20730        ] {
20731            let mut s = three_member_spec();
20732            s.politicas.timeout = Some(timeout);
20733            assert_eq!(
20734                s.validate().unwrap_err(),
20735                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
20736            );
20737        }
20738    }
20739
20740    #[test]
20741    fn accepts_policy_timeout_at_cap() {
20742        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
20743        // must validate. The cap is inclusive on the top edge,
20744        // matching the [`POLICY_RETRIES_MAX`] /
20745        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
20746        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
20747        // sibling capped axes. Pin the boundary explicitly so a
20748        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
20749        // instead of `>`) surfaces here as a test failure rather
20750        // than a silent contract narrowing.
20751        let mut s = three_member_spec();
20752        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
20753        s.validate()
20754            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
20755    }
20756
20757    #[test]
20758    fn accepts_policy_timeout_typical_values() {
20759        // The documented production-playbook band positive-control
20760        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
20761        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
20762        // plus a sweep through the long-running-workflow band
20763        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
20764        // validated set explicitly so a future tightening of the
20765        // ceiling surfaces here as a deliberate test edit, not a
20766        // silent contract narrowing.
20767        for timeout in [
20768            Duration::from_millis(1),
20769            Duration::from_millis(500),
20770            Duration::from_secs(1),
20771            Duration::from_secs(10),
20772            Duration::from_secs(15), // Envoy default
20773            Duration::from_secs(30),
20774            Duration::from_secs(60), // AWS App Mesh typical
20775            Duration::from_secs(300),
20776            Duration::from_secs(900),
20777            Duration::from_secs(1800),
20778            Duration::from_secs(3600), // exactly 1h, the cap
20779        ] {
20780            let mut s = three_member_spec();
20781            s.politicas.timeout = Some(timeout);
20782            s.validate()
20783                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
20784        }
20785    }
20786
20787    #[test]
20788    fn policy_timeout_zero_takes_precedence_over_cap() {
20789        // The cross-arm ordering pin: `Duration::ZERO` is
20790        // structurally outside both `>= 1ms` (zero-floor) and
20791        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
20792        // diagnostic is the more self-locating one (it directly
20793        // names the omit-axis remediation), so the validate gate
20794        // must fire on zero first. Same shape every other
20795        // zero-then-shape ordering on this surface uses
20796        // ([`AplicacaoError::PolicyRetriesZero`] then
20797        // [`AplicacaoError::PolicyRetriesExceedsCap`];
20798        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20799        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20800        let mut s = three_member_spec();
20801        s.politicas.timeout = Some(Duration::ZERO);
20802        assert_eq!(
20803            s.validate().unwrap_err(),
20804            AplicacaoError::PolicyTimeoutZero,
20805            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
20806        );
20807    }
20808
20809    #[test]
20810    fn policy_timeout_canonical_takes_precedence_over_cap() {
20811        // The cross-arm ordering pin: a `Duration` that is *both*
20812        // sub-millisecond (non-canonical-form) and structurally
20813        // above the cap surfaces the canonical-form diagnostic
20814        // first, because the round-trip-shape break is the more
20815        // fundamental issue (the value can't even round-trip
20816        // through the codec, so the cap diagnostic naming
20817        // `1ms..=1h` would be misleading — there's no integer-ms
20818        // form of the offending value). Pin the order so a future
20819        // refactor that reorders the arms surfaces here as a test
20820        // failure rather than a silent diagnostic regression.
20821        let mut s = three_member_spec();
20822        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
20823        // *and* total magnitude above the 1h cap.
20824        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
20825        s.politicas.timeout = Some(timeout);
20826        assert_eq!(
20827            s.validate().unwrap_err(),
20828            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
20829            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
20830        );
20831    }
20832
20833    #[test]
20834    fn policy_timeout_cap_diagnostic_carries_offending_value() {
20835        // The diagnostic-shape pin: the offending `Duration` is
20836        // carried verbatim into the
20837        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
20838        // surfaced error message names the value the author wrote
20839        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
20840        // exceeds the mesh-policy ceiling …"`), not just the cap.
20841        // Same self-locating diagnostic shape every other typed-cap
20842        // arm on this surface carries
20843        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
20844        // offending retry count verbatim).
20845        let mut s = three_member_spec();
20846        let timeout = Duration::from_secs(7200); // 2h
20847        s.politicas.timeout = Some(timeout);
20848        let err = s.validate().unwrap_err();
20849        assert!(
20850            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
20851            "got {err:?}"
20852        );
20853        let msg = err.to_string();
20854        assert!(
20855            msg.contains("7200"),
20856            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
20857        );
20858    }
20859
20860    #[test]
20861    fn policy_timeout_cap_pins_canonical_value() {
20862        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
20863        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
20864        // the shared duration codec emits as a clean canonical
20865        // string (`"<n>h"`). Pinning the literal value here surfaces
20866        // a future drift (a relaxation to 24h, a tightening to 5m)
20867        // as a deliberate test edit, not a silent contract
20868        // narrowing. Same shape every other typed-cap value pin on
20869        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
20870        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
20871        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
20872    }
20873
20874    #[test]
20875    fn policy_timeout_cap_value_round_trips_through_codec() {
20876        // The codec round-trip property the cap arm preserves: the
20877        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
20878        // the shared duration codec — every value at the cap renders
20879        // to a clean canonical string (`"1h"`) and parses back to
20880        // the same `Duration`. Pin this so a future drift between
20881        // the cap constant and the codec's largest emitted unit
20882        // surfaces here. Same shape every other typed boundary pin
20883        // on this surface uses
20884        // (`wasm32_memory_cap_matches_parsed_4_gib`).
20885        let policy = MeshPolicy {
20886            timeout: Some(POLICY_TIMEOUT_MAX),
20887            ..Default::default()
20888        };
20889        let json = serde_json::to_string(&policy).unwrap();
20890        // The codec emits `"1h"` for the canonical 1-hour magnitude.
20891        assert!(
20892            json.contains("\"1h\""),
20893            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
20894        );
20895        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20896        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
20897    }
20898
20899    #[test]
20900    fn rejects_circuit_breaker_window_sub_millisecond() {
20901        // Peer of the `:timeout` sub-millisecond arm on the second
20902        // typed-`Duration` `:politicas` axis: a purely sub-ms
20903        // `Duration` (`from_micros(500)`) renders through the shared
20904        // codec as `"0s"`, which the codec parses back to
20905        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
20906        // zero-floor gate then rejects on re-validate.
20907        let mut s = three_member_spec();
20908        let window = Duration::from_micros(500);
20909        s.politicas.circuit_breaker = Some(CircuitBreaker {
20910            max_failures: 5,
20911            window,
20912        });
20913        assert_eq!(
20914            s.validate().unwrap_err(),
20915            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
20916        );
20917    }
20918
20919    #[test]
20920    fn rejects_circuit_breaker_window_non_integer_millisecond() {
20921        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
20922        // with non-integer-millisecond residue renders through the
20923        // shared codec as the truncated `"<n>ms"` form, parsing back
20924        // to a *different* `Duration` on the next round-trip.
20925        let mut s = three_member_spec();
20926        let window = Duration::from_micros(1500);
20927        s.politicas.circuit_breaker = Some(CircuitBreaker {
20928            max_failures: 5,
20929            window,
20930        });
20931        assert_eq!(
20932            s.validate().unwrap_err(),
20933            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
20934        );
20935    }
20936
20937    #[test]
20938    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
20939        // The canonical-forms sweep on the breaker axis: every
20940        // integer-ms multiple the codec round-trips losslessly
20941        // passes the canonical gate.
20942        //
20943        // Clears `:timeout` from the fixture so this per-axis sweep
20944        // covers windows shorter than the fixture's 30s timeout
20945        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
20946        // structurally-inert breaker
20947        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
20948        // the cross-axis gate at the end of
20949        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
20950        // `(:timeout, :window)` shape, not on the per-axis
20951        // integer-millisecond canonical-form shape this test pins.
20952        // The paired shape is covered by
20953        // `rejects_circuit_breaker_window_below_timeout`.
20954        for window in [
20955            Duration::from_millis(1),
20956            Duration::from_millis(500),
20957            Duration::from_millis(1500),
20958            Duration::from_secs(30),
20959            Duration::from_secs(60),
20960            Duration::from_secs(3600),
20961        ] {
20962            let mut s = three_member_spec();
20963            s.politicas.timeout = None;
20964            s.politicas.circuit_breaker = Some(CircuitBreaker {
20965                max_failures: 5,
20966                window,
20967            });
20968            s.validate()
20969                .expect("integer-millisecond :circuit-breaker :window must validate");
20970        }
20971    }
20972
20973    #[test]
20974    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
20975        // `Duration::ZERO` would pass the canonical-ms gate (the
20976        // sub-ns residue is zero) but must surface the narrower
20977        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
20978        // remediation.
20979        let mut s = three_member_spec();
20980        s.politicas.circuit_breaker = Some(CircuitBreaker {
20981            max_failures: 5,
20982            window: Duration::ZERO,
20983        });
20984        assert_eq!(
20985            s.validate().unwrap_err(),
20986            AplicacaoError::PolicyBreakerZeroWindow
20987        );
20988    }
20989
20990    #[test]
20991    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
20992        // Both axes invalid: max_failures == 0 *and* window is
20993        // sub-ms. The validate gate must fire on max_failures first
20994        // (matching the existing ordering pin
20995        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
20996        // the existing diagnostic continues to lead with the simpler
20997        // "zero threshold" framing.
20998        let mut s = three_member_spec();
20999        s.politicas.circuit_breaker = Some(CircuitBreaker {
21000            max_failures: 0,
21001            window: Duration::from_micros(500),
21002        });
21003        assert_eq!(
21004            s.validate().unwrap_err(),
21005            AplicacaoError::PolicyBreakerZeroFailures
21006        );
21007    }
21008
21009    #[test]
21010    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
21011        let mut s = three_member_spec();
21012        let window = Duration::from_nanos(60_000_000_001);
21013        s.politicas.circuit_breaker = Some(CircuitBreaker {
21014            max_failures: 5,
21015            window,
21016        });
21017        match s.validate().unwrap_err() {
21018            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
21019                assert_eq!(w, window, "diagnostic must carry the offending Duration");
21020            }
21021            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
21022        }
21023    }
21024
21025    #[test]
21026    fn rejects_circuit_breaker_window_above_cap() {
21027        // The fail-before-pass-after pin: 3601s = 1h + 1s is
21028        // structurally one canonical-tick past the
21029        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
21030        // integer-millisecond magnitude the canonical-form arm above
21031        // accepts cleanly, that the codec round-trips losslessly as
21032        // `"3601s"`, and that silently passed validate on every
21033        // pre-gate codebase because the typed slot's only checks were
21034        // the zero-floor and canonical-form arms. The
21035        // rolling-window-to-lifetime-counter degeneration surfaces
21036        // only at the runtime substrate (Envoy's outlier_detection
21037        // interval, the future CiliumClusterwideEnvoyConfig overlay)
21038        // far from the source `caixa.lisp` with no field naming the
21039        // offending policy.
21040        let mut s = three_member_spec();
21041        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
21042        s.politicas.circuit_breaker = Some(CircuitBreaker {
21043            max_failures: 5,
21044            window,
21045        });
21046        assert_eq!(
21047            s.validate().unwrap_err(),
21048            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
21049        );
21050    }
21051
21052    #[test]
21053    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
21054        // Boundary case: exactly 1ms past the cap (the granularity the
21055        // canonical-form gate enforces). Catches a future "strictly
21056        // less than" half-measure and pins the diagnostic to name the
21057        // offending `Duration` verbatim. Peer of
21058        // `rejects_policy_timeout_one_millisecond_above_cap` on the
21059        // sibling duration-typed `:politicas :timeout` top edge.
21060        let mut s = three_member_spec();
21061        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
21062        s.politicas.circuit_breaker = Some(CircuitBreaker {
21063            max_failures: 5,
21064            window,
21065        });
21066        assert_eq!(
21067            s.validate().unwrap_err(),
21068            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
21069        );
21070    }
21071
21072    #[test]
21073    fn rejects_circuit_breaker_window_far_above_cap() {
21074        // The "obvious authoring footgun" case: a `(:window "24h")` or
21075        // `(:window "86400s")` — values the canonical-form arm
21076        // accepts as integer-millisecond magnitudes, the codec
21077        // round-trips losslessly through serde, but the
21078        // rolling-window breaker contract cannot honor (a 24-hour
21079        // rolling failure window is operationally a lifetime counter).
21080        // Until this gate landed validate accepted it. Pin both common
21081        // above-cap values (24h, 7d) so a future relaxation that
21082        // drops the upper bound surfaces here.
21083        for window in [
21084            Duration::from_secs(86_400),    // 24h
21085            Duration::from_secs(604_800),   // 7d
21086            Duration::from_secs(1_000_000), // ~11.5 days
21087        ] {
21088            let mut s = three_member_spec();
21089            s.politicas.circuit_breaker = Some(CircuitBreaker {
21090                max_failures: 5,
21091                window,
21092            });
21093            assert_eq!(
21094                s.validate().unwrap_err(),
21095                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
21096            );
21097        }
21098    }
21099
21100    #[test]
21101    fn accepts_circuit_breaker_window_at_cap() {
21102        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
21103        // (1h) — must validate. The cap is inclusive on the top edge,
21104        // matching the [`POLICY_TIMEOUT_MAX`] /
21105        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
21106        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
21107        // sibling capped axes. Pin the boundary explicitly so a
21108        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
21109        // instead of `>`) surfaces here as a test failure rather than
21110        // a silent contract narrowing.
21111        let mut s = three_member_spec();
21112        s.politicas.circuit_breaker = Some(CircuitBreaker {
21113            max_failures: 5,
21114            window: POLICY_BREAKER_WINDOW_MAX,
21115        });
21116        s.validate()
21117            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
21118    }
21119
21120    #[test]
21121    fn accepts_circuit_breaker_window_typical_values() {
21122        // The documented production-playbook band positive-control
21123        // sweep — every value Hystrix / resilience4j / Istio / Envoy
21124        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
21125        // through the long-tail failure-detection band (15m, 30m, 1h)
21126        // the cap accepts. Pin the inclusive validated set explicitly
21127        // so a future tightening of the ceiling surfaces here as a
21128        // deliberate test edit, not a silent contract narrowing.
21129        //
21130        // Clears `:timeout` from the fixture so this per-axis sweep
21131        // covers windows shorter than the fixture's 30s timeout
21132        // (Hystrix's 10s default, resilience4j's 30s, and the
21133        // sub-second warm-up band) — every such value is a
21134        // structurally-inert breaker under the cross-axis gate at the
21135        // end of [`AplicacaoSpec::validate_politicas`]
21136        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
21137        // the paired `(:timeout, :window)` shape is covered by
21138        // `rejects_circuit_breaker_window_below_timeout`; this
21139        // per-axis pin ranges only over the per-axis-bracket accept set.
21140        for window in [
21141            Duration::from_millis(1),
21142            Duration::from_millis(500),
21143            Duration::from_secs(1),
21144            Duration::from_secs(10), // Hystrix / Istio / Envoy default
21145            Duration::from_secs(30),
21146            Duration::from_secs(60),  // resilience4j typical
21147            Duration::from_secs(300), // AWS App Mesh typical
21148            Duration::from_secs(900),
21149            Duration::from_secs(1800),
21150            Duration::from_secs(3600), // exactly 1h, the cap
21151        ] {
21152            let mut s = three_member_spec();
21153            s.politicas.timeout = None;
21154            s.politicas.circuit_breaker = Some(CircuitBreaker {
21155                max_failures: 5,
21156                window,
21157            });
21158            s.validate()
21159                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
21160        }
21161    }
21162
21163    #[test]
21164    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
21165        // The cross-arm ordering pin: `Duration::ZERO` is structurally
21166        // outside both `>= 1ms` (zero-floor) and
21167        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
21168        // diagnostic is the more self-locating one (it directly names
21169        // the omit-axis remediation), so the validate gate must fire
21170        // on zero first. Same shape every other zero-then-cap
21171        // ordering on this surface uses
21172        // ([`AplicacaoError::PolicyTimeoutZero`] then
21173        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
21174        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
21175        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
21176        let mut s = three_member_spec();
21177        s.politicas.circuit_breaker = Some(CircuitBreaker {
21178            max_failures: 5,
21179            window: Duration::ZERO,
21180        });
21181        assert_eq!(
21182            s.validate().unwrap_err(),
21183            AplicacaoError::PolicyBreakerZeroWindow,
21184            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
21185        );
21186    }
21187
21188    #[test]
21189    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
21190        // The cross-arm ordering pin: a `Duration` that is *both*
21191        // sub-millisecond (non-canonical-form) and structurally above
21192        // the cap surfaces the canonical-form diagnostic first,
21193        // because the round-trip-shape break is the more fundamental
21194        // issue (the value can't even round-trip through the codec, so
21195        // the cap diagnostic naming `1ms..=1h` would be misleading —
21196        // there's no integer-ms form of the offending value). Pin the
21197        // order so a future refactor that reorders the arms surfaces
21198        // here as a test failure rather than a silent diagnostic
21199        // regression. Peer of
21200        // `policy_timeout_canonical_takes_precedence_over_cap` on the
21201        // sibling duration-typed `:politicas :timeout` axis.
21202        let mut s = three_member_spec();
21203        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
21204        s.politicas.circuit_breaker = Some(CircuitBreaker {
21205            max_failures: 5,
21206            window,
21207        });
21208        assert_eq!(
21209            s.validate().unwrap_err(),
21210            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
21211            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
21212        );
21213    }
21214
21215    #[test]
21216    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
21217        // The cross-arm ordering pin between the two breaker axes: a
21218        // `CircuitBreaker` whose *both* `max_failures` is above its
21219        // cap *and* `window` is above its cap surfaces the
21220        // max-failures cap diagnostic first, because the validate
21221        // gate visits the failures arm before the window arm. Pin the
21222        // order so a future refactor that reorders the breaker arms
21223        // surfaces here.
21224        let mut s = three_member_spec();
21225        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
21226        s.politicas.circuit_breaker = Some(CircuitBreaker {
21227            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
21228            window,
21229        });
21230        assert_eq!(
21231            s.validate().unwrap_err(),
21232            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
21233                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
21234            },
21235            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
21236        );
21237    }
21238
21239    #[test]
21240    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
21241        // The diagnostic-shape pin: the offending `Duration` is
21242        // carried verbatim into the
21243        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
21244        // the surfaced error message names the value the author wrote
21245        // (`":politicas :circuit-breaker :window (Duration { secs:
21246        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
21247        // just the cap. Same self-locating diagnostic shape every
21248        // other typed-cap arm on this surface carries
21249        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
21250        // offending `Duration` verbatim).
21251        let mut s = three_member_spec();
21252        let window = Duration::from_secs(7200); // 2h
21253        s.politicas.circuit_breaker = Some(CircuitBreaker {
21254            max_failures: 5,
21255            window,
21256        });
21257        let err = s.validate().unwrap_err();
21258        assert!(
21259            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
21260            "got {err:?}"
21261        );
21262        let msg = err.to_string();
21263        assert!(
21264            msg.contains("7200"),
21265            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
21266        );
21267    }
21268
21269    #[test]
21270    fn circuit_breaker_window_cap_pins_canonical_value() {
21271        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
21272        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
21273        // shared duration codec emits as a clean canonical string
21274        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
21275        // the sibling duration-typed `:politicas :timeout` axis (the
21276        // two duration-typed `:politicas` axes share a uniform top
21277        // edge). Pinning the literal value here surfaces a future
21278        // drift (a relaxation to 24h, a tightening to 5m) as a
21279        // deliberate test edit, not a silent contract narrowing. Same
21280        // shape every other typed-cap value pin on this surface uses
21281        // (`policy_timeout_cap_pins_canonical_value`).
21282        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
21283        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
21284        assert_eq!(
21285            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
21286            "the two duration-typed `:politicas` caps share the same top edge"
21287        );
21288    }
21289
21290    #[test]
21291    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
21292        // The codec round-trip property the cap arm preserves: the
21293        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
21294        // through the shared duration codec — every value at the cap
21295        // renders to a clean canonical string (`"1h"`) and parses back
21296        // to the same `Duration`. Pin this so a future drift between
21297        // the cap constant and the codec's largest emitted unit
21298        // surfaces here. Same shape every other typed boundary pin on
21299        // this surface uses
21300        // (`policy_timeout_cap_value_round_trips_through_codec`).
21301        let policy = MeshPolicy {
21302            circuit_breaker: Some(CircuitBreaker {
21303                max_failures: 5,
21304                window: POLICY_BREAKER_WINDOW_MAX,
21305            }),
21306            ..Default::default()
21307        };
21308        let json = serde_json::to_string(&policy).unwrap();
21309        // The codec emits `"1h"` for the canonical 1-hour magnitude.
21310        assert!(
21311            json.contains("\"1h\""),
21312            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
21313        );
21314        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21315        assert_eq!(
21316            back.circuit_breaker.unwrap().window,
21317            POLICY_BREAKER_WINDOW_MAX
21318        );
21319    }
21320
21321    #[test]
21322    fn is_integer_millisecond_duration_predicate_tracks_codec() {
21323        // Pin the predicate's accepted set against the codec's
21324        // accepted set explicitly. The codec parses
21325        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
21326        // accepted value is an integer-millisecond multiple — so the
21327        // predicate must accept exactly that set. Same shape every
21328        // other predicate-on-the-typed-slot helper carries
21329        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
21330        // Read directly from the codec-owned predicate — the crate's
21331        // single source of truth every typed-`Duration` axis now routes
21332        // through via
21333        // [`crate::render::require_positive_canonical_bounded_duration`].
21334        use super::supervisor::duration_codec::is_integer_millisecond_duration;
21335        assert!(is_integer_millisecond_duration(Duration::ZERO));
21336        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
21337        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
21338        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
21339        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
21340        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
21341        // Non-integer-millisecond residue: rejected.
21342        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
21343        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
21344        assert!(!is_integer_millisecond_duration(Duration::from_micros(
21345            1500
21346        )));
21347        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
21348        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
21349            999_999
21350        )));
21351        // The 1-ns-past-1ms boundary: rejected (no longer a clean
21352        // integer-millisecond multiple).
21353        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
21354            1_000_001
21355        )));
21356    }
21357
21358    #[test]
21359    fn policy_timeout_validated_value_round_trips_through_codec() {
21360        // The structural property the canonical-ms gate enforces:
21361        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
21362        // round-trips losslessly through the shared `duration_codec`
21363        // (serialize → string → deserialize → equal value). Pin this
21364        // end-to-end so a future change to either side (the validate
21365        // gate's accepted granularity, the codec's parse/render unit
21366        // set) that breaks the alignment surfaces here. The
21367        // previous-state shape (typed slot accepts arbitrary
21368        // `Duration`, codec only round-trips integer-ms) would fail
21369        // this test for any `Duration::from_micros(1500)` timeout —
21370        // the validate gate now forecloses that.
21371        for timeout in [
21372            Duration::from_millis(1),
21373            Duration::from_millis(1500),
21374            Duration::from_secs(30),
21375            Duration::from_secs(3600),
21376        ] {
21377            let mut s = three_member_spec();
21378            s.politicas.timeout = Some(timeout);
21379            s.validate().unwrap();
21380            let json = serde_json::to_string(&s.politicas).unwrap();
21381            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21382            assert_eq!(
21383                back.timeout, s.politicas.timeout,
21384                "every validated :timeout must round-trip losslessly through the codec"
21385            );
21386        }
21387    }
21388
21389    #[test]
21390    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
21391        // Peer of the `:timeout` round-trip property on the breaker
21392        // axis.
21393        //
21394        // Clears `:timeout` from the fixture so the round-trip pin
21395        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
21396        // cross-axis gate would otherwise reject as structurally-inert
21397        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
21398        // the paired `(:timeout, :window)` cross-axis relation is
21399        // pinned separately by
21400        // `rejects_circuit_breaker_window_below_timeout`, and this
21401        // property is a pure serde-codec round-trip on the per-axis
21402        // slot.
21403        for window in [
21404            Duration::from_millis(1),
21405            Duration::from_millis(1500),
21406            Duration::from_secs(30),
21407            Duration::from_secs(3600),
21408        ] {
21409            let mut s = three_member_spec();
21410            s.politicas.timeout = None;
21411            s.politicas.circuit_breaker = Some(CircuitBreaker {
21412                max_failures: 5,
21413                window,
21414            });
21415            s.validate().unwrap();
21416            let json = serde_json::to_string(&s.politicas).unwrap();
21417            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21418            assert_eq!(
21419                back.circuit_breaker.unwrap().window,
21420                window,
21421                "every validated :circuit-breaker :window must round-trip losslessly"
21422            );
21423        }
21424    }
21425
21426    #[test]
21427    fn rejects_circuit_breaker_window_below_timeout() {
21428        // The fail-before-pass-after pin on the cross-axis
21429        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
21430        // is individually well-formed under its own per-axis bracket
21431        // (both integer-millisecond, both above the zero floor, both
21432        // below the cap), but the pair is a structurally-inert
21433        // breaker: a call dispatched at t=0 is declared failed at
21434        // t=30s, by which point the 10s rolling window open at
21435        // dispatch has already rolled twice, so no window can hold
21436        // a timeout-derived failure however high the call volume.
21437        //
21438        // Envoy's `outlier_detection.interval` against the per-route
21439        // request timeout carries the identical relation; Hystrix
21440        // ships the canonical ratio in its defaults (10s window
21441        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
21442        //
21443        // Pin both the diagnostic arm and the payload values so a
21444        // future re-shape of the arm surfaces here as a deliberate
21445        // test edit.
21446        let mut s = three_member_spec();
21447        s.politicas.timeout = Some(Duration::from_secs(30));
21448        s.politicas.circuit_breaker = Some(CircuitBreaker {
21449            max_failures: 5,
21450            window: Duration::from_secs(10),
21451        });
21452        assert_eq!(
21453            s.validate().unwrap_err(),
21454            AplicacaoError::PolicyBreakerWindowBelowTimeout {
21455                window: Duration::from_secs(10),
21456                timeout: Duration::from_secs(30),
21457            }
21458        );
21459    }
21460
21461    #[test]
21462    fn accepts_circuit_breaker_window_equal_to_timeout() {
21463        // Boundary pin: `:window == :timeout` is the smallest window
21464        // that structurally admits at least one full timeout-derived
21465        // failure before the rolling interval closes (the invariant
21466        // is `:window >= :timeout`, not strict inequality). Catches
21467        // a future off-by-one tightening that would drift the accept
21468        // set away from the codified [`MeshPolicy::breaker_window_
21469        // observes_timeout`] predicate.
21470        let mut s = three_member_spec();
21471        s.politicas.timeout = Some(Duration::from_secs(30));
21472        s.politicas.circuit_breaker = Some(CircuitBreaker {
21473            max_failures: 5,
21474            window: Duration::from_secs(30),
21475        });
21476        s.validate()
21477            .expect("window == timeout is the boundary accept case");
21478    }
21479
21480    #[test]
21481    fn accepts_circuit_breaker_window_above_timeout() {
21482        // Positive-control sweep across the production-playbook band —
21483        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
21484        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
21485        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
21486        // playbook recommends must validate under the cross-axis gate.
21487        for (timeout, window) in [
21488            (Duration::from_secs(1), Duration::from_secs(10)),
21489            (Duration::from_secs(5), Duration::from_secs(30)),
21490            (Duration::from_secs(10), Duration::from_secs(60)),
21491            (Duration::from_secs(30), Duration::from_secs(300)),
21492            (Duration::from_secs(60), Duration::from_secs(300)),
21493        ] {
21494            let mut s = three_member_spec();
21495            s.politicas.timeout = Some(timeout);
21496            s.politicas.circuit_breaker = Some(CircuitBreaker {
21497                max_failures: 5,
21498                window,
21499            });
21500            s.validate().unwrap_or_else(|e| {
21501                panic!(
21502                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
21503                     validate; got {e:?}"
21504                )
21505            });
21506        }
21507    }
21508
21509    #[test]
21510    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
21511        // Off-by-one boundary pin: a window exactly 1ms shy of the
21512        // timeout is still structurally inert under the invariant
21513        // (the dispatch-to-report lag is `timeout`, so the window
21514        // must span at least one such lag). Catches a future
21515        // strict-inequality relaxation that would silently drift
21516        // the accept boundary.
21517        let timeout = Duration::from_secs(30);
21518        let window = Duration::from_millis(29_999);
21519        let mut s = three_member_spec();
21520        s.politicas.timeout = Some(timeout);
21521        s.politicas.circuit_breaker = Some(CircuitBreaker {
21522            max_failures: 5,
21523            window,
21524        });
21525        assert_eq!(
21526            s.validate().unwrap_err(),
21527            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
21528        );
21529    }
21530
21531    #[test]
21532    fn cross_axis_gate_vacuous_when_timeout_absent() {
21533        // The predicate is vacuously `true` when `:timeout` is None —
21534        // a `:circuit-breaker` alone declares no relation to a
21535        // substrate-imposed deadline (the failure signal reaches the
21536        // breaker from the transport's own error surface, so no
21537        // dispatch-to-report lag is knowable at author time). Pin so
21538        // a future tightening that made the gate opinionated on
21539        // half-declared pairs surfaces here.
21540        let mut s = three_member_spec();
21541        s.politicas.timeout = None;
21542        s.politicas.circuit_breaker = Some(CircuitBreaker {
21543            max_failures: 5,
21544            window: Duration::from_millis(1),
21545        });
21546        s.validate().expect(
21547            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
21548        );
21549    }
21550
21551    #[test]
21552    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
21553        // Peer of the sibling `:timeout`-absent case: a `:timeout`
21554        // without a `:circuit-breaker` declares a per-call deadline
21555        // without any rolling-window failure accounting, so the pair
21556        // is undeclared and the cross-axis gate has nothing to check.
21557        let mut s = three_member_spec();
21558        s.politicas.timeout = Some(Duration::from_secs(3600));
21559        s.politicas.circuit_breaker = None;
21560        s.validate().expect(
21561            "cross-axis gate must be vacuous when :circuit-breaker is None, \
21562             however large :timeout is",
21563        );
21564    }
21565
21566    #[test]
21567    fn cross_axis_gate_runs_after_per_axis_brackets() {
21568        // Ordering pin: a pair whose window is *both* zero-floor-
21569        // violating and structurally below the timeout must surface
21570        // the per-axis zero-floor arm first — the zero-floor
21571        // diagnostic is more self-locating (its omit-axis remediation
21572        // is directly named), where the cross-axis arm would send the
21573        // author to reconcile two values one of which is not a
21574        // meaningful window at all. Same ordering discipline every
21575        // per-axis bracket carries internally (zero-floor before
21576        // canonical-form before cap).
21577        let mut s = three_member_spec();
21578        s.politicas.timeout = Some(Duration::from_secs(30));
21579        s.politicas.circuit_breaker = Some(CircuitBreaker {
21580            max_failures: 5,
21581            window: Duration::ZERO,
21582        });
21583        assert_eq!(
21584            s.validate().unwrap_err(),
21585            AplicacaoError::PolicyBreakerZeroWindow,
21586            "per-axis zero-floor arm must fire before the cross-axis gate"
21587        );
21588    }
21589
21590    #[test]
21591    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
21592        // Equivalence pin: the substrate-canonical
21593        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
21594        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21595        // arm must discriminate the same set on every pair covered
21596        // by their shared invariant. A future refactor of either
21597        // side that breaks the equivalence trips here rather than as
21598        // a divergence between the predicate's Boolean answer and
21599        // the validate gate's Ok/Err arm — the same
21600        // predicate-vs-gate coherence discipline the peer
21601        // [`PlacementStrategy::is_shard_keyed`] predicate carries
21602        // against `AplicacaoSpec::validate_placement`. The sweep
21603        // covers both arms of the invariant (below, equal, above)
21604        // and both vacuous arms (None `:timeout`, None
21605        // `:circuit-breaker`), so the equivalence holds
21606        // exhaustively over the axis-covered accept and reject sets.
21607        let cases: &[(Option<Duration>, Option<Duration>)] = &[
21608            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
21609            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
21610            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
21611            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
21612            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
21613            (None, Some(Duration::from_secs(1))),
21614            (Some(Duration::from_secs(30)), None),
21615            (None, None),
21616        ];
21617        for (timeout, window) in cases.iter().copied() {
21618            let politicas = MeshPolicy {
21619                timeout,
21620                circuit_breaker: window.map(|w| CircuitBreaker {
21621                    max_failures: 5,
21622                    window: w,
21623                }),
21624                ..Default::default()
21625            };
21626            let predicate = politicas.breaker_window_observes_timeout();
21627
21628            let mut s = three_member_spec();
21629            s.politicas = politicas.clone();
21630            let gate_ok = !matches!(
21631                s.validate(),
21632                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
21633            );
21634
21635            assert_eq!(
21636                predicate, gate_ok,
21637                "predicate must agree with validate arm on pair \
21638                 (timeout={timeout:?}, window={window:?})"
21639            );
21640        }
21641    }
21642
21643    #[test]
21644    fn rejects_rate_limit_starves_circuit_breaker() {
21645        // The fail-before-pass-after pin on the cross-axis
21646        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
21647        // individually well-formed under its own per-axis bracket
21648        // (both above the zero floor, both below the cap, rate-limit
21649        // window canonical), but the pair is a structurally-inert
21650        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
21651        // calls per rolling breaker window, so no window can
21652        // accumulate five failures however catastrophic the upstream
21653        // failure rate.
21654        //
21655        // Envoy's `outlier_detection.consecutive_5xx` paired against
21656        // `local_rate_limit.token_bucket.max_tokens` /
21657        // `fill_interval` carries the identical relation; every
21658        // production playbook that pairs the two axes (Envoy, Istio,
21659        // AWS App Mesh, Kong) sizes the rate at or above the
21660        // breaker's minimum-request-volume threshold for exactly this
21661        // reason.
21662        //
21663        // Pin both the diagnostic arm and the payload values so a
21664        // future re-shape of the arm surfaces here as a deliberate
21665        // test edit. Clears `:timeout` so the sibling
21666        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
21667        // does not fire first on the ordering-precedent it holds
21668        // over this arm.
21669        let mut s = three_member_spec();
21670        s.politicas.timeout = None;
21671        s.politicas.circuit_breaker = Some(CircuitBreaker {
21672            max_failures: 5,
21673            window: Duration::from_secs(10),
21674        });
21675        s.politicas.rate_limit = Some(RateLimit {
21676            rate: 1,
21677            window: Duration::from_secs(3600),
21678        });
21679        assert_eq!(
21680            s.validate().unwrap_err(),
21681            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21682                rate: 1,
21683                rl_window: Duration::from_secs(3600),
21684                max_failures: 5,
21685                cb_window: Duration::from_secs(10),
21686            }
21687        );
21688    }
21689
21690    #[test]
21691    fn accepts_rate_limit_can_trip_circuit_breaker() {
21692        // Positive-control sweep across the production-playbook band
21693        // — every pair a real playbook recommends where the rate
21694        // clearly admits enough calls per breaker window to reach
21695        // `:max-failures` must validate. Envoy default 5 failures
21696        // in 10s with 100/s (1000 calls / window, 200× the threshold),
21697        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
21698        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
21699        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
21700        // the sibling cross-axis arm is vacuous on this sweep.
21701        for (rate, rl_window, max_failures, cb_window) in [
21702            (
21703                100u32,
21704                Duration::from_secs(1),
21705                5u32,
21706                Duration::from_secs(10),
21707            ),
21708            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
21709            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
21710            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
21711            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
21712        ] {
21713            let mut s = three_member_spec();
21714            s.politicas.timeout = None;
21715            s.politicas.circuit_breaker = Some(CircuitBreaker {
21716                max_failures,
21717                window: cb_window,
21718            });
21719            s.politicas.rate_limit = Some(RateLimit {
21720                rate,
21721                window: rl_window,
21722            });
21723            s.validate().unwrap_or_else(|e| {
21724                panic!(
21725                    "production-playbook pair rate={rate}/{rl_window:?} \
21726                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
21727                )
21728            });
21729        }
21730    }
21731
21732    #[test]
21733    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
21734        // Boundary pin: `rate × cb_window == max_failures × rl_window`
21735        // is the smallest bucket capacity that structurally admits
21736        // exactly `max_failures` calls per rolling breaker window
21737        // (the invariant is `≥`, not strict inequality). Catches a
21738        // future off-by-one tightening to strict inequality that
21739        // would drift the accept set away from the codified
21740        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
21741        // 5 calls/s over a 1s breaker window == 5 max_failures.
21742        let mut s = three_member_spec();
21743        s.politicas.timeout = None;
21744        s.politicas.circuit_breaker = Some(CircuitBreaker {
21745            max_failures: 5,
21746            window: Duration::from_secs(1),
21747        });
21748        s.politicas.rate_limit = Some(RateLimit {
21749            rate: 5,
21750            window: Duration::from_secs(1),
21751        });
21752        s.validate()
21753            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
21754    }
21755
21756    #[test]
21757    fn rejects_rate_limit_one_call_short_per_cb_window() {
21758        // Off-by-one boundary pin: exactly one call short of the trip
21759        // threshold per breaker window is still structurally inert
21760        // (the invariant is `≥`, so `<` refuses even a one-call
21761        // shortfall). 4 calls/s over a 1s window == 4 admissible
21762        // failures, one shy of the 5-`max_failures` threshold.
21763        // Catches a future strict-inequality relaxation that would
21764        // silently drift the accept boundary.
21765        let mut s = three_member_spec();
21766        s.politicas.timeout = None;
21767        s.politicas.circuit_breaker = Some(CircuitBreaker {
21768            max_failures: 5,
21769            window: Duration::from_secs(1),
21770        });
21771        s.politicas.rate_limit = Some(RateLimit {
21772            rate: 4,
21773            window: Duration::from_secs(1),
21774        });
21775        assert_eq!(
21776            s.validate().unwrap_err(),
21777            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
21778                rate: 4,
21779                rl_window: Duration::from_secs(1),
21780                max_failures: 5,
21781                cb_window: Duration::from_secs(1),
21782            }
21783        );
21784    }
21785
21786    #[test]
21787    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
21788        // The predicate is vacuously `true` when `:rate-limit` is
21789        // None — a `:circuit-breaker` alone declares no relation to
21790        // a substrate-imposed call rate (the failure signal reaches
21791        // the breaker from the transport's own error surface, at
21792        // whatever rate upstream callers push traffic). Pin so a
21793        // future tightening that made the gate opinionated on
21794        // half-declared pairs surfaces here.
21795        let mut s = three_member_spec();
21796        s.politicas.timeout = None;
21797        s.politicas.circuit_breaker = Some(CircuitBreaker {
21798            max_failures: 1000,
21799            window: Duration::from_millis(1),
21800        });
21801        s.politicas.rate_limit = None;
21802        s.validate().expect(
21803            "cross-axis starve gate must be vacuous when :rate-limit is None, \
21804             however high :max-failures and however small :window are",
21805        );
21806    }
21807
21808    #[test]
21809    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
21810        // Peer of the sibling `:rate-limit`-absent case: a
21811        // `:rate-limit` without a `:circuit-breaker` declares a
21812        // per-edge token-bucket rate without any failure counter to
21813        // starve, so the pair is undeclared and the cross-axis gate
21814        // has nothing to check.
21815        //
21816        // Also clears the fixture's `:retries` (which is `Some(3)`) so
21817        // the sibling cross-axis
21818        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
21819        // (which reasons across the paired `(:retries, :rate-limit)`
21820        // pair independent of `:circuit-breaker`) is vacuous on this
21821        // pin — this test names the *starve* arm's vacuity on the
21822        // `:circuit-breaker`-absent case, not the burst arm's.
21823        let mut s = three_member_spec();
21824        s.politicas.timeout = None;
21825        s.politicas.retries = None;
21826        s.politicas.circuit_breaker = None;
21827        s.politicas.rate_limit = Some(RateLimit {
21828            rate: 1,
21829            window: Duration::from_secs(3600),
21830        });
21831        s.validate().expect(
21832            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
21833             however low :rate is",
21834        );
21835    }
21836
21837    #[test]
21838    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
21839        // Ordering pin: a pair whose rate is *both* zero-floor-
21840        // violating and structurally below the trip threshold must
21841        // surface the per-axis zero-floor arm first — the zero-floor
21842        // diagnostic is more self-locating (its omit-axis remediation
21843        // is directly named), where the cross-axis arm would send the
21844        // author to reconcile four values one of which is not a
21845        // meaningful rate at all. Same ordering discipline every
21846        // per-axis bracket carries internally (zero-floor before
21847        // canonical-form before cap), and the sibling cross-axis
21848        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
21849        // ordering pins on the `(:timeout, :window)` pair.
21850        let mut s = three_member_spec();
21851        s.politicas.timeout = None;
21852        s.politicas.circuit_breaker = Some(CircuitBreaker {
21853            max_failures: 5,
21854            window: Duration::from_secs(10),
21855        });
21856        s.politicas.rate_limit = Some(RateLimit {
21857            rate: 0,
21858            window: Duration::from_secs(1),
21859        });
21860        assert_eq!(
21861            s.validate().unwrap_err(),
21862            AplicacaoError::PolicyRateLimitZero,
21863            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
21864        );
21865    }
21866
21867    #[test]
21868    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
21869        // Cross-axis ordering pin: a `:politicas` whose axes trip
21870        // BOTH cross-axis arms — `:window < :timeout` (the sibling
21871        // `PolicyBreakerWindowBelowTimeout` invariant) AND
21872        // `:rate-limit` starves the breaker within `:window` (this
21873        // arm) — must surface the timeout-relation diagnostic first.
21874        // The timeout arm is the per-call-deadline invariant every
21875        // synchronous edge carries whether or not `:rate-limit` is
21876        // declared, so its diagnostic is more self-locating; the
21877        // starve arm needs the reader to reason across three axes,
21878        // where the timeout arm names only two.
21879        //
21880        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
21881        // pair trips both: the window is below the timeout, and the
21882        // rate (1 call/hour) admits far fewer than 5 calls per 10s
21883        // breaker window.
21884        let mut s = three_member_spec();
21885        s.politicas.timeout = Some(Duration::from_secs(30));
21886        s.politicas.circuit_breaker = Some(CircuitBreaker {
21887            max_failures: 5,
21888            window: Duration::from_secs(10),
21889        });
21890        s.politicas.rate_limit = Some(RateLimit {
21891            rate: 1,
21892            window: Duration::from_secs(3600),
21893        });
21894        assert_eq!(
21895            s.validate().unwrap_err(),
21896            AplicacaoError::PolicyBreakerWindowBelowTimeout {
21897                window: Duration::from_secs(10),
21898                timeout: Duration::from_secs(30),
21899            },
21900            "sibling :window<:timeout cross-axis arm must fire before the \
21901             starve arm when both apply"
21902        );
21903    }
21904
21905    #[test]
21906    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
21907        // Equivalence pin: the substrate-canonical
21908        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
21909        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
21910        // arm must discriminate the same set on every pair covered
21911        // by their shared invariant. A future refactor of either
21912        // side that breaks the equivalence trips here rather than as
21913        // a divergence between the predicate's Boolean answer and
21914        // the validate gate's Ok/Err arm — the same
21915        // predicate-vs-gate coherence discipline the sibling
21916        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
21917        // carries against `AplicacaoSpec::validate_politicas`. The
21918        // sweep covers both arms of the invariant (strictly below,
21919        // exactly at, strictly above) and both vacuous arms (None
21920        // `:rate-limit`, None `:circuit-breaker`), so the
21921        // equivalence holds exhaustively over the axis-covered
21922        // accept and reject sets. Clears `:timeout` throughout so
21923        // the sibling `:window<:timeout` gate is vacuous on every
21924        // input.
21925        let rl = |rate: u32, secs: u64| {
21926            Some(RateLimit {
21927                rate,
21928                window: Duration::from_secs(secs),
21929            })
21930        };
21931        let cb = |max_failures: u32, secs: u64| {
21932            Some(CircuitBreaker {
21933                max_failures,
21934                window: Duration::from_secs(secs),
21935            })
21936        };
21937        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
21938            // starving pairs (predicate = false, gate = Err)
21939            (rl(1, 3600), cb(5, 10)),
21940            (rl(4, 1), cb(5, 1)),
21941            // boundary + coherent pairs (predicate = true, gate = Ok)
21942            (rl(5, 1), cb(5, 1)),
21943            (rl(100, 1), cb(5, 10)),
21944            // vacuous arms
21945            (None, cb(5, 10)),
21946            (rl(1, 3600), None),
21947            (None, None),
21948        ];
21949        for (rate_limit, circuit_breaker) in cases.iter().copied() {
21950            let politicas = MeshPolicy {
21951                circuit_breaker,
21952                rate_limit,
21953                ..Default::default()
21954            };
21955            let predicate = politicas.breaker_can_trip_under_rate_limit();
21956
21957            let mut s = three_member_spec();
21958            s.politicas = politicas.clone();
21959            s.politicas.timeout = None;
21960            let gate_ok = !matches!(
21961                s.validate(),
21962                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
21963            );
21964
21965            assert_eq!(
21966                predicate, gate_ok,
21967                "predicate must agree with validate arm on pair \
21968                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
21969            );
21970        }
21971    }
21972
21973    #[test]
21974    fn rejects_retries_saturate_breaker_trip_threshold() {
21975        // The fail-before-pass-after pin on the cross-axis
21976        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
21977        // axis is individually well-formed under its own per-axis
21978        // bracket (both above the zero floor, both below the cap), but
21979        // the pair is a structurally-truncated retry policy: one
21980        // client's `retries + 1 = 4` failing attempts hit the trip
21981        // threshold on the third attempt, the breaker opens, and the
21982        // fourth attempt (the last declared retry) is blocked by the
21983        // open breaker — the substrate declared four attempts and
21984        // structurally allows three.
21985        //
21986        // Envoy's `retry_policy.num_retries` paired against
21987        // `outlier_detection.consecutive_5xx` carries the identical
21988        // relation; every production playbook that pairs the two axes
21989        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
21990        // trip threshold strictly above any single client's retry
21991        // budget so the breaker distinguishes one persistently-failing
21992        // client from sustained multi-client failure.
21993        //
21994        // Pin both the diagnostic arm and the payload values so a
21995        // future re-shape of the arm surfaces here as a deliberate
21996        // test edit. Clears `:timeout` and `:rate-limit` so the
21997        // sibling cross-axis
21998        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
21999        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
22000        // arms do not fire first on the ordering-precedent they hold
22001        // over this arm.
22002        let mut s = three_member_spec();
22003        s.politicas.timeout = None;
22004        s.politicas.retries = Some(3);
22005        s.politicas.circuit_breaker = Some(CircuitBreaker {
22006            max_failures: 3,
22007            window: Duration::from_secs(1),
22008        });
22009        s.politicas.rate_limit = None;
22010        assert_eq!(
22011            s.validate().unwrap_err(),
22012            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22013                retries: 3,
22014                max_failures: 3,
22015            }
22016        );
22017    }
22018
22019    #[test]
22020    fn accepts_retries_below_breaker_trip_threshold() {
22021        // Positive-control sweep across the production-playbook band
22022        // — every pair a real playbook recommends where the breaker's
22023        // trip threshold is strictly above the client's retry budget
22024        // must validate. Envoy default `num_retries: 3` with
22025        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
22026        // opens on multi-client failures beyond that); Istio
22027        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
22028        // `execution.isolation.thread.timeoutInMilliseconds` + 3
22029        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
22030        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
22031        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
22032        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
22033        // arms are vacuous on this sweep.
22034        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
22035        {
22036            let mut s = three_member_spec();
22037            s.politicas.timeout = None;
22038            s.politicas.retries = Some(retries);
22039            s.politicas.circuit_breaker = Some(CircuitBreaker {
22040                max_failures,
22041                window: Duration::from_secs(60),
22042            });
22043            s.politicas.rate_limit = None;
22044            s.validate().unwrap_or_else(|e| {
22045                panic!(
22046                    "production-playbook pair retries={retries} \
22047                     max_failures={max_failures} must validate; got {e:?}"
22048                )
22049            });
22050        }
22051    }
22052
22053    #[test]
22054    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
22055        // Boundary pin: `max_failures == retries + 1` is the smallest
22056        // trip threshold that admits one client's exhausted retries
22057        // through completion (the R+1th failure — the last declared
22058        // retry — trips the breaker exactly as it completes, so
22059        // retries fully executed). The invariant is `>`, not `>=`,
22060        // stated in the coherent direction `max_failures > retries`.
22061        // Catches a future off-by-one tightening to
22062        // `max_failures > retries + 1` that would drift the accept set
22063        // away from the codified
22064        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
22065        // predicate.
22066        let mut s = three_member_spec();
22067        s.politicas.timeout = None;
22068        s.politicas.retries = Some(3);
22069        s.politicas.circuit_breaker = Some(CircuitBreaker {
22070            max_failures: 4,
22071            window: Duration::from_secs(60),
22072        });
22073        s.politicas.rate_limit = None;
22074        s.validate()
22075            .expect("max_failures == retries + 1 is the boundary accept case");
22076    }
22077
22078    #[test]
22079    fn rejects_retries_equal_to_breaker_trip_threshold() {
22080        // Off-by-one boundary pin: exactly at the trip threshold is
22081        // still structurally truncating (the invariant is `>`, so `<=`
22082        // refuses even the tight boundary). `retries = 3` with
22083        // `max_failures = 3` means the breaker trips on the third
22084        // failure — the last declared retry attempt is blocked.
22085        // Catches a future relaxation to `>=` that would silently
22086        // drift the accept boundary.
22087        let mut s = three_member_spec();
22088        s.politicas.timeout = None;
22089        s.politicas.retries = Some(3);
22090        s.politicas.circuit_breaker = Some(CircuitBreaker {
22091            max_failures: 3,
22092            window: Duration::from_secs(60),
22093        });
22094        s.politicas.rate_limit = None;
22095        assert_eq!(
22096            s.validate().unwrap_err(),
22097            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22098                retries: 3,
22099                max_failures: 3,
22100            }
22101        );
22102    }
22103
22104    #[test]
22105    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
22106        // The predicate is vacuously `true` when `:retries` is None —
22107        // a `:circuit-breaker` alone declares a failure counter whose
22108        // per-client attempt count is unconstrained by the substrate,
22109        // so no per-client saturation bound on failures-per-client-call
22110        // is knowable at author time. The substrate takes no position
22111        // on whether an omitted `:retries` axis means zero retries or
22112        // "the client picks its own retry policy" — either way, the
22113        // pair is undeclared and the cross-axis gate has nothing to
22114        // check. Pin so a future tightening that made the gate
22115        // opinionated on half-declared pairs surfaces here.
22116        let mut s = three_member_spec();
22117        s.politicas.timeout = None;
22118        s.politicas.retries = None;
22119        s.politicas.circuit_breaker = Some(CircuitBreaker {
22120            max_failures: 1,
22121            window: Duration::from_secs(60),
22122        });
22123        s.politicas.rate_limit = None;
22124        s.validate().expect(
22125            "cross-axis retries gate must be vacuous when :retries is None, \
22126             however low :max-failures is",
22127        );
22128    }
22129
22130    #[test]
22131    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
22132        // Peer of the sibling `:retries`-absent case: a `:retries`
22133        // without a `:circuit-breaker` declares a client-retry policy
22134        // with no failure counter to trip, so the pair is undeclared
22135        // and the cross-axis gate has nothing to check.
22136        let mut s = three_member_spec();
22137        s.politicas.timeout = None;
22138        s.politicas.retries = Some(POLICY_RETRIES_MAX);
22139        s.politicas.circuit_breaker = None;
22140        s.politicas.rate_limit = None;
22141        s.validate().expect(
22142            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
22143             however high :retries is",
22144        );
22145    }
22146
22147    #[test]
22148    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
22149        // Ordering pin: a pair whose retries is *both* zero-floor-
22150        // violating and structurally at-or-below the trip threshold
22151        // must surface the per-axis zero-floor arm first — the
22152        // zero-floor diagnostic is more self-locating (its omit-axis
22153        // remediation is directly named), where the cross-axis arm
22154        // would send the author to reconcile two values one of which
22155        // is not a meaningful retry count at all. Same ordering
22156        // discipline every per-axis bracket carries internally
22157        // (zero-floor before canonical-form before cap), and the
22158        // sibling cross-axis
22159        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
22160        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
22161        let mut s = three_member_spec();
22162        s.politicas.timeout = None;
22163        s.politicas.retries = Some(0);
22164        s.politicas.circuit_breaker = Some(CircuitBreaker {
22165            max_failures: 3,
22166            window: Duration::from_secs(60),
22167        });
22168        s.politicas.rate_limit = None;
22169        assert_eq!(
22170            s.validate().unwrap_err(),
22171            AplicacaoError::PolicyRetriesZero,
22172            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
22173        );
22174    }
22175
22176    #[test]
22177    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
22178        // Cross-axis ordering pin: a `:politicas` whose axes trip
22179        // BOTH cross-axis arms — `:rate-limit` starves the breaker
22180        // within `:window` (the sibling
22181        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
22182        // `:retries + 1` saturates `:max-failures` (this arm) — must
22183        // surface the rate-limit-starve diagnostic first. The
22184        // rate-limit-starve arm reasons across the token-bucket
22185        // admission axis every rate-limited edge carries whether or
22186        // not `:retries` is declared, so its diagnostic is more
22187        // self-locating; the retries-saturate arm reasons across a
22188        // per-client retry-policy budget the starve arm does not
22189        // touch.
22190        //
22191        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
22192        // pair trips both: the rate structurally cannot deliver 5
22193        // failures per 10s breaker window, and simultaneously
22194        // one client's `retries + 1 = 6` attempts alone would
22195        // saturate the 5-`max_failures` threshold.
22196        let mut s = three_member_spec();
22197        s.politicas.timeout = None;
22198        s.politicas.retries = Some(5);
22199        s.politicas.circuit_breaker = Some(CircuitBreaker {
22200            max_failures: 5,
22201            window: Duration::from_secs(10),
22202        });
22203        s.politicas.rate_limit = Some(RateLimit {
22204            rate: 1,
22205            window: Duration::from_secs(3600),
22206        });
22207        assert_eq!(
22208            s.validate().unwrap_err(),
22209            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22210                rate: 1,
22211                rl_window: Duration::from_secs(3600),
22212                max_failures: 5,
22213                cb_window: Duration::from_secs(10),
22214            },
22215            "sibling :rate-limit-starve cross-axis arm must fire before the \
22216             retries-saturate arm when both apply"
22217        );
22218    }
22219
22220    #[test]
22221    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
22222        // Equivalence pin: the substrate-canonical
22223        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
22224        // predicate and the [`AplicacaoSpec::validate_politicas`]
22225        // cross-axis arm must discriminate the same set on every pair
22226        // covered by their shared invariant. A future refactor of
22227        // either side that breaks the equivalence trips here rather
22228        // than as a divergence between the predicate's Boolean answer
22229        // and the validate gate's Ok/Err arm — the same
22230        // predicate-vs-gate coherence discipline the sibling
22231        // [`MeshPolicy::breaker_window_observes_timeout`] and
22232        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
22233        // carry against `AplicacaoSpec::validate_politicas`. The
22234        // sweep covers both arms of the invariant (strictly below,
22235        // exactly at the boundary, strictly above) and both vacuous
22236        // arms (None `:retries`, None `:circuit-breaker`), so the
22237        // equivalence holds exhaustively over the axis-covered accept
22238        // and reject sets. Clears `:timeout` and `:rate-limit`
22239        // throughout so the sibling cross-axis arms are vacuous on
22240        // every input.
22241        let cb = |max_failures: u32| {
22242            Some(CircuitBreaker {
22243                max_failures,
22244                window: Duration::from_secs(60),
22245            })
22246        };
22247        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
22248            // saturating pairs (predicate = false, gate = Err)
22249            (Some(3), cb(3)),
22250            (Some(3), cb(1)),
22251            (Some(10), cb(5)),
22252            // boundary + coherent pairs (predicate = true, gate = Ok)
22253            (Some(3), cb(4)),
22254            (Some(1), cb(5)),
22255            (Some(3), cb(20)),
22256            // vacuous arms
22257            (None, cb(1)),
22258            (Some(10), None),
22259            (None, None),
22260        ];
22261        for (retries, circuit_breaker) in cases.iter().copied() {
22262            let politicas = MeshPolicy {
22263                retries,
22264                circuit_breaker,
22265                ..Default::default()
22266            };
22267            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
22268
22269            let mut s = three_member_spec();
22270            s.politicas = politicas.clone();
22271            let gate_ok = !matches!(
22272                s.validate(),
22273                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
22274            );
22275
22276            assert_eq!(
22277                predicate, gate_ok,
22278                "predicate must agree with validate arm on pair \
22279                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
22280            );
22281        }
22282    }
22283
22284    #[test]
22285    fn rejects_rate_limit_cannot_admit_retry_burst() {
22286        // The fail-before-pass-after pin on the cross-axis
22287        // `(:retries, :rate-limit)` invariant. Each axis is
22288        // individually well-formed under its own per-axis bracket (both
22289        // above the zero floor, both below the cap), but the pair is a
22290        // structurally-truncated retry policy: one client's
22291        // `retries + 1 = 6` failing attempts consume 6 tokens from a
22292        // bucket that admits at most 3 per refill window, so the fourth
22293        // attempt onward is 429ed by the local rate limiter and the
22294        // declared retry policy is silently truncated by the same rate
22295        // limiter it feeds through — the substrate declared six
22296        // attempts and structurally allows three.
22297        //
22298        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
22299        // against `retry_policy.num_retries` carries the identical
22300        // relation; every production playbook that pairs the two axes
22301        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
22302        // capacity strictly above any single client's retry budget so
22303        // the limiter distinguishes one client's declared retries from
22304        // sustained multi-client load.
22305        //
22306        // Pin both the diagnostic arm and the payload values so a
22307        // future re-shape of the arm surfaces here as a deliberate
22308        // test edit. Clears `:timeout` and `:circuit-breaker` so the
22309        // sibling cross-axis
22310        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
22311        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
22312        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
22313        // arms do not fire first on the ordering-precedent they hold
22314        // over this arm.
22315        let mut s = three_member_spec();
22316        s.politicas.timeout = None;
22317        s.politicas.retries = Some(5);
22318        s.politicas.circuit_breaker = None;
22319        s.politicas.rate_limit = Some(RateLimit {
22320            rate: 3,
22321            window: Duration::from_secs(1),
22322        });
22323        assert_eq!(
22324            s.validate().unwrap_err(),
22325            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22326                retries: 5,
22327                rate: 3,
22328            }
22329        );
22330    }
22331
22332    #[test]
22333    fn accepts_rate_limit_admits_retry_burst() {
22334        // Positive-control sweep across the production-playbook band
22335        // — every pair a real playbook recommends where the bucket
22336        // capacity is strictly above the client's retry budget must
22337        // validate. Envoy default `num_retries: 3` with 100/s (100
22338        // tokens per window admits 4 attempts per client with 96 to
22339        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
22340        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
22341        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
22342        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
22343        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
22344        // arms are vacuous on this sweep.
22345        for (retries, rate, secs) in [
22346            (3u32, 100u32, 1u64),
22347            (3, 50, 1),
22348            (2, 10, 1),
22349            (5, 1000, 1),
22350            (3, 1_000_000, 3600),
22351            (10, POLICY_RATE_LIMIT_MAX, 1),
22352        ] {
22353            let mut s = three_member_spec();
22354            s.politicas.timeout = None;
22355            s.politicas.retries = Some(retries);
22356            s.politicas.circuit_breaker = None;
22357            s.politicas.rate_limit = Some(RateLimit {
22358                rate,
22359                window: Duration::from_secs(secs),
22360            });
22361            s.validate().unwrap_or_else(|e| {
22362                panic!(
22363                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
22364                     must validate; got {e:?}"
22365                )
22366            });
22367        }
22368    }
22369
22370    #[test]
22371    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
22372        // Boundary pin: `rate == retries + 1` is the smallest bucket
22373        // capacity that structurally admits one client's exhausted
22374        // retries through completion (each attempt draws exactly one
22375        // token; `retries + 1` tokens available admits `retries + 1`
22376        // attempts, retries fully executed). The invariant is `>=`,
22377        // stated in the coherent direction `rate >= retries + 1`.
22378        // Catches a future off-by-one tightening to `rate > retries + 1`
22379        // that would drift the accept set away from the codified
22380        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
22381        let mut s = three_member_spec();
22382        s.politicas.timeout = None;
22383        s.politicas.retries = Some(3);
22384        s.politicas.circuit_breaker = None;
22385        s.politicas.rate_limit = Some(RateLimit {
22386            rate: 4,
22387            window: Duration::from_secs(1),
22388        });
22389        s.validate()
22390            .expect("rate == retries + 1 is the boundary accept case");
22391    }
22392
22393    #[test]
22394    fn rejects_rate_one_below_retry_burst() {
22395        // Off-by-one boundary pin: exactly one token short of the
22396        // retry burst is still structurally truncating (the invariant
22397        // is `>=`, so `<` refuses even a one-token shortfall).
22398        // `retries = 3` with `rate = 3` means one client's four
22399        // attempts consume four tokens from a three-token bucket —
22400        // the fourth attempt is 429ed. Catches a future relaxation to
22401        // `>` on the wrong side (`rate > retries`, accepting equal)
22402        // that would silently drift the accept boundary and admit a
22403        // structurally-truncated retry policy at the emit boundary.
22404        let mut s = three_member_spec();
22405        s.politicas.timeout = None;
22406        s.politicas.retries = Some(3);
22407        s.politicas.circuit_breaker = None;
22408        s.politicas.rate_limit = Some(RateLimit {
22409            rate: 3,
22410            window: Duration::from_secs(1),
22411        });
22412        assert_eq!(
22413            s.validate().unwrap_err(),
22414            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22415                retries: 3,
22416                rate: 3,
22417            }
22418        );
22419    }
22420
22421    #[test]
22422    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
22423        // The predicate is vacuously `true` when `:retries` is None —
22424        // a `:rate-limit` alone declares a token-bucket rate whose
22425        // per-client attempt count is unconstrained by the substrate,
22426        // so no per-client saturation bound on tokens-per-client-call
22427        // is knowable at author time. The substrate takes no position
22428        // on whether an omitted `:retries` axis means zero retries or
22429        // "the client picks its own retry policy" — either way, the
22430        // pair is undeclared and the cross-axis gate has nothing to
22431        // check. Pin so a future tightening that made the gate
22432        // opinionated on half-declared pairs surfaces here.
22433        let mut s = three_member_spec();
22434        s.politicas.timeout = None;
22435        s.politicas.retries = None;
22436        s.politicas.circuit_breaker = None;
22437        s.politicas.rate_limit = Some(RateLimit {
22438            rate: 1,
22439            window: Duration::from_secs(1),
22440        });
22441        s.validate().expect(
22442            "cross-axis burst gate must be vacuous when :retries is None, \
22443             however low :rate is",
22444        );
22445    }
22446
22447    #[test]
22448    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
22449        // Peer of the sibling `:retries`-absent case: a `:retries`
22450        // without a `:rate-limit` declares a client-retry policy with
22451        // no rate limiter to saturate, so the pair is undeclared and
22452        // the cross-axis gate has nothing to check. Uses
22453        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
22454        // authored retry budget the per-axis cap admits — a `:retries
22455        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
22456        // or not `:rate-limit` is declared.
22457        let mut s = three_member_spec();
22458        s.politicas.timeout = None;
22459        s.politicas.retries = Some(POLICY_RETRIES_MAX);
22460        s.politicas.circuit_breaker = None;
22461        s.politicas.rate_limit = None;
22462        s.validate().expect(
22463            "cross-axis burst gate must be vacuous when :rate-limit is None, \
22464             however high :retries is",
22465        );
22466    }
22467
22468    #[test]
22469    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
22470        // Ordering pin: a pair whose retries is *both* zero-floor-
22471        // violating and structurally below the retry-burst threshold
22472        // must surface the per-axis zero-floor arm first — the
22473        // zero-floor diagnostic is more self-locating (its omit-axis
22474        // remediation is directly named), where the cross-axis arm
22475        // would send the author to reconcile two values one of which
22476        // is not a meaningful retry count at all. Same ordering
22477        // discipline every per-axis bracket carries internally
22478        // (zero-floor before canonical-form before cap), and the
22479        // sibling cross-axis
22480        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
22481        // ordering pin on the `(:retries, :max-failures)` pair.
22482        let mut s = three_member_spec();
22483        s.politicas.timeout = None;
22484        s.politicas.retries = Some(0);
22485        s.politicas.circuit_breaker = None;
22486        s.politicas.rate_limit = Some(RateLimit {
22487            rate: 1,
22488            window: Duration::from_secs(1),
22489        });
22490        assert_eq!(
22491            s.validate().unwrap_err(),
22492            AplicacaoError::PolicyRetriesZero,
22493            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
22494        );
22495    }
22496
22497    #[test]
22498    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
22499        // Cross-axis ordering pin: a `:politicas` whose axes trip
22500        // BOTH cross-axis arms — `:rate-limit` starves the breaker
22501        // within `:window` (the sibling
22502        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
22503        // `:retries + 1` exceeds the bucket capacity (this arm) —
22504        // must surface the rate-limit-starve diagnostic first. The
22505        // starve arm is the token-bucket admission invariant every
22506        // rate-limited edge carries against the breaker whether or
22507        // not `:retries` is declared, so its diagnostic is more
22508        // self-locating; the burst arm reasons across a per-client
22509        // retry-policy budget the starve arm does not touch. Same
22510        // "more foundational cross-axis first" ordering discipline the
22511        // sibling
22512        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
22513        // pin on the peer pair carries.
22514        //
22515        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
22516        // pair trips both: the rate structurally cannot deliver 5
22517        // failures per 10s breaker window (starve arm), and
22518        // simultaneously one client's `retries + 1 = 6` attempts alone
22519        // would exhaust the 1-token bucket (burst arm).
22520        let mut s = three_member_spec();
22521        s.politicas.timeout = None;
22522        s.politicas.retries = Some(5);
22523        s.politicas.circuit_breaker = Some(CircuitBreaker {
22524            max_failures: 5,
22525            window: Duration::from_secs(10),
22526        });
22527        s.politicas.rate_limit = Some(RateLimit {
22528            rate: 1,
22529            window: Duration::from_secs(3600),
22530        });
22531        assert_eq!(
22532            s.validate().unwrap_err(),
22533            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22534                rate: 1,
22535                rl_window: Duration::from_secs(3600),
22536                max_failures: 5,
22537                cb_window: Duration::from_secs(10),
22538            },
22539            "sibling :rate-limit-starve cross-axis arm must fire before the \
22540             burst arm when both apply"
22541        );
22542    }
22543
22544    #[test]
22545    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
22546        // Cross-axis ordering pin: a `:politicas` whose axes trip
22547        // BOTH the retries-saturate arm and this burst arm — one
22548        // client's `retries + 1` failures saturate the breaker's trip
22549        // threshold (the sibling
22550        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
22551        // `retries + 1` exceeds the bucket capacity (this arm) —
22552        // must surface the retries-saturate diagnostic first. The
22553        // saturate arm is the per-client-vs-breaker relation every
22554        // retry-with-breaker pair carries whether or not `:rate-limit`
22555        // is declared, so its diagnostic is more self-locating; the
22556        // burst arm reasons across the rate-limit token-bucket
22557        // admission axis the saturate arm does not touch. Same
22558        // "more foundational cross-axis first" ordering discipline
22559        // carries here.
22560        //
22561        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
22562        // rate: 3/s }` pair trips both: the breaker's `max_failures
22563        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
22564        // one client's `retries + 1 = 6` attempts alone would exhaust
22565        // the 3-token bucket (burst arm). Clears `:timeout` so the
22566        // sibling `:window<:timeout` gate is vacuous, and the
22567        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
22568        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
22569        // the arm that fires first.
22570        let mut s = three_member_spec();
22571        s.politicas.timeout = None;
22572        s.politicas.retries = Some(5);
22573        s.politicas.circuit_breaker = Some(CircuitBreaker {
22574            max_failures: 3,
22575            window: Duration::from_secs(60),
22576        });
22577        s.politicas.rate_limit = Some(RateLimit {
22578            rate: 3,
22579            window: Duration::from_secs(1),
22580        });
22581        assert_eq!(
22582            s.validate().unwrap_err(),
22583            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22584                retries: 5,
22585                max_failures: 3,
22586            },
22587            "sibling :retries-saturate cross-axis arm must fire before the \
22588             burst arm when both apply"
22589        );
22590    }
22591
22592    #[test]
22593    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
22594        // Equivalence pin: the substrate-canonical
22595        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
22596        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
22597        // must discriminate the same set on every pair covered by
22598        // their shared invariant. A future refactor of either side
22599        // that breaks the equivalence trips here rather than as a
22600        // divergence between the predicate's Boolean answer and the
22601        // validate gate's Ok/Err arm — the same predicate-vs-gate
22602        // coherence discipline the three sibling cross-axis
22603        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
22604        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
22605        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
22606        // carry against `AplicacaoSpec::validate_politicas`. The sweep
22607        // covers both arms of the invariant (strictly below, exactly
22608        // at the boundary, strictly above) and both vacuous arms
22609        // (None `:retries`, None `:rate-limit`), so the equivalence
22610        // holds exhaustively over the axis-covered accept and reject
22611        // sets. Clears `:timeout` and `:circuit-breaker` throughout
22612        // so the three sibling cross-axis arms are vacuous on every
22613        // input.
22614        let rl = |rate: u32, secs: u64| {
22615            Some(RateLimit {
22616                rate,
22617                window: Duration::from_secs(secs),
22618            })
22619        };
22620        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
22621            // burst-exceeding pairs (predicate = false, gate = Err)
22622            (Some(3), rl(3, 1)),
22623            (Some(5), rl(1, 1)),
22624            (Some(10), rl(5, 1)),
22625            // boundary + coherent pairs (predicate = true, gate = Ok)
22626            (Some(3), rl(4, 1)),
22627            (Some(1), rl(5, 1)),
22628            (Some(3), rl(1_000_000, 3600)),
22629            // vacuous arms
22630            (None, rl(1, 1)),
22631            (Some(10), None),
22632            (None, None),
22633        ];
22634        for (retries, rate_limit) in cases.iter().copied() {
22635            let politicas = MeshPolicy {
22636                retries,
22637                rate_limit,
22638                ..Default::default()
22639            };
22640            let predicate = politicas.rate_limit_admits_retry_burst();
22641
22642            let mut s = three_member_spec();
22643            s.politicas = politicas.clone();
22644            let gate_ok = !matches!(
22645                s.validate(),
22646                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
22647            );
22648
22649            assert_eq!(
22650                predicate, gate_ok,
22651                "predicate must agree with validate arm on pair \
22652                 (retries={retries:?}, rate_limit={rate_limit:?})"
22653            );
22654        }
22655    }
22656
22657    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
22658    /// equivalence pin — assert that on each `(label, politicas,
22659    /// expected)` case the substrate-canonical fold and the validate
22660    /// cascade agree byte-for-byte. Extracted so each pin's own body
22661    /// stays under `clippy::too_many_lines`.
22662    fn assert_first_cross_axis_violation_agrees_with_gate(
22663        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
22664    ) {
22665        for (label, politicas, expected) in cases {
22666            let fold = politicas.first_cross_axis_violation();
22667            assert_eq!(
22668                fold.as_ref(),
22669                expected.as_ref(),
22670                "fold must return {expected:?} on `{label}`; got {fold:?}"
22671            );
22672
22673            let mut s = three_member_spec();
22674            s.politicas = politicas.clone();
22675            let gate = s.validate();
22676            match expected {
22677                None => {
22678                    // No cross-axis violation: validate must pass (the
22679                    // per-axis brackets pass by construction on every
22680                    // fixture above; every fixture's non-`:politicas`
22681                    // slots come from `three_member_spec`).
22682                    gate.as_ref()
22683                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
22684                }
22685                Some(want) => {
22686                    let got =
22687                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
22688                    assert_eq!(
22689                        &got, want,
22690                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
22691                    );
22692                }
22693            }
22694        }
22695    }
22696
22697    #[test]
22698    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
22699        // Equivalence pin on the compound cross-axis fold: the
22700        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
22701        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
22702        // cascade must return identical `AplicacaoError` variants on
22703        // every axis-covered input — the "compound-fold ≡ gate"
22704        // contract that generalizes the four sibling per-arm pins
22705        // onto the compound primitive that folds all four. A future
22706        // refactor of either side that breaks the equivalence trips
22707        // here rather than as a divergence between what the substrate
22708        // primitive answers and what `feira build` accepts.
22709        //
22710        // Half-A of the sweep: every single-arm violation (one arm
22711        // fires with the three sibling arms vacuous), the vacuous
22712        // shape (empty policy — no arm fires), and the fully-coherent
22713        // shape (every axis declared inside the coherence surface —
22714        // no arm fires). Half-B (pairwise-ordering coverage — the
22715        // "which arm wins when two apply" contract) lives in the
22716        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
22717        // pin; splitting keeps each pin's body under
22718        // `clippy::too_many_lines`.
22719        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
22720            max_failures,
22721            window: Duration::from_secs(secs),
22722        };
22723        let rl = |rate: u32, secs: u64| RateLimit {
22724            rate,
22725            window: Duration::from_secs(secs),
22726        };
22727        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22728            (
22729                "window-below-timeout only",
22730                MeshPolicy {
22731                    timeout: Some(Duration::from_secs(30)),
22732                    circuit_breaker: Some(cb(5, 10)),
22733                    ..Default::default()
22734                },
22735                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22736                    window: Duration::from_secs(10),
22737                    timeout: Duration::from_secs(30),
22738                }),
22739            ),
22740            (
22741                "starve only",
22742                MeshPolicy {
22743                    rate_limit: Some(rl(1, 3600)),
22744                    circuit_breaker: Some(cb(5, 10)),
22745                    ..Default::default()
22746                },
22747                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22748                    rate: 1,
22749                    rl_window: Duration::from_secs(3600),
22750                    max_failures: 5,
22751                    cb_window: Duration::from_secs(10),
22752                }),
22753            ),
22754            (
22755                "retries-saturate only",
22756                MeshPolicy {
22757                    retries: Some(3),
22758                    circuit_breaker: Some(cb(3, 60)),
22759                    ..Default::default()
22760                },
22761                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22762                    retries: 3,
22763                    max_failures: 3,
22764                }),
22765            ),
22766            (
22767                "retries-burst only",
22768                MeshPolicy {
22769                    retries: Some(5),
22770                    rate_limit: Some(rl(3, 1)),
22771                    ..Default::default()
22772                },
22773                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
22774                    retries: 5,
22775                    rate: 3,
22776                }),
22777            ),
22778            ("empty policy", MeshPolicy::default(), None),
22779            (
22780                "fully-coherent policy",
22781                MeshPolicy {
22782                    timeout: Some(Duration::from_secs(30)),
22783                    retries: Some(3),
22784                    circuit_breaker: Some(cb(5, 60)),
22785                    mtls_required: Some(true),
22786                    rate_limit: Some(rl(100, 1)),
22787                },
22788                None,
22789            ),
22790        ];
22791        assert_first_cross_axis_violation_agrees_with_gate(cases);
22792    }
22793
22794    #[test]
22795    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
22796        // Half-B of the compound-fold ≡ gate equivalence pin: the
22797        // load-bearing pairwise-ordering coverage. Every ordered pair
22798        // of the four cross-axis arms — six combinations — where two
22799        // arms are simultaneously eligible must surface the
22800        // more-foundational arm's diagnostic verbatim. Pins the fold's
22801        // arm-ordering byte-for-byte against the validate cascade's
22802        // arm-ordering, so a future reshuffle of either side that
22803        // silently drifts the ordering trips here rather than as a
22804        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
22805        // pins cannot catch (they clear every sibling arm, so their
22806        // sweeps are pairwise-ordering-agnostic by construction).
22807        //
22808        // The six pairs the four-arm cascade admits:
22809        // window-before-starve, window-before-saturate,
22810        // window-before-burst, starve-before-saturate,
22811        // starve-before-burst, saturate-before-burst.
22812        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
22813            max_failures,
22814            window: Duration::from_secs(secs),
22815        };
22816        let rl = |rate: u32, secs: u64| RateLimit {
22817            rate,
22818            window: Duration::from_secs(secs),
22819        };
22820        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22821            (
22822                "window+starve → window wins",
22823                MeshPolicy {
22824                    timeout: Some(Duration::from_secs(30)),
22825                    rate_limit: Some(rl(1, 3600)),
22826                    circuit_breaker: Some(cb(5, 10)),
22827                    ..Default::default()
22828                },
22829                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22830                    window: Duration::from_secs(10),
22831                    timeout: Duration::from_secs(30),
22832                }),
22833            ),
22834            (
22835                "window+retries-saturate → window wins",
22836                MeshPolicy {
22837                    timeout: Some(Duration::from_secs(30)),
22838                    retries: Some(5),
22839                    circuit_breaker: Some(cb(3, 10)),
22840                    ..Default::default()
22841                },
22842                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22843                    window: Duration::from_secs(10),
22844                    timeout: Duration::from_secs(30),
22845                }),
22846            ),
22847            (
22848                "window+retries-burst → window wins",
22849                MeshPolicy {
22850                    timeout: Some(Duration::from_secs(30)),
22851                    retries: Some(5),
22852                    rate_limit: Some(rl(3, 1)),
22853                    circuit_breaker: Some(cb(5, 10)),
22854                    ..Default::default()
22855                },
22856                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
22857                    window: Duration::from_secs(10),
22858                    timeout: Duration::from_secs(30),
22859                }),
22860            ),
22861            (
22862                "starve+retries-saturate → starve wins",
22863                MeshPolicy {
22864                    retries: Some(5),
22865                    rate_limit: Some(rl(1, 3600)),
22866                    circuit_breaker: Some(cb(5, 10)),
22867                    ..Default::default()
22868                },
22869                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22870                    rate: 1,
22871                    rl_window: Duration::from_secs(3600),
22872                    max_failures: 5,
22873                    cb_window: Duration::from_secs(10),
22874                }),
22875            ),
22876            (
22877                "starve+retries-burst → starve wins",
22878                MeshPolicy {
22879                    retries: Some(5),
22880                    rate_limit: Some(rl(1, 3600)),
22881                    circuit_breaker: Some(cb(10, 10)),
22882                    ..Default::default()
22883                },
22884                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22885                    rate: 1,
22886                    rl_window: Duration::from_secs(3600),
22887                    max_failures: 10,
22888                    cb_window: Duration::from_secs(10),
22889                }),
22890            ),
22891            (
22892                "retries-saturate+retries-burst → saturate wins",
22893                MeshPolicy {
22894                    retries: Some(5),
22895                    rate_limit: Some(rl(3, 1)),
22896                    circuit_breaker: Some(cb(3, 60)),
22897                    ..Default::default()
22898                },
22899                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22900                    retries: 5,
22901                    max_failures: 3,
22902                }),
22903            ),
22904        ];
22905        assert_first_cross_axis_violation_agrees_with_gate(cases);
22906    }
22907
22908    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
22909    /// equivalence pin — assert that on each `(label, politicas,
22910    /// expected)` case both the substrate primitive
22911    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
22912    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
22913    /// same `three_member_spec` fixture whose non-`:politicas` slots
22914    /// always validate cleanly) return identical `AplicacaoError` variants.
22915    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
22916    /// the sibling cross-axis-only surface — extended here onto the
22917    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
22918    /// own body stays under `clippy::too_many_lines`.
22919    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
22920        for (label, politicas, expected) in cases {
22921            let direct = politicas.validate();
22922            match (expected, &direct) {
22923                (None, Ok(())) => {}
22924                (None, Err(got)) => {
22925                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
22926                }
22927                (Some(want), Ok(())) => {
22928                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
22929                }
22930                (Some(want), Err(got)) => assert_eq!(
22931                    got, want,
22932                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
22933                ),
22934            }
22935
22936            let mut s = three_member_spec();
22937            s.politicas = politicas.clone();
22938            let gate = s.validate();
22939            match (expected, &gate) {
22940                (None, Ok(())) => {}
22941                (None, Err(got)) => {
22942                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
22943                }
22944                (Some(want), Ok(())) => {
22945                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
22946                }
22947                (Some(want), Err(got)) => assert_eq!(
22948                    got, want,
22949                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
22950                ),
22951            }
22952        }
22953    }
22954
22955    #[test]
22956    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
22957        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
22958        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
22959        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
22960        // :max-failures`, `:rate-limit` rate) that discriminate the
22961        // "per-axis phase fires" arm of the compound gate, plus one
22962        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
22963        // ZERO }`) that pins the phase-boundary ordering — the per-axis
22964        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
22965        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
22966        // diagnostic wins over the window-below-timeout diagnostic. Peer
22967        // of the sibling
22968        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
22969        // + `_on_pairwise_orderings` pins on the compound cross-axis
22970        // fold, extended here onto the outer compound entry gate that
22971        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
22972        // clean-pass surfaces) lives in the sibling
22973        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
22974        // pin; splitting keeps each pin's body under
22975        // `clippy::too_many_lines`.
22976        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
22977            (
22978                "per-axis: timeout zero",
22979                MeshPolicy {
22980                    timeout: Some(Duration::ZERO),
22981                    ..Default::default()
22982                },
22983                Some(AplicacaoError::PolicyTimeoutZero),
22984            ),
22985            (
22986                "per-axis: retries zero",
22987                MeshPolicy {
22988                    retries: Some(0),
22989                    ..Default::default()
22990                },
22991                Some(AplicacaoError::PolicyRetriesZero),
22992            ),
22993            (
22994                "per-axis: breaker max-failures zero",
22995                MeshPolicy {
22996                    circuit_breaker: Some(CircuitBreaker {
22997                        max_failures: 0,
22998                        window: Duration::from_secs(60),
22999                    }),
23000                    ..Default::default()
23001                },
23002                Some(AplicacaoError::PolicyBreakerZeroFailures),
23003            ),
23004            (
23005                "per-axis: rate-limit rate zero",
23006                MeshPolicy {
23007                    rate_limit: Some(RateLimit {
23008                        rate: 0,
23009                        window: Duration::from_secs(1),
23010                    }),
23011                    ..Default::default()
23012                },
23013                Some(AplicacaoError::PolicyRateLimitZero),
23014            ),
23015            (
23016                "per-axis before cross-axis: zero-window wins over window-below-timeout",
23017                MeshPolicy {
23018                    timeout: Some(Duration::from_secs(30)),
23019                    circuit_breaker: Some(CircuitBreaker {
23020                        max_failures: 5,
23021                        window: Duration::ZERO,
23022                    }),
23023                    ..Default::default()
23024                },
23025                Some(AplicacaoError::PolicyBreakerZeroWindow),
23026            ),
23027        ];
23028        assert_validate_matches_gate(cases);
23029    }
23030
23031    #[test]
23032    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
23033        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
23034        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
23035        // arm that discriminates the "cross-axis phase fires" arm of
23036        // the compound gate (window-below-timeout — sibling per-arm
23037        // coverage lives in the two
23038        // `first_cross_axis_violation_matches_gate_on_*` pins above),
23039        // plus the two clean-pass shapes (empty policy — every axis
23040        // absent — and fully-coherent — every axis inside the coherence
23041        // surface) that pin the compound gate's `Ok(())` arm. Half-A
23042        // (per-axis + phase-boundary surfaces) lives in the sibling
23043        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
23044        // pin; splitting keeps each pin's body under
23045        // `clippy::too_many_lines`.
23046        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23047            (
23048                "cross-axis: window-below-timeout",
23049                MeshPolicy {
23050                    timeout: Some(Duration::from_secs(30)),
23051                    circuit_breaker: Some(CircuitBreaker {
23052                        max_failures: 5,
23053                        window: Duration::from_secs(10),
23054                    }),
23055                    ..Default::default()
23056                },
23057                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23058                    window: Duration::from_secs(10),
23059                    timeout: Duration::from_secs(30),
23060                }),
23061            ),
23062            ("clean pass: empty policy", MeshPolicy::default(), None),
23063            (
23064                "clean pass: every axis coherent",
23065                MeshPolicy {
23066                    timeout: Some(Duration::from_secs(30)),
23067                    retries: Some(3),
23068                    circuit_breaker: Some(CircuitBreaker {
23069                        max_failures: 5,
23070                        window: Duration::from_secs(60),
23071                    }),
23072                    mtls_required: Some(true),
23073                    rate_limit: Some(RateLimit {
23074                        rate: 100,
23075                        window: Duration::from_secs(1),
23076                    }),
23077                },
23078                None,
23079            ),
23080        ];
23081        assert_validate_matches_gate(cases);
23082    }
23083
23084    #[test]
23085    fn empty_politicas_validates() {
23086        // Omitting every policy axis is fine — defaults express "no
23087        // policy on this axis", not "policy = 0". The fixture's typical
23088        // values continue to validate; this test pins that
23089        // MeshPolicy::default() is a clean pass through validate().
23090        let mut s = three_member_spec();
23091        s.politicas = MeshPolicy::default();
23092        s.validate().unwrap();
23093    }
23094
23095    #[test]
23096    fn typical_politicas_validates_with_every_axis_set() {
23097        // The full §III.1 example block (timeout + retries + breaker +
23098        // mtls + rate-limit) — every axis nonzero — must remain a
23099        // clean pass.
23100        let mut s = three_member_spec();
23101        s.politicas = MeshPolicy {
23102            timeout: Some(Duration::from_secs(30)),
23103            retries: Some(3),
23104            circuit_breaker: Some(CircuitBreaker {
23105                max_failures: 5,
23106                window: Duration::from_secs(60),
23107            }),
23108            mtls_required: Some(true),
23109            rate_limit: Some(RateLimit {
23110                rate: 100,
23111                window: Duration::from_secs(1),
23112            }),
23113        };
23114        s.validate().unwrap();
23115    }
23116
23117    #[test]
23118    fn rejects_empty_cluster_name() {
23119        let mut s = three_member_spec();
23120        s.placement.clusters = vec!["rio".into(), String::new()];
23121        assert_eq!(
23122            s.validate().unwrap_err(),
23123            AplicacaoError::PlacementClusterEmpty
23124        );
23125    }
23126
23127    #[test]
23128    fn rejects_duplicate_cluster_names() {
23129        let mut s = three_member_spec();
23130        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
23131        let err = s.validate().unwrap_err();
23132        assert!(
23133            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
23134            "got {err:?}"
23135        );
23136    }
23137
23138    #[test]
23139    fn rejects_placement_cluster_with_uppercase() {
23140        // The canonical "I copied the cluster's display name verbatim"
23141        // typo — K8s context names are lowercase per DNS-1123 label
23142        // rule, but org docs often round-trip a TitleCase identifier
23143        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
23144        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
23145        // on the peer name axis.
23146        let mut s = three_member_spec();
23147        s.placement.clusters = vec!["Rio".into(), "mar".into()];
23148        let err = s.validate().unwrap_err();
23149        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
23150            panic!("expected PlacementClusterInvalid, got other variant");
23151        };
23152        assert_eq!(cluster, "Rio");
23153        assert!(
23154            reason.contains("uppercase"),
23155            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
23156        );
23157        assert!(
23158            reason.contains("\"rio\""),
23159            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
23160        );
23161    }
23162
23163    #[test]
23164    fn rejects_placement_cluster_with_underscore() {
23165        // The canonical "I'm thinking of an env var / hostname slug"
23166        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
23167        // schema. K8s context filtering on `my_cluster` silently misses
23168        // the cluster the author intended; the gate moves it to caixa-
23169        // build time. Same shape as `rejects_membro_caixa_with_underscore`
23170        // (3f9d7a0).
23171        let mut s = three_member_spec();
23172        s.placement.clusters = vec!["my_cluster".into()];
23173        let err = s.validate().unwrap_err();
23174        assert!(
23175            matches!(
23176                err,
23177                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
23178                    if cluster == "my_cluster" && reason.contains('_')
23179            ),
23180            "got {err:?}"
23181        );
23182    }
23183
23184    #[test]
23185    fn rejects_placement_cluster_with_dot() {
23186        // A `:placement :clusters` entry is a single DNS-1123 *label*,
23187        // not a subdomain — even though K8s context names sometimes
23188        // carry a dotted form via kubeconfig conventions, the strictest
23189        // floor among the use sites (DNS-1035 cluster.x-k8s.io
23190        // `metadata.name`, Cilium identity label values) wins. The "I
23191        // want to namespace my cluster names with `.`" intent is
23192        // expressed via `-` (`mar-east`).
23193        let mut s = three_member_spec();
23194        s.placement.clusters = vec!["team.rio".into()];
23195        let err = s.validate().unwrap_err();
23196        assert!(
23197            matches!(
23198                err,
23199                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
23200                    if cluster == "team.rio" && reason.contains('.')
23201            ),
23202            "got {err:?}"
23203        );
23204    }
23205
23206    #[test]
23207    fn rejects_placement_cluster_with_leading_hyphen() {
23208        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
23209        // with an alphanumeric. The K8s apiserver rejects `-rio`
23210        // outright; the rendered fan-out would emit a `metadata.name:
23211        // "-rio"` that fails admission far from the source caixa.lisp.
23212        let mut s = three_member_spec();
23213        s.placement.clusters = vec!["-rio".into()];
23214        let err = s.validate().unwrap_err();
23215        assert!(
23216            matches!(
23217                err,
23218                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
23219                    if cluster == "-rio" && reason.contains("start and end")
23220            ),
23221            "got {err:?}"
23222        );
23223    }
23224
23225    #[test]
23226    fn rejects_placement_cluster_with_trailing_hyphen() {
23227        // The symmetric arm of the boundary rule. Pin separately so
23228        // both ends are covered against a future relaxation that only
23229        // checks one boundary (parallel to
23230        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
23231        let mut s = three_member_spec();
23232        s.placement.clusters = vec!["rio-".into()];
23233        let err = s.validate().unwrap_err();
23234        assert!(
23235            matches!(
23236                err,
23237                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23238                    if cluster == "rio-"
23239            ),
23240            "got {err:?}"
23241        );
23242    }
23243
23244    #[test]
23245    fn rejects_placement_cluster_with_unicode() {
23246        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
23247        // before it reaches K8s. The byte-by-byte ASCII validity check
23248        // rejects multi-byte UTF-8 sequences by the first byte that
23249        // fails `[a-z0-9-]`.
23250        let mut s = three_member_spec();
23251        s.placement.clusters = vec!["rió".into()];
23252        let err = s.validate().unwrap_err();
23253        assert!(
23254            matches!(
23255                err,
23256                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23257                    if cluster == "rió"
23258            ),
23259            "got {err:?}"
23260        );
23261    }
23262
23263    #[test]
23264    fn rejects_placement_cluster_with_whitespace() {
23265        // Whitespace is the canonical "I pasted from a sketch / doc"
23266        // footgun. The apiserver rejects every cluster `metadata.name`
23267        // value carrying whitespace.
23268        let mut s = three_member_spec();
23269        s.placement.clusters = vec!["rio cluster".into()];
23270        let err = s.validate().unwrap_err();
23271        assert!(
23272            matches!(
23273                err,
23274                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
23275                    if cluster == "rio cluster"
23276            ),
23277            "got {err:?}"
23278        );
23279    }
23280
23281    #[test]
23282    fn rejects_placement_cluster_too_long() {
23283        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
23284        // pin. The diagnostic names both the cap (63) and the actual
23285        // length so the author can shorten in one edit. Mirrors
23286        // `rejects_membro_caixa_too_long` (3f9d7a0).
23287        let mut s = three_member_spec();
23288        let too_long = "a".repeat(64);
23289        s.placement.clusters = vec![too_long.clone()];
23290        let err = s.validate().unwrap_err();
23291        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
23292            panic!("expected PlacementClusterInvalid");
23293        };
23294        assert_eq!(cluster, too_long);
23295        assert!(
23296            reason.contains("63") && reason.contains("64"),
23297            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23298        );
23299    }
23300
23301    #[test]
23302    fn placement_cluster_max_length_validates() {
23303        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
23304        // future tightening (e.g. dropping to 62) surfaces here as a
23305        // regression, mirroring `membro_caixa_max_length_validates`
23306        // (3f9d7a0).
23307        let mut s = three_member_spec();
23308        s.placement.clusters = vec!["a".repeat(63)];
23309        s.validate().unwrap();
23310    }
23311
23312    #[test]
23313    fn accepts_canonical_placement_cluster_forms() {
23314        // The DNS-1123 label shapes a caixa author is realistically
23315        // going to write for cluster names: single-word lowercase
23316        // (`rio`), regional hyphen-joined (`mar-east`), single
23317        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
23318        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
23319        // Pin every leg so a future tightening that bans (e.g.) digit-
23320        // start identifiers surfaces here.
23321        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
23322            let mut s = three_member_spec();
23323            s.placement.clusters = vec![form.into()];
23324            s.validate().unwrap_or_else(|e| {
23325                panic!("canonical cluster form {form:?} must validate, got {e:?}")
23326            });
23327        }
23328    }
23329
23330    #[test]
23331    fn placement_cluster_empty_takes_precedence_over_invalid() {
23332        // Order pin: the existing `PlacementClusterEmpty` diagnostic
23333        // (which doesn't try to parse) fires before the new
23334        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
23335        // `:clusters` entry keeps its narrower error message — the new
23336        // gate would also reject `""`, but the empty-string arm is the
23337        // more self-locating diagnostic. Mirrors the
23338        // `membro_caixa_empty_takes_precedence_over_invalid` pin
23339        // (3f9d7a0).
23340        let mut s = three_member_spec();
23341        s.placement.clusters = vec!["rio".into(), String::new()];
23342        let err = s.validate().unwrap_err();
23343        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
23344    }
23345
23346    #[test]
23347    fn placement_cluster_invalid_fires_before_duplicate_check() {
23348        // Order pin: a malformed-shape `:clusters` entry surfaces *its
23349        // own* diagnostic, even when a later entry would otherwise
23350        // collapse onto a duplicate name. The per-entry shape gate runs
23351        // inline before the duplicate-key insert, parallel to
23352        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
23353        let mut s = three_member_spec();
23354        s.placement.clusters = vec!["Rio".into(), "rio".into()];
23355        let err = s.validate().unwrap_err();
23356        assert!(
23357            matches!(
23358                err,
23359                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
23360            ),
23361            "got {err:?}"
23362        );
23363    }
23364
23365    #[test]
23366    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
23367        // The diagnostic-shape pin: the error names the offending
23368        // `:clusters` value verbatim so the author can grep their
23369        // caixa.lisp without re-running the build, and carries a
23370        // non-empty `reason` naming the specific violation. Same shape
23371        // every typed-shape gate enshrines
23372        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
23373        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
23374        let mut s = three_member_spec();
23375        s.placement.clusters = vec!["BAD_CLUSTER".into()];
23376        let err = s.validate().unwrap_err();
23377        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
23378            panic!("expected PlacementClusterInvalid");
23379        };
23380        assert_eq!(cluster, "BAD_CLUSTER");
23381        assert!(
23382            !reason.is_empty(),
23383            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
23384        );
23385    }
23386
23387    #[test]
23388    fn rejects_sharded_with_empty_clusters() {
23389        // §III.1: Sharded uses :clusters as the shard pool. An empty
23390        // pool means "shard across no clusters" — meaningless, same as
23391        // Replicated with no hosts.
23392        let mut s = three_member_spec();
23393        s.placement.estrategia = PlacementStrategy::Sharded;
23394        s.placement.shard_key = Some("$tenantId".into());
23395        s.placement.clusters = vec![];
23396        assert!(matches!(
23397            s.validate().unwrap_err(),
23398            AplicacaoError::PlacementWithoutClusters {
23399                estrategia: PlacementStrategy::Sharded
23400            }
23401        ));
23402    }
23403
23404    #[test]
23405    fn rejects_sharded_with_empty_shard_key() {
23406        let mut s = three_member_spec();
23407        s.placement.estrategia = PlacementStrategy::Sharded;
23408        s.placement.shard_key = Some(String::new());
23409        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
23410    }
23411
23412    #[test]
23413    fn rejects_shard_key_under_replicated_strategy() {
23414        // The fail-before-pass-after pin: a `:placement (:estrategia
23415        // Replicated :shard-key "tenantId")` manifest carries the
23416        // hash-keyed-distribution slot on a strategy that never consumes
23417        // it. Before the gate the typed slot's value silently vanished
23418        // at the renderer layer (caixa-mesh emits `placement.shardKey`
23419        // verbatim regardless of strategy; the Akka-style cluster-
23420        // sharding reconciler keys off `estrategia == Sharded` and
23421        // ignores the slot otherwise), with no diagnostic. Lifting the
23422        // rejection to a build-time gate makes the
23423        // `shard_key.is_some() == matches!(estrategia, Sharded)`
23424        // partition a structural property of every validated
23425        // [`Placement`].
23426        let mut s = three_member_spec();
23427        // The fixture already uses Replicated; just add a shard-key.
23428        s.placement.shard_key = Some("$tenantId".into());
23429        let err = s.validate().unwrap_err();
23430        let AplicacaoError::ShardKeyOnNonSharded {
23431            estrategia,
23432            shard_key,
23433        } = err
23434        else {
23435            panic!("expected ShardKeyOnNonSharded, got {err:?}");
23436        };
23437        assert_eq!(estrategia, PlacementStrategy::Replicated);
23438        assert_eq!(shard_key, "$tenantId");
23439    }
23440
23441    #[test]
23442    fn rejects_shard_key_under_singlenode_strategy() {
23443        // Peer of the Replicated case above on the SingleNode arm: OTP
23444        // distributed-app takeover (one cluster runs at a time) has no
23445        // hash-keyed routing axis to consume `:shard-key` either, so
23446        // the rejection fires on both non-Sharded arms uniformly.
23447        let mut s = three_member_spec();
23448        s.placement.estrategia = PlacementStrategy::SingleNode;
23449        s.placement.shard_key = Some("$tenantId".into());
23450        let err = s.validate().unwrap_err();
23451        let AplicacaoError::ShardKeyOnNonSharded {
23452            estrategia,
23453            shard_key,
23454        } = err
23455        else {
23456            panic!("expected ShardKeyOnNonSharded, got {err:?}");
23457        };
23458        assert_eq!(estrategia, PlacementStrategy::SingleNode);
23459        assert_eq!(shard_key, "$tenantId");
23460    }
23461
23462    #[test]
23463    fn rejects_empty_shard_key_under_replicated_strategy() {
23464        // The `Some("")` case under non-Sharded is rejected by
23465        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
23466        // fires before the empty-value gate), not
23467        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
23468        // the `Sharded` arm). Pin the partition so a future reorder of
23469        // the validate_placement match arms doesn't silently swap which
23470        // diagnostic the author sees — both are author errors, but
23471        // ShardKeyOnNonSharded names which strategy is the actual fix
23472        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
23473        // only says "pick a non-empty key".
23474        let mut s = three_member_spec();
23475        s.placement.shard_key = Some(String::new());
23476        let err = s.validate().unwrap_err();
23477        assert!(
23478            matches!(
23479                err,
23480                AplicacaoError::ShardKeyOnNonSharded {
23481                    estrategia: PlacementStrategy::Replicated,
23482                    ref shard_key,
23483                } if shard_key.is_empty()
23484            ),
23485            "got {err:?}"
23486        );
23487    }
23488
23489    #[test]
23490    fn replicated_without_shard_key_validates() {
23491        // The complement of the rejection: `:placement :estrategia
23492        // Replicated` with `:shard-key None` is the canonical happy
23493        // path on every existing fixture. Pin the no-shard-key case so
23494        // the new gate doesn't accidentally fire on `None`.
23495        let mut s = three_member_spec();
23496        assert!(matches!(
23497            s.placement.estrategia,
23498            PlacementStrategy::Replicated
23499        ));
23500        s.placement.shard_key = None;
23501        s.validate().unwrap();
23502    }
23503
23504    #[test]
23505    fn singlenode_without_shard_key_validates() {
23506        // Peer of the Replicated no-shard-key case on the SingleNode
23507        // arm — both non-Sharded strategies must validate cleanly when
23508        // the slot is omitted.
23509        let mut s = three_member_spec();
23510        s.placement.estrategia = PlacementStrategy::SingleNode;
23511        s.placement.shard_key = None;
23512        s.validate().unwrap();
23513    }
23514
23515    #[test]
23516    fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
23517        // Fail-before-pass-after pin on
23518        // [`AplicacaoError::shard_key_on_non_sharded`]'s
23519        // substrate-primitive posture: byte-identity + `Display`
23520        // byte-string parity against the open-coded struct-literal
23521        // for every non-`Sharded` [`PlacementStrategy`] arm across a
23522        // representative `:shard-key` value the sole in-crate wire-up
23523        // site (`AplicacaoSpec::validate_placement`'s
23524        // `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
23525        // arm) emits. Any wrapper-side silent normalization, `.into()`
23526        // divergence, or accidental field rebrand on the ctor body
23527        // surfaces at assert time rather than at a downstream consumer
23528        // that reads `err.estrategia` / `err.shard_key` back and gets a
23529        // different value than the one it stored.
23530        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23531            let placement = Placement {
23532                estrategia,
23533                clusters: vec!["cluster-a".to_string()],
23534                shard_key: Some("$tenantId".to_string()),
23535                affinity: None,
23536            };
23537            let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
23538            let via_literal = AplicacaoError::ShardKeyOnNonSharded {
23539                estrategia,
23540                shard_key: "$tenantId".to_string(),
23541            };
23542            assert_eq!(
23543                via_ctor, via_literal,
23544                "shard_key_on_non_sharded(&placement, k) must byte-equal the \
23545                 open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
23546            );
23547            assert_eq!(
23548                via_ctor.to_string(),
23549                via_literal.to_string(),
23550                "Display byte-string must byte-equal the open-coded struct-literal \
23551                 for {estrategia:?}"
23552            );
23553        }
23554    }
23555
23556    #[test]
23557    fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
23558        // Boundary-sweep pin on the ctor's substrate-primitive
23559        // projection: the `estrategia` slot is stored verbatim from
23560        // [`Placement::estrategia`] on every arm the accessor can
23561        // return, and the `shard_key` slot preserves the caller-side
23562        // `&str` byte-for-byte. Sweeping every arm of
23563        // [`PlacementStrategy::ALL`] (including the `Sharded` arm the
23564        // current caller never reaches, since the ctor is a substrate
23565        // primitive independent of any single caller's dispatch gate)
23566        // catches a future silent field-rebrand or per-arm ctor
23567        // divergence at caixa-core build time rather than at a
23568        // downstream consumer far from the wire-up commit.
23569        for &estrategia in PlacementStrategy::ALL {
23570            let placement = Placement {
23571                estrategia,
23572                clusters: vec!["cluster-a".to_string()],
23573                shard_key: Some("$tenantId".to_string()),
23574                affinity: None,
23575            };
23576            let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
23577            let AplicacaoError::ShardKeyOnNonSharded {
23578                estrategia: stored_estrategia,
23579                shard_key: stored_shard_key,
23580            } = err
23581            else {
23582                panic!(
23583                    "shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
23584                );
23585            };
23586            assert_eq!(
23587                stored_estrategia, estrategia,
23588                "estrategia slot must round-trip verbatim through Placement::estrategia \
23589                 for {estrategia:?}"
23590            );
23591            assert_eq!(
23592                stored_shard_key, "$tenantId",
23593                "shard_key slot must preserve the caller-side &str byte-for-byte \
23594                 for {estrategia:?}"
23595            );
23596        }
23597    }
23598
23599    #[test]
23600    fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
23601        // End-to-end pin: the sole in-crate wire-up site
23602        // (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
23603        // refusal) routes through
23604        // [`AplicacaoError::shard_key_on_non_sharded`] and the observed
23605        // `Err` byte-equals the ctor's output on the same non-`Sharded`
23606        // fixture. A future silent de-lift of the wire-up back to the
23607        // open-coded struct-literal trips this test at caixa-core build
23608        // time rather than at a downstream diagnostic consumer far from
23609        // the wire-up commit.
23610        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23611            let mut s = three_member_spec();
23612            s.placement.estrategia = estrategia;
23613            s.placement.shard_key = Some("$tenantId".to_string());
23614            let observed = s.validate().unwrap_err();
23615            let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
23616            assert_eq!(
23617                observed, expected,
23618                "validate_placement's non-Sharded-arm Err must byte-equal \
23619                 shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
23620            );
23621            assert_eq!(
23622                observed.to_string(),
23623                expected.to_string(),
23624                "Display byte-string parity for {estrategia:?}"
23625            );
23626        }
23627    }
23628
23629    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
23630        // Fixture builder for the `:placement :shard-key` shape gate
23631        // tests: a three-member Aplicacao on the `Sharded` strategy
23632        // with the supplied `:shard-key` slot. Co-locates the
23633        // arm-construction so every test below carries one line of
23634        // setup (the offending `:shard-key` value) and the assertion.
23635        let mut s = three_member_spec();
23636        s.placement.estrategia = PlacementStrategy::Sharded;
23637        s.placement.shard_key = Some(key.into());
23638        s
23639    }
23640
23641    #[test]
23642    fn rejects_shard_key_with_embedded_space() {
23643        // The canonical paste-from-aligned-doc footgun:
23644        // `:shard-key "$tenant Id"` — the Akka-style entity-id
23645        // extractor reads the slot as a single-token reference, and an
23646        // embedded space breaks the token boundary at the runtime
23647        // hash-extractor pass with no diagnostic naming the offending
23648        // entry.
23649        let s = sharded_spec_with_key("$tenant Id");
23650        let err = s.validate().unwrap_err();
23651        assert!(
23652            matches!(
23653                err,
23654                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23655                    if shard_key == "$tenant Id" && reason.contains("space")
23656            ),
23657            "got {err:?}"
23658        );
23659    }
23660
23661    #[test]
23662    fn rejects_shard_key_with_leading_space() {
23663        // Leading-space arm of the embedded-whitespace footgun — the
23664        // paste-from-aligned-doc / paste-from-CSV-cell variant where
23665        // the leading column-padding leaked into the slot.
23666        let s = sharded_spec_with_key(" $tenantId");
23667        let err = s.validate().unwrap_err();
23668        assert!(
23669            matches!(
23670                err,
23671                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
23672                    if shard_key == " $tenantId"
23673            ),
23674            "got {err:?}"
23675        );
23676    }
23677
23678    #[test]
23679    fn rejects_shard_key_with_trailing_newline() {
23680        // The canonical paste-from-shell-heredoc footgun — every
23681        // `<<EOF` heredoc terminator paste leaves a trailing newline
23682        // the YAML emitter then folds away inconsistently across
23683        // emitter implementations.
23684        let s = sharded_spec_with_key("$tenantId\n");
23685        let err = s.validate().unwrap_err();
23686        assert!(
23687            matches!(
23688                err,
23689                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23690                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
23691            ),
23692            "got {err:?}"
23693        );
23694    }
23695
23696    #[test]
23697    fn rejects_shard_key_with_embedded_tab() {
23698        // The paste-from-aligned-doc tab-stop variant — tabs land
23699        // alongside spaces in copy-paste from formatted columns.
23700        let s = sharded_spec_with_key("$tenant\tId");
23701        let err = s.validate().unwrap_err();
23702        assert!(
23703            matches!(
23704                err,
23705                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23706                    if shard_key == "$tenant\tId" && reason.contains("tab")
23707            ),
23708            "got {err:?}"
23709        );
23710    }
23711
23712    #[test]
23713    fn rejects_shard_key_with_control_character() {
23714        // The paste-from-binary / paste-from-screen-cleared-terminal
23715        // footgun — an embedded `\x01` (SOH) byte that some YAML
23716        // emitters silently strip and others escape as ``,
23717        // breaking round-trip across emitter implementations.
23718        let s = sharded_spec_with_key("$tenant\u{0001}Id");
23719        let err = s.validate().unwrap_err();
23720        assert!(
23721            matches!(
23722                err,
23723                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23724                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
23725            ),
23726            "got {err:?}"
23727        );
23728    }
23729
23730    #[test]
23731    fn rejects_shard_key_with_non_ascii() {
23732        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
23733        // footgun — non-ASCII bytes normalize differently between the
23734        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
23735        // YAML parser, the same entity ID can silently map to two
23736        // distinct shards on a re-render.
23737        let s = sharded_spec_with_key("$tenàntId");
23738        let err = s.validate().unwrap_err();
23739        assert!(
23740            matches!(
23741                err,
23742                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
23743                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
23744            ),
23745            "got {err:?}"
23746        );
23747    }
23748
23749    #[test]
23750    fn rejects_shard_key_too_long() {
23751        // Length cap pin: 64 bytes — one byte over the
23752        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
23753        // here is a paste-from-doc multi-line blob landing in
23754        // `:shard-key` instead of a single-token extractor expression.
23755        let too_long = "a".repeat(64);
23756        let s = sharded_spec_with_key(&too_long);
23757        let err = s.validate().unwrap_err();
23758        let AplicacaoError::ShardKeyInvalid {
23759            ref shard_key,
23760            ref reason,
23761        } = err
23762        else {
23763            panic!("expected ShardKeyInvalid, got {err:?}");
23764        };
23765        assert_eq!(shard_key, &too_long);
23766        assert!(
23767            reason.contains("63") && reason.contains("64"),
23768            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
23769        );
23770    }
23771
23772    #[test]
23773    fn shard_key_max_length_validates() {
23774        // Boundary pin: 63 bytes exactly — the
23775        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
23776        // dropping to 62) surfaces here as a regression, mirroring
23777        // `placement_cluster_max_length_validates` /
23778        // `placement_affinity_max_length_validates` on the peer
23779        // identifier-shaped slots.
23780        let s = sharded_spec_with_key(&"a".repeat(63));
23781        s.validate().unwrap();
23782    }
23783
23784    #[test]
23785    fn accepts_canonical_shard_key_forms() {
23786        // The Akka-style entity-id extractor shapes a caixa author is
23787        // realistically going to write — pin every leg so a future
23788        // tightening that bans (e.g.) the `${...}` interpolation
23789        // variant or the `metadata.<field>` JSONPath form surfaces
23790        // here as a regression. The canonical forms span:
23791        //
23792        //   - bare property name (`tenantId`, `customerId`)
23793        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
23794        //   - JSONPath-style nested reference (`metadata.tenantId`,
23795        //     `$.user.id`)
23796        //   - interpolation-style template (`${tenant}`)
23797        //   - snake_case property name (`customer_id`)
23798        //   - kebab-case property name (`customer-id` — accepted
23799        //     because the slot is a printable-ASCII single-token
23800        //     reference, not a DNS-1123 label like
23801        //     `:placement :affinity` / `:clusters`)
23802        //   - single character (`a`, `$` — boundary)
23803        for form in [
23804            "tenantId",
23805            "customerId",
23806            "$tenantId",
23807            "metadata.tenantId",
23808            "$.user.id",
23809            "${tenant}",
23810            "customer_id",
23811            "customer-id",
23812            "a",
23813            "$",
23814        ] {
23815            let s = sharded_spec_with_key(form);
23816            s.validate().unwrap_or_else(|e| {
23817                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
23818            });
23819        }
23820    }
23821
23822    #[test]
23823    fn shard_key_empty_takes_precedence_over_invalid() {
23824        // Order pin: the existing `ShardedKeyEmpty` diagnostic
23825        // (reserved for the `Sharded` `Some("")` arm) fires before the
23826        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
23827        // `:shard-key` keeps its narrower error message — the new gate
23828        // would also reject `""` defensively, but the empty-string arm
23829        // is the more self-locating diagnostic. Mirrors the
23830        // `placement_cluster_empty_takes_precedence_over_invalid` pin
23831        // on the peer identifier-shaped slot.
23832        let s = sharded_spec_with_key("");
23833        let err = s.validate().unwrap_err();
23834        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
23835    }
23836
23837    #[test]
23838    fn shard_key_invalid_diagnostic_carries_offending_value() {
23839        // The diagnostic-shape pin: the error names the offending
23840        // `:shard-key` value verbatim so the author can grep their
23841        // caixa.lisp without re-running the build, and carries a
23842        // parser-shaped `reason:` naming the specific violation —
23843        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
23844        // on the peer identifier-shaped slot.
23845        let s = sharded_spec_with_key("$tenant Id");
23846        let err = s.validate().unwrap_err();
23847        let AplicacaoError::ShardKeyInvalid {
23848            ref shard_key,
23849            ref reason,
23850        } = err
23851        else {
23852            panic!("expected ShardKeyInvalid, got {err:?}");
23853        };
23854        assert_eq!(shard_key, "$tenant Id");
23855        assert!(
23856            !reason.is_empty(),
23857            "reason must name the specific violation, got empty string"
23858        );
23859    }
23860
23861    #[test]
23862    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
23863        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
23864        // `:shard-key` carried on non-Sharded strategies) fires before
23865        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
23866        // a `Replicated` strategy surfaces the more self-locating
23867        // strategy-mismatch diagnostic (naming the actual fix — drop
23868        // the slot, or switch to Sharded) rather than the shape
23869        // diagnostic. The strategy-mismatch arm is the more actionable
23870        // diagnostic: a malformed shard-key on Replicated is "you
23871        // shouldn't have a :shard-key here at all", not "your
23872        // :shard-key value is malformed".
23873        let mut s = three_member_spec();
23874        // Replicated is the default fixture strategy.
23875        s.placement.shard_key = Some("$tenant Id".into());
23876        let err = s.validate().unwrap_err();
23877        assert!(
23878            matches!(
23879                err,
23880                AplicacaoError::ShardKeyOnNonSharded {
23881                    estrategia: PlacementStrategy::Replicated,
23882                    ..
23883                }
23884            ),
23885            "got {err:?}"
23886        );
23887    }
23888
23889    #[test]
23890    fn rejects_empty_affinity_hint() {
23891        let mut s = three_member_spec();
23892        s.placement.affinity = Some(String::new());
23893        assert_eq!(
23894            s.validate().unwrap_err(),
23895            AplicacaoError::PlacementAffinityEmpty
23896        );
23897    }
23898
23899    #[test]
23900    fn placement_without_affinity_validates() {
23901        // Omitting :affinity is fine — the placement engine falls back
23902        // to the default heuristic. Pin the no-hint case so the
23903        // affinity-empty rejection doesn't accidentally fire on `None`.
23904        let mut s = three_member_spec();
23905        s.placement.affinity = None;
23906        s.validate().unwrap();
23907    }
23908
23909    #[test]
23910    fn rejects_placement_affinity_with_uppercase() {
23911        // The canonical "I copied the ADR's display name verbatim" typo
23912        // — placement hints land verbatim in K8s label-selector
23913        // territory, where the apiserver enforces the DNS-1123 label
23914        // rule (lowercase-only) on every identity-keyed admission axis.
23915        // Mirrors `rejects_placement_cluster_with_uppercase` on the
23916        // sibling slot.
23917        let mut s = three_member_spec();
23918        s.placement.affinity = Some("DataLocality".into());
23919        let err = s.validate().unwrap_err();
23920        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
23921            panic!("expected PlacementAffinityInvalid, got other variant");
23922        };
23923        assert_eq!(affinity, "DataLocality");
23924        assert!(
23925            reason.contains("uppercase"),
23926            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
23927        );
23928        assert!(
23929            reason.contains("\"datalocality\""),
23930            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
23931        );
23932    }
23933
23934    #[test]
23935    fn rejects_placement_affinity_with_underscore() {
23936        // The canonical "I'm thinking of an env var / Python identifier"
23937        // leak — `_` is forbidden by every DNS-1123 label schema. Same
23938        // shape as `rejects_placement_cluster_with_underscore` on the
23939        // sibling slot.
23940        let mut s = three_member_spec();
23941        s.placement.affinity = Some("data_locality".into());
23942        let err = s.validate().unwrap_err();
23943        assert!(
23944            matches!(
23945                err,
23946                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23947                    if affinity == "data_locality" && reason.contains('_')
23948            ),
23949            "got {err:?}"
23950        );
23951    }
23952
23953    #[test]
23954    fn rejects_placement_affinity_with_dot() {
23955        // A `:placement :affinity` value is a single DNS-1123 *label*
23956        // (it lands as a K8s label value selector key), not a subdomain.
23957        // The "I want to namespace my hint with `.`" intent is expressed
23958        // via `-` (`data-locality-east`).
23959        let mut s = three_member_spec();
23960        s.placement.affinity = Some("data.locality".into());
23961        let err = s.validate().unwrap_err();
23962        assert!(
23963            matches!(
23964                err,
23965                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
23966                    if affinity == "data.locality" && reason.contains('.')
23967            ),
23968            "got {err:?}"
23969        );
23970    }
23971
23972    #[test]
23973    fn rejects_placement_affinity_with_unicode() {
23974        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
23975        // before it reaches K8s. The byte-by-byte ASCII validity check
23976        // rejects multi-byte UTF-8 sequences by the first byte that
23977        // fails `[a-z0-9-]`.
23978        let mut s = three_member_spec();
23979        s.placement.affinity = Some("data-localité".into());
23980        let err = s.validate().unwrap_err();
23981        assert!(
23982            matches!(
23983                err,
23984                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
23985                    if affinity == "data-localité"
23986            ),
23987            "got {err:?}"
23988        );
23989    }
23990
23991    #[test]
23992    fn rejects_placement_affinity_with_leading_hyphen() {
23993        // DNS-1123 boundary rule: labels must start with an
23994        // alphanumeric. Pin separately from the trailing-hyphen arm so
23995        // a future relaxation that only checks one boundary surfaces
23996        // here as a regression (parallel to
23997        // `rejects_placement_cluster_with_leading_hyphen`).
23998        let mut s = three_member_spec();
23999        s.placement.affinity = Some("-data-locality".into());
24000        let err = s.validate().unwrap_err();
24001        assert!(
24002            matches!(
24003                err,
24004                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
24005                    if affinity == "-data-locality" && reason.contains("start and end")
24006            ),
24007            "got {err:?}"
24008        );
24009    }
24010
24011    #[test]
24012    fn rejects_placement_affinity_with_trailing_hyphen() {
24013        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
24014        // ends are covered against a future relaxation.
24015        let mut s = three_member_spec();
24016        s.placement.affinity = Some("data-locality-".into());
24017        let err = s.validate().unwrap_err();
24018        assert!(
24019            matches!(
24020                err,
24021                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
24022                    if affinity == "data-locality-"
24023            ),
24024            "got {err:?}"
24025        );
24026    }
24027
24028    #[test]
24029    fn rejects_placement_affinity_with_whitespace() {
24030        // Whitespace is the canonical "I pasted from a sketch / doc"
24031        // footgun. The apiserver rejects every label-selector value
24032        // carrying whitespace.
24033        let mut s = three_member_spec();
24034        s.placement.affinity = Some("data locality".into());
24035        let err = s.validate().unwrap_err();
24036        assert!(
24037            matches!(
24038                err,
24039                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
24040                    if affinity == "data locality"
24041            ),
24042            "got {err:?}"
24043        );
24044    }
24045
24046    #[test]
24047    fn rejects_placement_affinity_too_long() {
24048        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
24049        // pin. The diagnostic names both the cap (63) and the actual
24050        // length so the author can shorten in one edit. Mirrors
24051        // `rejects_placement_cluster_too_long`.
24052        let mut s = three_member_spec();
24053        let too_long = "a".repeat(64);
24054        s.placement.affinity = Some(too_long.clone());
24055        let err = s.validate().unwrap_err();
24056        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
24057            panic!("expected PlacementAffinityInvalid");
24058        };
24059        assert_eq!(affinity, too_long);
24060        assert!(
24061            reason.contains("63") && reason.contains("64"),
24062            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
24063        );
24064    }
24065
24066    #[test]
24067    fn placement_affinity_max_length_validates() {
24068        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
24069        // future tightening (e.g. dropping to 62) surfaces here as a
24070        // regression, mirroring `placement_cluster_max_length_validates`.
24071        let mut s = three_member_spec();
24072        s.placement.affinity = Some("a".repeat(63));
24073        s.validate().unwrap();
24074    }
24075
24076    #[test]
24077    fn accepts_canonical_placement_affinity_forms() {
24078        // The DNS-1123 label shapes a caixa author is realistically
24079        // going to write for placement hints: the M3 canonical examples
24080        // (`data-locality`, `low-latency`, `anti-affinity`), the
24081        // single-token form (`affinity`), the single-character boundary
24082        // (`a`), the digit-start (DNS-1123 allows this, unlike
24083        // DNS-1035), and a regional-suffixed form. Pin every leg so a
24084        // future tightening that bans (e.g.) digit-start identifiers
24085        // surfaces here.
24086        for form in [
24087            "data-locality",
24088            "low-latency",
24089            "anti-affinity",
24090            "affinity",
24091            "a",
24092            "3-tier",
24093            "locality-east",
24094        ] {
24095            let mut s = three_member_spec();
24096            s.placement.affinity = Some(form.into());
24097            s.validate().unwrap_or_else(|e| {
24098                panic!("canonical affinity form {form:?} must validate, got {e:?}")
24099            });
24100        }
24101    }
24102
24103    #[test]
24104    fn placement_affinity_empty_takes_precedence_over_invalid() {
24105        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
24106        // (which doesn't try to parse) fires before the new
24107        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
24108        // `:affinity` keeps its narrower error message — the new gate
24109        // would also reject `""`, but the empty-string arm is the more
24110        // self-locating diagnostic. Mirrors the
24111        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
24112        let mut s = three_member_spec();
24113        s.placement.affinity = Some(String::new());
24114        let err = s.validate().unwrap_err();
24115        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
24116    }
24117
24118    #[test]
24119    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
24120        // The diagnostic shape pin: every rejection carries the offending
24121        // `affinity:` verbatim plus a parser-shaped `reason:` so the
24122        // author can grep their caixa.lisp for `:affinity "<hint>"` and
24123        // fix it in one edit. Mirrors the
24124        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
24125        // pin on the sibling slot.
24126        let mut s = three_member_spec();
24127        s.placement.affinity = Some("Data_Locality".into());
24128        let err = s.validate().unwrap_err();
24129        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
24130            panic!("expected PlacementAffinityInvalid");
24131        };
24132        assert_eq!(affinity, "Data_Locality");
24133        assert!(
24134            !reason.is_empty(),
24135            "diagnostic reason must not be empty (got: {reason:?})"
24136        );
24137    }
24138
24139    #[test]
24140    fn singlenode_with_takeover_candidates_validates() {
24141        // OTP distributed-application convention (MESH-COMPOSITION
24142        // §II.1): SingleNode runs on one cluster at a time but the
24143        // :clusters list enumerates the takeover candidates. Multiple
24144        // entries are not a contradiction — they are the failover pool.
24145        let mut s = three_member_spec();
24146        s.placement.estrategia = PlacementStrategy::SingleNode;
24147        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
24148        s.validate().unwrap();
24149    }
24150
24151    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
24152
24153    #[test]
24154    fn mesh_policy_default_is_empty() {
24155        // The Default impl carries None on every axis — the typed
24156        // analog of an unset `:politicas (())` slot. Renderers that
24157        // overlay the policy onto a cluster artifact key off this
24158        // predicate to skip the slot entirely; pinning so a future
24159        // axis added to MeshPolicy can't silently break the contract
24160        // (a new field whose Default is non-None would flip is_empty
24161        // to false on every existing caixa, surfacing here).
24162        assert!(MeshPolicy::default().is_empty());
24163    }
24164
24165    #[test]
24166    fn mesh_policy_with_only_timeout_is_not_empty() {
24167        let p = MeshPolicy {
24168            timeout: Some(Duration::from_secs(30)),
24169            ..Default::default()
24170        };
24171        assert!(!p.is_empty());
24172    }
24173
24174    #[test]
24175    fn mesh_policy_with_only_retries_is_not_empty() {
24176        let p = MeshPolicy {
24177            retries: Some(3),
24178            ..Default::default()
24179        };
24180        assert!(!p.is_empty());
24181    }
24182
24183    #[test]
24184    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
24185        let p = MeshPolicy {
24186            circuit_breaker: Some(CircuitBreaker {
24187                max_failures: 5,
24188                window: Duration::from_secs(60),
24189            }),
24190            ..Default::default()
24191        };
24192        assert!(!p.is_empty());
24193    }
24194
24195    #[test]
24196    fn mesh_policy_with_only_mtls_required_is_not_empty() {
24197        // Even `mtls_required: Some(false)` (an explicit opt-out) is
24198        // not empty — the author *named* the axis, the renderer needs
24199        // to honor that vs. fall back to the cluster default.
24200        let p = MeshPolicy {
24201            mtls_required: Some(false),
24202            ..Default::default()
24203        };
24204        assert!(!p.is_empty());
24205    }
24206
24207    #[test]
24208    fn mesh_policy_with_only_rate_limit_is_not_empty() {
24209        let p = MeshPolicy {
24210            rate_limit: Some(RateLimit {
24211                rate: 100,
24212                window: Duration::from_secs(1),
24213            }),
24214            ..Default::default()
24215        };
24216        assert!(!p.is_empty());
24217    }
24218
24219    #[test]
24220    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
24221        // The three-member happy-path fixture sets timeout + retries +
24222        // mtls_required — every populated axis must read non-empty.
24223        // Pin the round-trip so the M3.x per-:politicas emitter (the
24224        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
24225        // on is_empty() to decide whether to emit at all without
24226        // re-deriving the contract from inline field probes.
24227        assert!(!three_member_spec().politicas.is_empty());
24228    }
24229
24230    // ── shared duration codec: cross-slot integer-magnitude gate ──
24231    //
24232    // The integer-magnitude discipline applied to
24233    // `supervisor::duration_codec::parse` lifts onto every typed slot
24234    // that routes through the shared codec — `MeshPolicy::timeout`
24235    // (`:politicas :timeout`) and `CircuitBreaker::window`
24236    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
24237    // These cross-slot tests pin that the gate fires at the serde
24238    // layer for both typed slots, not just for the supervisor side.
24239
24240    #[test]
24241    fn policy_timeout_serde_rejects_fractional_seconds() {
24242        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
24243        // so the shared codec's integer-magnitude gate applies on
24244        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
24245        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
24246        // deserialize with the canonical-form diagnostic naming the
24247        // offending `"1.5"` and the remediation `"1500ms"`.
24248        let payload = r#"{"timeout":"1.5s"}"#;
24249        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24250        let msg = err.to_string();
24251        assert!(
24252            msg.contains("not a non-negative integer"),
24253            "expected integer-magnitude diagnostic in {msg:?}"
24254        );
24255        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
24256        assert!(
24257            msg.contains("\"1500ms\""),
24258            "missing canonical-form remediation in {msg:?}"
24259        );
24260    }
24261
24262    #[test]
24263    fn policy_timeout_serde_rejects_leading_plus_sign() {
24264        // Pin the leading-`+` arm cross-slot — the prior f64 parser
24265        // accepted `"+30s"` silently and round-tripped to `"30s"`.
24266        let payload = r#"{"timeout":"+30s"}"#;
24267        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24268        let msg = err.to_string();
24269        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
24270    }
24271
24272    #[test]
24273    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
24274        // `CircuitBreaker::window` uses `with =
24275        // "supervisor::duration_codec_required"` (the required-Duration
24276        // variant that delegates to the same shared parser). `"0.5m"`
24277        // parsed to 30s and round-tripped to `"30s"` on next emit —
24278        // DRIFT closed.
24279        let payload = format!(
24280            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
24281            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24282            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
24283        );
24284        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
24285        let msg = err.to_string();
24286        assert!(
24287            msg.contains("not a non-negative integer"),
24288            "expected integer-magnitude diagnostic in {msg:?}"
24289        );
24290        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
24291        assert!(
24292            msg.contains("\"30s\""),
24293            "missing canonical-form remediation in {msg:?}"
24294        );
24295    }
24296
24297    #[test]
24298    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
24299        // Pin the happy-path on the cross-slot side: every canonical
24300        // author shape `render` ever emits parses cleanly through the
24301        // shared codec on the `CircuitBreaker` slot. The
24302        // codec's accepted set (post-gate) is exactly its emitted set
24303        // for the integer-magnitude class.
24304        for window_lit in ["30s", "500ms", "2m", "1h"] {
24305            let payload = format!(
24306                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
24307                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
24308                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
24309            );
24310            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
24311                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
24312            });
24313            assert_eq!(cb.max_failures, 5);
24314        }
24315    }
24316
24317    // ── rate_limit_codec: integer-magnitude gate ──
24318    //
24319    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
24320    // / 737a676 / d53c922 trajectory landed on every typed-duration /
24321    // typed-byte-size codec in caixa-core lifts onto the fifth typed
24322    // codec — `rate_limit_codec` — through the digit-only magnitude
24323    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
24324    // These tests pin the gate at the serde layer for `:politicas
24325    // :rate-limit` (the only typed slot the codec backs), and at the
24326    // codec-internal `parse` layer for the canonical positive cases.
24327
24328    #[test]
24329    fn rate_limit_serde_rejects_fractional_rate() {
24330        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
24331        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
24332        // wording, which didn't name the canonical-form remediation or
24333        // the round-trip drift the next emit would produce. Now refused
24334        // at deserialize with the canonical-form diagnostic naming the
24335        // offending `"1.5"` magnitude and the round-trip drift wording.
24336        let payload = r#"{"rateLimit":"1.5/s"}"#;
24337        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24338        let msg = err.to_string();
24339        assert!(
24340            msg.contains("not a non-negative integer"),
24341            "expected integer-magnitude diagnostic in {msg:?}"
24342        );
24343        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
24344        assert!(
24345            msg.contains("THEORY.md"),
24346            "missing render-determinism contract citation in {msg:?}"
24347        );
24348    }
24349
24350    #[test]
24351    fn rate_limit_serde_rejects_leading_plus_sign() {
24352        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
24353        // permissive-`+` parse), so `"+100/s"` silently parsed to
24354        // `RateLimit { 100, 1s }` and round-tripped through `render` to
24355        // `"100/s"` — a *different* canonical string on the next emit,
24356        // breaking the THEORY.md Part V render-determinism contract
24357        // exactly the way the peer duration codecs' `"+30s"` case did.
24358        // This is the load-bearing class the digit-only gate closes
24359        // beyond what `u32::from_str`'s strictness covers on its own.
24360        let payload = r#"{"rateLimit":"+100/s"}"#;
24361        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24362        let msg = err.to_string();
24363        assert!(
24364            msg.contains("not a non-negative integer"),
24365            "expected integer-magnitude diagnostic in {msg:?}"
24366        );
24367        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
24368    }
24369
24370    #[test]
24371    fn rate_limit_serde_rejects_leading_minus_sign() {
24372        // The signed-negative arm: `"-1/s"` lands on the
24373        // non-canonical-but-numeric branch via the `i64` fallback (the
24374        // `f64` parse also succeeds), surfacing the canonical-form
24375        // diagnostic. Replaces the prior value-laundered "not a u32"
24376        // wording with the unified diagnostic across signs.
24377        let payload = r#"{"rateLimit":"-1/s"}"#;
24378        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24379        let msg = err.to_string();
24380        assert!(
24381            msg.contains("not a non-negative integer"),
24382            "expected integer-magnitude diagnostic in {msg:?}"
24383        );
24384        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
24385    }
24386
24387    #[test]
24388    fn rate_limit_serde_rejects_decimal_shaped_integer() {
24389        // `"100.0/s"` is integer-valued numerically but not in the
24390        // codec's accepted set — `render` emits `"100/s"`, so the
24391        // round-trip would drift. Lifted to the canonical-form
24392        // diagnostic peer with the duration codec's `"1.0s"` case
24393        // (1c55a2a).
24394        let payload = r#"{"rateLimit":"100.0/s"}"#;
24395        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24396        let msg = err.to_string();
24397        assert!(
24398            msg.contains("not a non-negative integer"),
24399            "expected integer-magnitude diagnostic in {msg:?}"
24400        );
24401        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
24402    }
24403
24404    #[test]
24405    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
24406        // Non-numeric, non-digit-only input lands on the existing
24407        // narrower `"not a u32"` arm (preserved for diagnostic-shape
24408        // stability on the parser-shape footgun case). Pin this so a
24409        // future relaxation of the numeric-fallback predicate doesn't
24410        // silently collapse garbage onto the canonical-form arm — same
24411        // partition the peer duration codecs draw between
24412        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
24413        let payload = r#"{"rateLimit":"abc/s"}"#;
24414        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24415        let msg = err.to_string();
24416        assert!(
24417            msg.contains("not a u32"),
24418            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
24419        );
24420        assert!(
24421            !msg.contains("not a non-negative integer"),
24422            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
24423        );
24424    }
24425
24426    #[test]
24427    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
24428        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
24429        // u32's range. The digit-only gate passes; `u32::from_str`
24430        // fails on overflow. Surface that with the overflow-shaped
24431        // diagnostic naming the offending magnitude verbatim, peer
24432        // with `supervisor::duration_codec`'s overflow arm. Pinning
24433        // the wording so a future refactor doesn't silently collapse
24434        // overflow onto the canonical-form arm.
24435        let payload = r#"{"rateLimit":"4294967296/s"}"#;
24436        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24437        let msg = err.to_string();
24438        assert!(
24439            msg.contains("overflows u32"),
24440            "expected overflow diagnostic in {msg:?}"
24441        );
24442        assert!(
24443            msg.contains("\"4294967296\""),
24444            "missing offending magnitude in {msg:?}"
24445        );
24446    }
24447
24448    #[test]
24449    fn rate_limit_serde_rejects_leading_zero_magnitude() {
24450        // `"0100/s"` is digit-only, so the existing
24451        // non-digit-only / sign / fractional arm doesn't catch it —
24452        // `u32::from_str("0100")` returns `Ok(100)`, so before this
24453        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
24454        // round-tripped through `render` to `"100/s"` — a *different*
24455        // canonical string on the next emit, breaking the THEORY.md
24456        // Part V render-determinism contract exactly the way the
24457        // peer `"+100/s"` case did before the leading-`+` arm landed.
24458        // This is the load-bearing class the leading-zero gate closes
24459        // beyond what the existing digit-only / sign / fractional
24460        // gates cover, and the peer arm to the leading-`+` test
24461        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
24462        // canonical-form-drift axis.
24463        let payload = r#"{"rateLimit":"0100/s"}"#;
24464        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24465        let msg = err.to_string();
24466        assert!(
24467            msg.contains("non-canonical leading zero"),
24468            "expected leading-zero diagnostic in {msg:?}"
24469        );
24470        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
24471        assert!(
24472            msg.contains("THEORY.md"),
24473            "missing render-determinism contract citation in {msg:?}"
24474        );
24475    }
24476
24477    #[test]
24478    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
24479        // `"00/s"` is the degenerate leading-zero case — every byte
24480        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
24481        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
24482        // a *different* canonical string, same render-determinism
24483        // violation. The single-byte `"0/s"` itself is in the
24484        // accepted set (round-trips losslessly through `render`,
24485        // refused downstream by `PolicyRateLimitZero`); the
24486        // multi-byte `"00/s"` is not. Pins the boundary between the
24487        // accepted single-`0` and the rejected leading-zero class.
24488        let payload = r#"{"rateLimit":"00/s"}"#;
24489        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24490        let msg = err.to_string();
24491        assert!(
24492            msg.contains("non-canonical leading zero"),
24493            "expected leading-zero diagnostic in {msg:?}"
24494        );
24495        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
24496    }
24497
24498    #[test]
24499    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
24500        // Cross-window pin — the gate is window-agnostic; the
24501        // leading-zero class is a property of the magnitude, not the
24502        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
24503        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
24504        // single-window coverage extended across the three canonical
24505        // windows the codec accepts.
24506        let payload = r#"{"rateLimit":"007/h"}"#;
24507        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24508        let msg = err.to_string();
24509        assert!(
24510            msg.contains("non-canonical leading zero"),
24511            "expected leading-zero diagnostic in {msg:?}"
24512        );
24513        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
24514    }
24515
24516    #[test]
24517    fn rate_limit_serde_rejects_leading_whitespace() {
24518        // `" 100/s"` — the canonical paste-from-aligned-doc /
24519        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
24520        // the top-level `s.trim()` silently ate the leading space and
24521        // parsed the value to `RateLimit { 100, 1s }`, which then
24522        // round-tripped through `render` to `"100/s"` (a *different*
24523        // canonical string on the next emit) — the exact
24524        // canonical-form-drift class the leading-`+` / leading-zero
24525        // arms already close, extended to the whitespace byte class.
24526        let payload = r#"{"rateLimit":" 100/s"}"#;
24527        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24528        let msg = err.to_string();
24529        assert!(
24530            msg.contains("contains whitespace byte"),
24531            "expected whitespace diagnostic in {msg:?}"
24532        );
24533        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24534        assert!(
24535            msg.contains("THEORY.md"),
24536            "missing render-determinism contract citation in {msg:?}"
24537        );
24538    }
24539
24540    #[test]
24541    fn rate_limit_serde_rejects_trailing_whitespace() {
24542        // `"100/s "` — the canonical shell-history / trailing-space
24543        // paste footgun. Before this gate the top-level `s.trim()`
24544        // silently ate the trailing space and parsed to
24545        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
24546        // next emit — same canonical-form drift as the leading-space
24547        // sibling, closed on the same whitespace-byte arm.
24548        let payload = r#"{"rateLimit":"100/s "}"#;
24549        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24550        let msg = err.to_string();
24551        assert!(
24552            msg.contains("contains whitespace byte"),
24553            "expected whitespace diagnostic in {msg:?}"
24554        );
24555        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24556    }
24557
24558    #[test]
24559    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
24560        // `"100 / s"` — the canonical typographically-spaced author
24561        // shape (the same idiom every prose reference to a rate limit
24562        // renders as, mistakenly retained when the value is pasted
24563        // into a codec-shaped slot). Before this gate the per-part
24564        // `rate_str.trim()` / `unit.trim()` calls silently ate both
24565        // spaces on either side of `/` and parsed to
24566        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
24567        // codec's *internal* whitespace-tolerance vector, orthogonal
24568        // to the leading / trailing surface but the same canonical-
24569        // form-drift class. Pins the arm as strictly stronger than the
24570        // pre-existing top-level `s.trim()` behavior: it fires on
24571        // whitespace anywhere in the value, not just at the string
24572        // boundary.
24573        let payload = r#"{"rateLimit":"100 / s"}"#;
24574        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24575        let msg = err.to_string();
24576        assert!(
24577            msg.contains("contains whitespace byte"),
24578            "expected whitespace diagnostic in {msg:?}"
24579        );
24580        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
24581    }
24582
24583    #[test]
24584    fn rate_limit_serde_rejects_tab_byte() {
24585        // `"\t100/s"` — the canonical paste-from-indented-doc /
24586        // paste-from-YAML-block-scalar footgun where a tab byte leads
24587        // the magnitude. Pins that the gate covers tab (`0x09`) as
24588        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
24589        // members and both would be silently swallowed by `s.trim()`
24590        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
24591        // space alone to the full ASCII-whitespace set (space `0x20`,
24592        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
24593        // the tab arm as a representative of the non-space members.
24594        let payload = r#"{"rateLimit":"\t100/s"}"#;
24595        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24596        let msg = err.to_string();
24597        assert!(
24598            msg.contains("contains whitespace byte"),
24599            "expected whitespace diagnostic in {msg:?}"
24600        );
24601        assert!(
24602            msg.contains("0x09"),
24603            "missing offending tab byte in {msg:?}"
24604        );
24605    }
24606
24607    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
24608    //
24609    // Successor to the ASCII-whitespace arm (1ad7755) on
24610    // `rate_limit_codec` — closes the strictly-complementary class the
24611    // byte-scan cannot see, through the lifted
24612    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
24613
24614    #[test]
24615    fn rate_limit_serde_rejects_leading_nbsp() {
24616        // NBSP prefix — paste-from-typography footgun. Byte-scan
24617        // misses, `str::trim` silently strips it, value drifts to
24618        // `"100/s"` on next serialize.
24619        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
24620        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24621        let msg = err.to_string();
24622        assert!(
24623            msg.contains("non-ASCII Unicode whitespace character"),
24624            "expected non-ASCII whitespace diagnostic in {msg:?}"
24625        );
24626        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
24627    }
24628
24629    #[test]
24630    fn rate_limit_serde_rejects_internal_em_space() {
24631        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
24632        // paste-from-typography footgun on the `<integer>/<unit>`
24633        // shape.
24634        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
24635        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
24636        let msg = err.to_string();
24637        assert!(
24638            msg.contains("non-ASCII Unicode whitespace character"),
24639            "expected non-ASCII whitespace diagnostic in {msg:?}"
24640        );
24641        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
24642    }
24643
24644    #[test]
24645    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
24646        // Positive-control pin: every ASCII-only canonical form the
24647        // renderer emits stays accepted through the new arm.
24648        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
24649            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
24650            let p: MeshPolicy = serde_json::from_str(&payload)
24651                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
24652            assert!(p.rate_limit.is_some());
24653        }
24654    }
24655
24656    #[test]
24657    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
24658        // The boundary case — `"0/s"` is the canonical form
24659        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
24660        // it at the parse layer; the downstream
24661        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
24662        // `rate == 0` at the typed-validate layer above. Pins the
24663        // partition: the leading-zero gate at the codec layer does
24664        // not poach the rate-zero semantic-validation arm at the
24665        // typed-validate layer above (a future stricter codec must
24666        // not reject `"0/s"` here, or it'd collapse the diagnostic
24667        // partitioning that lets `PolicyRateLimitZero` name the
24668        // offending typed slot).
24669        let payload = r#"{"rateLimit":"0/s"}"#;
24670        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
24671            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
24672        });
24673        let rl = policy.rate_limit.expect("rate_limit must be Some");
24674        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
24675        assert_eq!(
24676            rl.window,
24677            Duration::from_secs(1),
24678            "single-`0` magnitude with `s` unit must parse to window=1s"
24679        );
24680    }
24681
24682    #[test]
24683    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
24684        // The complementary boundary pin — every magnitude
24685        // `render` emits starts with `[1-9]` (or is the single byte
24686        // `"0"`), so the canonical-form predicate is `(len == 1) ||
24687        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
24688        // '1'` case explicitly so a future tightening of the gate
24689        // (e.g. an over-eager "no leading digit < 5" rule, or a
24690        // mistakenly anchored start-of-magnitude byte check) lands
24691        // here before the canonical-forms-iterating test would catch
24692        // it.
24693        let payload = r#"{"rateLimit":"100/s"}"#;
24694        let policy: MeshPolicy = serde_json::from_str(payload)
24695            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
24696        let rl = policy.rate_limit.expect("rate_limit must be Some");
24697        assert_eq!(
24698            rl.rate, 100,
24699            "canonical-100 magnitude must parse to rate=100"
24700        );
24701    }
24702
24703    #[test]
24704    fn rate_limit_serde_accepts_integer_canonical_forms() {
24705        // Pin the happy-path: every canonical author shape `render`
24706        // ever emits parses cleanly through the codec post-gate. The
24707        // codec's accepted set (post-gate) is exactly its emitted set
24708        // for the integer-magnitude class — same property
24709        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
24710        // gates guarantee on the peer codecs. Iterating across rate
24711        // magnitudes (including `"0"`, which the codec accepts even
24712        // though `validate_politicas` rejects `rate == 0` at the typed
24713        // layer above) closes the codec contract at the parse layer
24714        // independently of the validate layer.
24715        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
24716            for unit_lit in ["s", "m", "h"] {
24717                let lit = format!("{rate_lit}/{unit_lit}");
24718                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
24719                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
24720                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
24721                });
24722                let rl = policy.rate_limit.expect("rate_limit must be Some");
24723                assert_eq!(
24724                    rl.rate,
24725                    rate_lit.parse::<u32>().unwrap(),
24726                    "rate mismatch for {lit:?}"
24727                );
24728            }
24729        }
24730    }
24731
24732    #[test]
24733    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
24734        // The structural property the gate enforces: serialize ∘
24735        // deserialize is the identity on every canonical author shape.
24736        // Peer of `parse_byte_size`'s and `parse_duration`'s
24737        // `_round_trips_through_render_for_every_canonical_form` tests
24738        // on the rate-limit axis. Before the gate, `"+100/s"` violated
24739        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
24740        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
24741        for rate in [1u32, 100, 5000, 1_000_000] {
24742            for (window, unit) in [
24743                (Duration::from_secs(1), "s"),
24744                (Duration::from_secs(60), "m"),
24745                (Duration::from_secs(3600), "h"),
24746            ] {
24747                let policy = MeshPolicy {
24748                    rate_limit: Some(RateLimit { rate, window }),
24749                    ..Default::default()
24750                };
24751                let json = serde_json::to_string(&policy).unwrap();
24752                let expected = format!("\"{rate}/{unit}\"");
24753                assert!(
24754                    json.contains(&expected),
24755                    "expected {expected:?} in {json:?}"
24756                );
24757                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
24758                assert_eq!(
24759                    back.rate_limit, policy.rate_limit,
24760                    "round-trip for {json:?}"
24761                );
24762            }
24763        }
24764    }
24765
24766    // ── self-membership cross-slot gate ──────────────────────────────
24767
24768    #[test]
24769    fn validate_no_self_membership_rejects_self_named_membro() {
24770        // An Aplicacao whose `:membros` lists its own `:nome` is a
24771        // one-node lacre-closure recursion — rejected, naming the parent.
24772        let membros = vec![
24773            membro("catalog", "^0.1"),
24774            membro("checkout", "^0.1"),
24775            membro("cart", "^0.1"),
24776        ];
24777        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
24778        assert!(
24779            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
24780            "got {err:?}"
24781        );
24782    }
24783
24784    #[test]
24785    fn validate_no_self_membership_accepts_distinct_membros() {
24786        // Positive control: distinct member names (including a member
24787        // that is itself an Aplicacao — recursive composition is valid,
24788        // MESH-COMPOSITION §V) pass the gate.
24789        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
24790        validate_no_self_membership(&membros, "checkout").unwrap();
24791    }
24792
24793    #[test]
24794    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
24795        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
24796        // `NoMembros` arm (the more-fundamental "graph must have nodes"
24797        // gate), not by this cross-slot self-edge gate. Keeping the
24798        // self-membership predicate vacuously-ok on the empty input
24799        // matches its supervisor-axis peer
24800        // (`validate_no_self_supervision_empty_children_is_ok`) and
24801        // makes the gate composable from any future call site (an M4
24802        // CR materializer's per-membros validator) without re-checking
24803        // emptiness.
24804        validate_no_self_membership(&[], "checkout").unwrap();
24805    }
24806
24807    #[test]
24808    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
24809        // Pinning the Display: the self-membership diagnostic must name
24810        // the offending caixa verbatim + the "lists itself" framing the
24811        // author can grep for, so the cluster-far failure surfaces at
24812        // build time with one-line remediation. Same diagnostic shape
24813        // as the supervisor-axis `ChildSupervisesSelf` peer.
24814        let membros = vec![membro("orquestra", "^0.1")];
24815        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
24816        let msg = err.to_string();
24817        assert!(
24818            msg.contains("orquestra"),
24819            "diagnostic must name the offending caixa nome (got: {msg:?})"
24820        );
24821        assert!(
24822            msg.contains("lists itself"),
24823            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
24824        );
24825    }
24826
24827    #[test]
24828    fn default_servico_port_constant_pins_canonical_8080_literal() {
24829        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
24830        // at the verbatim `8080` literal both consumers (the
24831        // `Entrada::port` serde default via [`default_port`] and the
24832        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
24833        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
24834        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
24835        // discipline (a085b26) on the per-renderer canonical-K8s-axis
24836        // string-constant axis: a future refactor that drifts the
24837        // constant out from under either consumer surfaces here ahead
24838        // of every per-renderer's first emission. The literal value
24839        // matches the well-known HTTP-alt port the `pleme-computeunit`
24840        // library chart already emits as its `trigger.service.port`
24841        // default — by construction the same value the substrate
24842        // assumes about every Servico's in-cluster L4 listener.
24843        assert_eq!(
24844            DEFAULT_SERVICO_PORT, 8080,
24845            "canonical Servico port literal must remain `8080` verbatim — \
24846             this is the value both the `Entrada::port` serde default and the \
24847             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
24848        );
24849    }
24850
24851    #[test]
24852    fn default_port_helper_returns_canonical_servico_port_constant() {
24853        // The bridge-arm — pins that the [`default_port`] helper
24854        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
24855        // attribute hooks routes through the lifted
24856        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
24857        // literal. A future refactor that re-introduces the `8080`
24858        // literal at the helper's return site (silently re-opening
24859        // the drift footgun this lift closed) surfaces here ahead of
24860        // every author-side `(:entrada (:host … :para …))` slot
24861        // without an explicit `:port`. Peer with the
24862        // `default_namespace_re_export_points_at_caixa_core_canonical`
24863        // pin on the caixa-mesh-side re-export axis.
24864        assert_eq!(
24865            default_port(),
24866            DEFAULT_SERVICO_PORT,
24867            "the serde-default helper must route through the lifted constant"
24868        );
24869    }
24870
24871    #[test]
24872    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
24873        // The end-to-end pin — an author-surface `(:entrada (:host …
24874        // :para …))` without an explicit `:port` slot deserializes to
24875        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
24876        // verbatim. Routes the canonical lifted constant through both
24877        // the serde-default machinery (the `#[serde(default =
24878        // "default_port")]` attribute) and the typed-value-shape
24879        // contract (the resulting [`Entrada::port`] value). A future
24880        // refactor that drifts either axis — replacing the serde
24881        // hook's helper, changing the typed slot's wire shape — would
24882        // surface here before any per-renderer's CNP / Gateway /
24883        // HTTPRoute emission consumed the drifted default.
24884        let entrada: Entrada =
24885            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
24886        assert_eq!(
24887            entrada.port, DEFAULT_SERVICO_PORT,
24888            "the serde default must materialize as the lifted canonical Servico port"
24889        );
24890    }
24891
24892    #[test]
24893    fn servico_port_min_pins_canonical_accept_set_floor() {
24894        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
24895        // verbatim `1` literal every typed `:entrada :port` acceptance
24896        // gate keys off. Peer with the
24897        // [`default_servico_port_constant_pins_canonical_8080_literal`]
24898        // discipline on the canonical-Servico-port-constant axis: a
24899        // future refactor that drifts the accept-set floor out from
24900        // under the sole consumer at [`AplicacaoSpec::validate`]'s
24901        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
24902        // every per-`:entrada` `EntradaPortZero` diagnostic. The
24903        // literal value matches the IANA-registered TCP/UDP port
24904        // space floor (`1..=65535` — port `0` is the "any ephemeral"
24905        // sentinel, not a well-defined destination the substrate's
24906        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
24907        // axis can honor).
24908        assert_eq!(
24909            SERVICO_PORT_MIN, 1,
24910            "canonical Servico port accept-set floor must remain `1` verbatim — \
24911             this is the value the `AplicacaoSpec::validate` gate at \
24912             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
24913        );
24914    }
24915
24916    #[test]
24917    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
24918        // The cross-const invariant pin — the substrate's canonical
24919        // default port must satisfy its own accept-set floor by
24920        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
24921        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
24922        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
24923        // override the operator pins through a future
24924        // `:placement :default-port` slot that lands out-of-range, a
24925        // per-edition Servico-port migration that lifted the floor
24926        // above the previous default without coordinating the pair —
24927        // would silently invalidate the serde-default emission at
24928        // every author-side `(:entrada (:host … :para …))` slot
24929        // without an explicit `:port`: the default port would fall
24930        // below the accept-set floor, the `AplicacaoSpec::validate`
24931        // gate would reject every default-carrying Aplicacao as
24932        // `EntradaPortZero`, and the substrate's typed
24933        // `(defcaixa … :kind Aplicacao)` surface would fail validate
24934        // on every Aplicacao whose author omitted `:entrada :port`
24935        // for the substrate's chosen default — a class of authoring-
24936        // surface footguns the compile-time pin structurally closes.
24937        // Peer with the
24938        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
24939        // (27f9b34) cross-const invariant pin discipline on the peer
24940        // canonical-Helm-per-values-block child-chart-enablement-toggle
24941        // axis pair.
24942        const {
24943            assert!(
24944                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
24945                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
24946                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
24947                 every default-carrying `(:entrada (:host … :para …))` slot \
24948                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
24949                 through the serde default hook and must pass the \
24950                 `AplicacaoSpec::validate` floor gate by construction",
24951            );
24952        }
24953    }
24954
24955    #[test]
24956    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
24957        // The gate-site pin — asserts the `AplicacaoSpec::validate`
24958        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
24959        // `EntradaPortZero` diagnostic on the below-floor input
24960        // `port: 0` (the only below-floor value the `u16` field can
24961        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
24962        // is the singleton `{0}`). A future refactor that drifts the
24963        // gate off the lifted const (silently re-introducing an
24964        // inline `if e.port == 0` byte-check) surfaces here — the
24965        // pin cannot distinguish `< 1` from `== 0` on the current
24966        // floor, but it *does* pin that the diagnostic fires on `0`
24967        // through whichever gate is wired, so any future accept-set
24968        // floor migration (a hypothetical unprivileged-only
24969        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
24970        // update this test alongside the const declaration —
24971        // structurally guaranteeing the gate + accept-set + pin
24972        // trio move together. Peer with the
24973        // [`rejects_zero_entrada_port`] behavioral pin on the same
24974        // per-`:entrada :port` axis — that pin asserts the pre-lift
24975        // behavioral contract (`port: 0` → `EntradaPortZero`); this
24976        // pin adds the structural link to the lifted floor const.
24977        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
24978        let mut s = three_member_spec();
24979        s.entrada.as_mut().unwrap().port = 0;
24980        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
24981    }
24982
24983    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
24984
24985    #[test]
24986    fn membro_serde_keys_match_lifted_membro_key_consts() {
24987        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
24988        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
24989        // name the exact camelCase JSON keys the
24990        // `#[serde(rename_all = "camelCase")]` attribute on
24991        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
24992        // that each canonical byte-sequence appears verbatim in the
24993        // JSON — a future accidental `rename_all = "snake_case"` /
24994        // `"kebab-case"` / verbatim-field-name flip at the derive
24995        // attribute (any of which would silently break every downstream
24996        // JSON consumer that reaches for one of the two consts via
24997        // `Value::get(...)`) surfaces here as a build-time test failure
24998        // at `aplicacao.rs`, not as an apply-time
24999        // `.get(<stale-canonical-const>)` returning `None` far from the
25000        // derive-attr drift's commit. Peer with the sibling
25001        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
25002        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
25003        // same discipline the SupervisorSpec top-level lift established,
25004        // extended here to the M3 [`Membro`] per-`:membros` axis.
25005        let m = Membro {
25006            caixa: "catalog".into(),
25007            versao: "^0.1".into(),
25008        };
25009        let json = serde_json::to_string(&m).unwrap();
25010        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
25011            let quoted = format!("\"{key}\"");
25012            assert!(
25013                json.contains(&quoted),
25014                "serialized Membro must carry the lifted MEMBRO_KEY_* \
25015                 byte-sequence {quoted} verbatim in the JSON emission \
25016                 (got: {json})",
25017            );
25018        }
25019    }
25020
25021    #[test]
25022    fn membro_key_consts_are_pairwise_distinct() {
25023        // Cross-axis drift-detection pin: a future collapse of the two
25024        // canonical [`Membro`] per-entry byte-strings onto the same
25025        // value (e.g. an accidental copy-paste flip of
25026        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
25027        // silently reroute every downstream probe on one axis onto the
25028        // sibling axis's overlay entry and pass every propagation-probe
25029        // test that expected only the stale axis's value. Peer of the
25030        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
25031        // (40cc4e5).
25032        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
25033        for (i, a) in all.iter().enumerate() {
25034            for b in all.iter().skip(i + 1) {
25035                assert_ne!(
25036                    a, b,
25037                    "MEMBRO_KEY_* consts must be pairwise-distinct \
25038                     canonical byte-sequences — got `{a}` == `{b}`",
25039                );
25040            }
25041        }
25042    }
25043
25044    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
25045    //    URL-path fallback resolver every HTTPRoute-aware renderer
25046    //    reaching for a per-rule path-list resolution routes through.
25047    //    The four pin tests below fix the four-way accept-set the
25048    //    resolver must always honor: (:paths-non-empty-verbatim,
25049    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
25050    //    :paths-preserves-order-across-multiple-entries) — drift on any
25051    //    arm surfaces at caixa-core build time rather than at cluster-
25052    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
25053    //    sibling `:politicas` typed-primitive dispatch axis.
25054
25055    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
25056        Entrada {
25057            host: "example.com".into(),
25058            para: "cart".into(),
25059            paths: paths.into_iter().map(String::from).collect(),
25060            port: DEFAULT_SERVICO_PORT,
25061        }
25062    }
25063
25064    #[test]
25065    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
25066        // The typed `:entrada :paths` slot carries an author-declared
25067        // list — the resolver returns each entry verbatim, no
25068        // catch-all substitution. The canonical "author declared
25069        // paths, honor them verbatim" arm of the path-list dispatch.
25070        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
25071        assert_eq!(
25072            e.resolved_paths(),
25073            vec!["/api/cart", "/api/products"],
25074            "resolved_paths must return each `:entrada :paths` entry \
25075             verbatim when the typed slot is non-empty (got {:?})",
25076            e.resolved_paths(),
25077        );
25078    }
25079
25080    #[test]
25081    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
25082        // Empty `:entrada :paths` slot — the resolver substitutes the
25083        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
25084        // catch-all fallback verbatim. Pins the empty-arm of the
25085        // resolver's four-way accept-set against a future silent
25086        // detour that returned an empty Vec (which would emit an
25087        // HTTPRoute with zero rules — silently dropping every
25088        // external `:entrada` flow at admission time), routed to a
25089        // different fallback shape, or dropped the catch-all
25090        // altogether.
25091        let e = entrada_with_paths(vec![]);
25092        assert_eq!(
25093            e.resolved_paths(),
25094            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
25095            "resolved_paths on empty `:entrada :paths` must fall back \
25096             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
25097             all — got {:?}",
25098            e.resolved_paths(),
25099        );
25100    }
25101
25102    #[test]
25103    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
25104        // Single-entry `:entrada :paths` — the resolver returns the
25105        // single declared path verbatim, NOT the catch-all fallback
25106        // (author declared a path, honor it — the empty-arm and the
25107        // len-1 arm are semantically distinct axes of the resolver's
25108        // accept-set). Pins that the resolver treats "author declared
25109        // one path" as authored input, not as the empty case.
25110        let e = entrada_with_paths(vec!["/api/only"]);
25111        assert_eq!(
25112            e.resolved_paths(),
25113            vec!["/api/only"],
25114            "resolved_paths on single-entry `:entrada :paths` must \
25115             return the declared path verbatim, NOT the catch-all \
25116             fallback (got {:?})",
25117            e.resolved_paths(),
25118        );
25119    }
25120
25121    #[test]
25122    fn resolved_paths_preserves_author_declared_order() {
25123        // The `:entrada :paths` list is author-ordered — the resolver
25124        // preserves the author's declaration order verbatim, since
25125        // per-rule dispatch order at the K8s Gateway API HTTPRoute
25126        // consumer is significant (first-match-wins under the
25127        // path-prefix matcher). Pins against a future silent
25128        // re-sort / dedup / normalize detour that reordered author
25129        // input.
25130        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
25131        assert_eq!(
25132            e.resolved_paths(),
25133            vec!["/z/last", "/a/first", "/m/mid"],
25134            "resolved_paths must preserve author-declared `:entrada \
25135             :paths` order verbatim — got {:?}",
25136            e.resolved_paths(),
25137        );
25138    }
25139
25140    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
25141    //    slot `&[String]` slice accessor every per-`:entrada` consumer
25142    //    that must see the author's declaration verbatim (not the
25143    //    fallback-applied projection the sibling `resolved_paths`
25144    //    returns) routes through. The three pin tests below fix the
25145    //    accept-set the accessor must honor: (:non-empty-byte-equal,
25146    //    :empty-projects-empty-slice, :preserves-author-declared-order)
25147    //    — drift on any arm surfaces at caixa-core build time rather
25148    //    than at cluster-apply time. Peer discipline with the sibling
25149    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
25150    //    peer M3 mesh-slot `Vec<String>`-carry axis.
25151
25152    #[test]
25153    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
25154        // Byte-equal pin: [`Entrada::paths`] must project the raw
25155        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
25156        // slice borrowed from the typed slot's own [`Vec<String>`]
25157        // storage — no re-ordering, no dedup, no per-entry normalization,
25158        // no fallback substitution (the fallback-applying projection is
25159        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
25160        // a future silent detour that re-normalized the list, dropped
25161        // duplicates the [`AplicacaoSpec::validate`]
25162        // `EntradaPathDuplicate` refusal already rejects at build time,
25163        // or (most severe) accidentally routed through the fallback-
25164        // applying sibling and returned the substrate catch-all when
25165        // the author declared an empty list — collapsing the raw-slot
25166        // and fallback-applied axes into one and breaking the
25167        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
25168        //
25169        // Peer of the sibling
25170        // [`Placement::clusters`]-shape byte-equal pin
25171        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
25172        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
25173        let fixtures: Vec<Vec<String>> = vec![
25174            Vec::new(),
25175            vec!["/api/cart".into()],
25176            vec!["/api/cart".into(), "/api/products".into()],
25177            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
25178        ];
25179        for paths in fixtures {
25180            let e = Entrada {
25181                host: "example.com".into(),
25182                para: "cart".into(),
25183                paths: paths.clone(),
25184                port: DEFAULT_SERVICO_PORT,
25185            };
25186            assert_eq!(
25187                e.paths(),
25188                paths.as_slice(),
25189                "Entrada::paths must return :entrada :paths verbatim \
25190                 (got {:?}, expected {:?})",
25191                e.paths(),
25192                paths.as_slice(),
25193            );
25194            assert_eq!(
25195                e.paths(),
25196                e.paths.as_slice(),
25197                "Entrada::paths accessor and .paths.as_slice() field \
25198                 access must byte-equal — the accessor is the substrate-\
25199                 primitive typed dispatch every downstream per-`:entrada` \
25200                 raw-slot path-list consumer must route through",
25201            );
25202            assert_eq!(
25203                e.paths().len(),
25204                e.paths.len(),
25205                "Entrada::paths().len() must byte-equal self.paths.len() \
25206                 — a length drift would silently split the paired \
25207                 pre-flight cascade-head `.is_empty()` probe input in \
25208                 the sibling [`Entrada::resolved_paths`] resolver from \
25209                 the per-entry validate loop's traversal input in \
25210                 [`AplicacaoSpec::validate`]",
25211            );
25212        }
25213    }
25214
25215    #[test]
25216    fn resolved_paths_reads_through_lifted_paths_accessor() {
25217        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
25218        // pre-flight `.paths().is_empty()` cascade-head probe (which
25219        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
25220        // catch-all fallback arm when the accessor projects the empty
25221        // slice) and the per-entry `.paths().iter().map(String::as_str)`
25222        // projection (which must reach every entry in the same order
25223        // the accessor projects, so the sibling
25224        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
25225        // per-entry projection stay in lockstep by construction) must
25226        // both key off the lifted accessor. Pins the two-site coherence
25227        // by exercising each production consumer end-to-end: (1) the
25228        // catch-all-fallback arm under the empty slice, (2) the
25229        // author-declared-verbatim arm under a two-entry cohort whose
25230        // per-entry projection must byte-equal the input's per-entry
25231        // author-declared paths in the author's declared order.
25232        //
25233        // Peer of the sibling M3
25234        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
25235        // `validate_placement_reads_through_lifted_clusters_accessor`
25236        // on the sibling `Placement::clusters` reader-site convergence.
25237        let empty = entrada_with_paths(vec![]);
25238        assert_eq!(
25239            empty.resolved_paths(),
25240            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
25241            "resolved_paths on empty :entrada :paths must trip the \
25242             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
25243             catch-all fallback — routing through the lifted paths() \
25244             accessor must not silently drop the fallback arm",
25245        );
25246
25247        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
25248        assert_eq!(
25249            declared.resolved_paths(),
25250            vec!["/api/cart", "/api/products"],
25251            "resolved_paths on non-empty :entrada :paths must return each \
25252             entry verbatim in the author's declared order — routing \
25253             through the lifted paths() accessor must not silently \
25254             reorder or drop entries",
25255        );
25256        // Byte-equal pin against the raw-slot accessor to keep the
25257        // fallback-applying resolver's per-entry projection input in
25258        // lockstep with the raw-slot accessor's projection.
25259        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
25260        assert_eq!(
25261            declared.resolved_paths(),
25262            raw_projected,
25263            "resolved_paths non-empty projection must byte-equal the \
25264             lifted paths() accessor's per-entry String::as_str projection \
25265             — the two projections share the same input slice by \
25266             construction, so any drift here would surface a silent \
25267             re-ordering / dedup / normalization detour in the resolver",
25268        );
25269    }
25270
25271    #[test]
25272    fn validate_reads_through_lifted_entrada_paths_accessor() {
25273        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
25274        // per-entry value-shape gate's `for p in e.paths()` traversal
25275        // (which must reach every entry in the same order the accessor
25276        // projects, so both the per-entry `EntradaPathEmpty` /
25277        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
25278        // the duplicate-detection HashSet insert that trips
25279        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
25280        // projection) must route through the lifted accessor. Pins the
25281        // coherence by exercising each production consumer end-to-end:
25282        // (1) the `EntradaPathEmpty` refusal fires on the second entry
25283        // of a two-entry cohort whose head is valid but tail is empty
25284        // (which requires the loop to reach the second entry through
25285        // the accessor), and (2) the `EntradaPathDuplicate` refusal
25286        // fires on the second entry of a two-entry cohort that shares
25287        // a path (which requires the loop to reach both entries — a
25288        // first-entry-only projection would silently pass since the
25289        // dedup HashSet has room for the first insert).
25290        //
25291        // Peer of the sibling
25292        // `validate_placement_reads_through_lifted_clusters_accessor`
25293        // on the sibling `Placement::clusters` reader-site convergence.
25294        let base = crate::AplicacaoSpec {
25295            membros: vec![crate::Membro {
25296                caixa: "cart".into(),
25297                versao: "^0.1".into(),
25298            }],
25299            contratos: Vec::new(),
25300            politicas: crate::MeshPolicy::default(),
25301            placement: crate::Placement {
25302                estrategia: crate::PlacementStrategy::SingleNode,
25303                clusters: vec!["rio".into()],
25304                shard_key: None,
25305                affinity: None,
25306            },
25307            entrada: Some(Entrada {
25308                host: "example.com".into(),
25309                para: "cart".into(),
25310                paths: vec!["/api/cart".into(), String::new()],
25311                port: DEFAULT_SERVICO_PORT,
25312            }),
25313        };
25314        assert_eq!(
25315            base.validate(),
25316            Err(crate::AplicacaoError::EntradaPathEmpty),
25317            "validate must trip EntradaPathEmpty on the second entry of \
25318             a two-entry cohort — routing through the lifted paths() \
25319             accessor must not silently short-circuit the loop at the \
25320             valid head entry",
25321        );
25322
25323        let mut dup = base;
25324        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
25325        assert_eq!(
25326            dup.validate(),
25327            Err(crate::AplicacaoError::EntradaPathDuplicate {
25328                path: "/api/cart".into(),
25329            }),
25330            "validate must trip EntradaPathDuplicate on the second entry \
25331             of a two-entry cohort that shares a path — routing through \
25332             the lifted paths() accessor must not silently short-circuit \
25333             the dedup HashSet insert at the first entry",
25334        );
25335    }
25336
25337    // ── Entrada::hostname / Entrada::hostnames — the substrate-
25338    //    canonical per-`:entrada` DNS-hostname resolver pair every
25339    //    Gateway-API-aware renderer reaching for a per-listener
25340    //    singular `hostname:` filter (Gateway) or a per-route plural
25341    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
25342    //    The three pin tests below fix the two-way accept-set the pair
25343    //    must always honor: (:singular-byte-equal-to-host,
25344    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
25345    //    on any arm surfaces at caixa-core build time rather than at
25346    //    cluster-apply time when the API server refuses the HTTPRoute
25347    //    for non-intersecting hostname filters. Peer discipline with
25348    //    the sibling `resolved_paths` accept-set pin block above on the
25349    //    per-`:entrada` path-list resolver axis.
25350
25351    fn entrada_with_host(host: &str) -> Entrada {
25352        Entrada {
25353            host: host.into(),
25354            para: "cart".into(),
25355            paths: Vec::new(),
25356            port: DEFAULT_SERVICO_PORT,
25357        }
25358    }
25359
25360    #[test]
25361    fn hostname_returns_entrada_host_byte_equal() {
25362        // The canonical singular-axis pin: [`Entrada::hostname`] must
25363        // return the `:entrada :host` field byte-for-byte, borrowed
25364        // from the typed slot's own [`String`] storage. Pins against a
25365        // future silent detour that re-normalized the host (an
25366        // accidental `.to_lowercase()` — validate_entrada_host already
25367        // enforces lowercase, so any re-normalization is redundant + a
25368        // drift surface between the validator and the accessor), a
25369        // trailing-`.` fully-qualified DNS shape substitution, or a
25370        // Punycode round-trip that lowered a Unicode host through IDNA.
25371        let e = entrada_with_host("checkout.quero.cloud");
25372        assert_eq!(
25373            e.hostname(),
25374            "checkout.quero.cloud",
25375            "Entrada::hostname must return :entrada :host verbatim \
25376             (got {:?})",
25377            e.hostname(),
25378        );
25379        assert_eq!(
25380            e.hostname(),
25381            e.host.as_str(),
25382            "Entrada::hostname must byte-equal the .host field access",
25383        );
25384    }
25385
25386    #[test]
25387    fn hostnames_returns_singleton_of_hostname_accessor() {
25388        // The pair-invariant pin: [`Entrada::hostnames`] must always
25389        // return exactly `vec![hostname()]` — the singleton list whose
25390        // sole entry is the substrate's canonical per-`:entrada`
25391        // singular hostname. Pins the two-consumer coherence axis: the
25392        // Gateway listener's singular `hostname:` filter and the
25393        // HTTPRoute's plural `spec.hostnames[]` filter list must
25394        // agree, else the Gateway API v1.x conformance layer rejects
25395        // the HTTPRoute at attach time with
25396        // `Accepted:False/NoMatchingParent` (the parent Gateway's
25397        // listener hostname doesn't intersect the route's hostname
25398        // filter list) — a divergence whose apply-time symptom is far
25399        // from any single-site commit and never surfaces in the
25400        // emitted YAML. Pinning the pair-invariant here makes any
25401        // future accidental split (an accidental `.to_string() + "."`
25402        // trailing-`.` on the plural side that didn't land on the
25403        // singular side, an accidental prefix stripping on one axis,
25404        // an accidental wildcard prepend the SNI fan-out overlay
25405        // authors on the plural side without a paired singular
25406        // migration) trip at caixa-core build time.
25407        let e = entrada_with_host("checkout.quero.cloud");
25408        assert_eq!(
25409            e.hostnames(),
25410            vec![e.hostname()],
25411            "Entrada::hostnames must return `vec![hostname()]` under \
25412             the pair-invariant — got {:?} vs. singleton {:?}",
25413            e.hostnames(),
25414            vec![e.hostname()],
25415        );
25416    }
25417
25418    #[test]
25419    fn hostnames_is_singleton_under_single_host_author_surface() {
25420        // The singleton-shape pin: under today's single-hostname-per-
25421        // `:entrada` author surface (the `:host` slot is a single
25422        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
25423        // must always return a list of length exactly one. Pins
25424        // against a future silent detour that returned an empty list
25425        // (which would emit an HTTPRoute with `spec.hostnames: []` —
25426        // matching every incoming Host header regardless of the
25427        // Aplicacao's declared ingress apex, silently over-matching
25428        // every foreign VirtualHost the parent Gateway also fronts) or
25429        // a duplicated entry (which the Gateway API v1.x parser
25430        // accepts as a `[]-length-2 list of equal hostnames]` but
25431        // whose semantics differ from the intended singleton). The
25432        // author-surface extension point ("a future `:entrada
25433        // :alt-hosts` list overlay" the docstring names) is the sole
25434        // future axis that flips this pin — that migration will re-
25435        // author this test to pin the new plural cardinality.
25436        let e = entrada_with_host("checkout.quero.cloud");
25437        assert_eq!(
25438            e.hostnames().len(),
25439            1,
25440            "Entrada::hostnames must be a singleton under today's \
25441             single-hostname-per-`:entrada` author surface — got \
25442             length {}: {:?}",
25443            e.hostnames().len(),
25444            e.hostnames(),
25445        );
25446    }
25447
25448    // ── Entrada::destination — the substrate-canonical per-`:entrada`
25449    //    destination-Servico scalar accessor every Gateway-API
25450    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
25451    //    discriminator arg (HTTPRoute name composer) or a per-rule
25452    //    `backendRefs[0].name` axis routes through. The two pin tests
25453    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
25454    //    either arm surfaces at caixa-core build time rather than at
25455    //    cluster-apply time when an HTTPRoute's `metadata.name` and
25456    //    `backendRefs[]` silently disagree on which destination Servico
25457    //    the ingress fronts. Peer discipline with the sibling
25458    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
25459    //    blocks above on the per-`:entrada` path-list / DNS-hostname
25460    //    resolver axes.
25461
25462    #[test]
25463    fn destination_returns_entrada_para_byte_equal() {
25464        // The canonical destination-scalar pin: [`Entrada::destination`]
25465        // must return the `:entrada :para` field byte-for-byte, borrowed
25466        // from the typed slot's own [`String`] storage. Pins against a
25467        // future silent detour that re-normalized the destination (an
25468        // accidental `.to_lowercase()` — the destination Servico is
25469        // already validated as a DNS-1123 label upstream, so any
25470        // re-normalization is redundant + a drift surface between the
25471        // validator and the accessor), a namespace-prefix rewrite (an
25472        // accidental `format!("{namespace}/{para}")` per-CR fully-
25473        // qualified rewrite that didn't land on the peer axis), or a
25474        // per-cluster suffix stamp the operator authors on one
25475        // consumer without the other.
25476        for para in ["cart", "checkout", "catalog", "orders-v2"] {
25477            let e = Entrada {
25478                host: "checkout.quero.cloud".into(),
25479                para: para.into(),
25480                paths: Vec::new(),
25481                port: DEFAULT_SERVICO_PORT,
25482            };
25483            assert_eq!(
25484                e.destination(),
25485                para,
25486                "Entrada::destination must return :entrada :para verbatim \
25487                 (got {:?}, expected {para:?})",
25488                e.destination(),
25489            );
25490            assert_eq!(
25491                e.destination(),
25492                e.para.as_str(),
25493                "Entrada::destination must byte-equal the .para field access",
25494            );
25495        }
25496    }
25497
25498    #[test]
25499    fn destination_borrows_from_entrada_para_storage() {
25500        // The borrow-not-copy pin: [`Entrada::destination`] must
25501        // return a `&str` slice that borrows from the typed slot's
25502        // own [`String`] storage — same-address invariant with
25503        // `entrada.para.as_str()`. Pins against a future silent detour
25504        // that allocated a fresh `String` (`self.para.clone()` in the
25505        // body would type-check but silently drop the borrow, and
25506        // every downstream consumer that assumed the returned slice
25507        // outlives `&self` would break on a stale-reference use-after-
25508        // free). Peer with the sibling `hostname_returns_entrada_
25509        // host_byte_equal` on the singular-DNS-hostname axis.
25510        let e = entrada_with_host("checkout.quero.cloud");
25511        let dest = e.destination();
25512        let para_slice = e.para.as_str();
25513        assert_eq!(
25514            dest.as_ptr(),
25515            para_slice.as_ptr(),
25516            "Entrada::destination must borrow from the .para String's \
25517             backing storage — a fresh allocation here means the \
25518             accessor no longer names the substrate-primitive typed \
25519             dispatch and every downstream consumer would silently \
25520             carry a detached copy",
25521        );
25522        assert_eq!(
25523            dest.len(),
25524            para_slice.len(),
25525            "Entrada::destination and .para.as_str() must byte-equal in \
25526             length as well as in address",
25527        );
25528    }
25529
25530    #[test]
25531    fn port_returns_entrada_port_verbatim_across_permutations() {
25532        // The canonical L4-port-scalar pin: [`Entrada::port`] must
25533        // return the `:entrada :port` field verbatim as a `u16` across
25534        // every author-declared value in the validated accept-set
25535        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
25536        // silent detour that clamped the port (an accidental
25537        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
25538        // land on the peer [`AplicacaoSpec::port_for_destination`]
25539        // resolver), rewrote it through a per-cluster port-remap table
25540        // the operator authors on one consumer without the other, or
25541        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
25542        // serde-default value (which would silently collapse the
25543        // distinction between "author explicitly declared `:port 8080`"
25544        // and "author omitted the slot and inherited the default" the
25545        // future per-cluster override slot depends on). Peer with the
25546        // sibling `destination_returns_entrada_para_byte_equal` +
25547        // `hostname_returns_entrada_host_byte_equal` pins on the
25548        // per-`:entrada` `&str` scalar axes.
25549        for port in [
25550            SERVICO_PORT_MIN,
25551            DEFAULT_SERVICO_PORT,
25552            8443u16,
25553            9090u16,
25554            u16::MAX,
25555        ] {
25556            let e = Entrada {
25557                host: "checkout.quero.cloud".into(),
25558                para: "cart".into(),
25559                paths: Vec::new(),
25560                port,
25561            };
25562            assert_eq!(
25563                e.port(),
25564                port,
25565                "Entrada::port must return :entrada :port verbatim \
25566                 (got {}, expected {port})",
25567                e.port(),
25568            );
25569            assert_eq!(
25570                e.port(),
25571                e.port,
25572                "Entrada::port accessor and .port field access must \
25573                 byte-equal — the accessor is the substrate-primitive \
25574                 typed dispatch every downstream L4-port consumer must \
25575                 route through",
25576            );
25577        }
25578    }
25579
25580    #[test]
25581    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
25582        // Two-consumer coherence pin: the
25583        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
25584        // (which reads through [`Entrada::port`] to compare against
25585        // [`SERVICO_PORT_MIN`]) and the
25586        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
25587        // through [`Entrada::port`] to emit the per-destination
25588        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
25589        // lifted accessor, so any future rebrand on the typed slot's
25590        // reader shape lands at exactly one place. Pins the two-site
25591        // coherence by exercising a below-floor port through validate
25592        // (which must reject) and a validated in-accept-set port through
25593        // port_for_destination (which must emit the same value the
25594        // accessor returns).
25595        let mut spec = three_member_spec();
25596        if let Some(e) = spec.entrada.as_mut() {
25597            e.port = 0;
25598        }
25599        assert_eq!(
25600            spec.validate().unwrap_err(),
25601            AplicacaoError::EntradaPortZero,
25602            "validate must reject `:entrada :port 0` through the lifted \
25603             Entrada::port accessor — port zero lies below \
25604             SERVICO_PORT_MIN and the validator routes through port() \
25605             to name the floor",
25606        );
25607
25608        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
25609            let mut spec = three_member_spec();
25610            if let Some(e) = spec.entrada.as_mut() {
25611                e.port = port;
25612            }
25613            spec.validate().expect(
25614                "entrada with in-accept-set :port must validate — the \
25615                 structural-floor gate reads through Entrada::port",
25616            );
25617            let entrada_ref = spec.entrada().expect(":entrada present");
25618            assert_eq!(
25619                spec.port_for_destination(entrada_ref.destination()),
25620                entrada_ref.port(),
25621                "port_for_destination(entrada.destination()) must equal \
25622                 entrada.port() — the two consumers of the per-:entrada \
25623                 L4-port axis (validator, per-destination resolver) both \
25624                 route through Entrada::port",
25625            );
25626        }
25627    }
25628
25629    #[test]
25630    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
25631        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
25632        // must return the `:contratos :de` field byte-for-byte, borrowed
25633        // from the typed slot's own [`String`] storage. Peer of the
25634        // sibling `destination_returns_entrada_para_byte_equal` pin on
25635        // the per-`:entrada` axis — same "the substrate-primitive
25636        // accessor must byte-equal the raw field access verbatim across
25637        // every author-declared value" discipline extended to the
25638        // per-`:contratos` caller arm. Pins against a future silent
25639        // detour that re-normalized the caller (an accidental
25640        // `.to_lowercase()` — every `:contratos :de` is validated as a
25641        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
25642        // re-normalization is redundant + a drift surface between the
25643        // validator and the accessor), a namespace-prefix rewrite (an
25644        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
25645        // rewrite that didn't land on the peer axis), or a per-cluster
25646        // suffix stamp the operator authors on one consumer without the
25647        // other.
25648        for de in ["cart", "checkout", "catalog", "orders-v2"] {
25649            let c = WitContract {
25650                de: de.into(),
25651                para: "downstream".into(),
25652                wit: "wasi:http/proxy".into(),
25653                endpoint: Some("/lookup".into()),
25654                subject: None,
25655                slot: None,
25656            };
25657            assert_eq!(
25658                c.source(),
25659                de,
25660                "WitContract::source must return :contratos :de verbatim \
25661                 (got {:?}, expected {de:?})",
25662                c.source(),
25663            );
25664            assert_eq!(
25665                c.source(),
25666                c.de.as_str(),
25667                "WitContract::source must byte-equal the .de field access",
25668            );
25669        }
25670    }
25671
25672    #[test]
25673    fn wit_contract_source_borrows_from_de_storage() {
25674        // The borrow-not-copy pin: [`WitContract::source`] must return a
25675        // `&str` slice that borrows from the typed slot's own [`String`]
25676        // storage — same-address invariant with `c.de.as_str()`. Pins
25677        // against a future silent detour that allocated a fresh `String`
25678        // (`self.de.clone()` in the body would type-check but silently
25679        // drop the borrow, and every downstream consumer that assumed
25680        // the returned slice outlives `&self` would break on a stale-
25681        // reference use-after-free). Peer of the sibling
25682        // `destination_borrows_from_entrada_para_storage` on the
25683        // per-`:entrada` axis.
25684        let c = WitContract {
25685            de: "cart".into(),
25686            para: "catalog".into(),
25687            wit: "wasi:http/proxy".into(),
25688            endpoint: Some("/lookup".into()),
25689            subject: None,
25690            slot: None,
25691        };
25692        let src = c.source();
25693        let de_slice = c.de.as_str();
25694        assert_eq!(
25695            src.as_ptr(),
25696            de_slice.as_ptr(),
25697            "WitContract::source must borrow from the .de String's \
25698             backing storage — a fresh allocation here means the \
25699             accessor no longer names the substrate-primitive typed \
25700             dispatch and every downstream consumer would silently \
25701             carry a detached copy",
25702        );
25703        assert_eq!(
25704            src.len(),
25705            de_slice.len(),
25706            "WitContract::source and .de.as_str() must byte-equal in \
25707             length as well as in address",
25708        );
25709    }
25710
25711    #[test]
25712    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
25713        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
25714        // must return the `:contratos :para` field byte-for-byte,
25715        // borrowed from the typed slot's own [`String`] storage. Peer of
25716        // the sibling `destination_returns_entrada_para_byte_equal` on
25717        // the per-`:entrada` axis — both accessors name "the destination-
25718        // Servico byte-string" concept on their respective mesh-slot
25719        // atoms (per-ingress apex vs. per-typed-edge callee) and both
25720        // must project the underlying `.para` field verbatim so every
25721        // downstream renderer that composes them with peer accessors
25722        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
25723        // per-edge L4 port emit site) reads the same byte-string the
25724        // author declared.
25725        for para in ["catalog", "payment", "orders", "inventory-v3"] {
25726            let c = WitContract {
25727                de: "cart".into(),
25728                para: para.into(),
25729                wit: "wasi:http/proxy".into(),
25730                endpoint: Some("/lookup".into()),
25731                subject: None,
25732                slot: None,
25733            };
25734            assert_eq!(
25735                c.destination(),
25736                para,
25737                "WitContract::destination must return :contratos :para \
25738                 verbatim (got {:?}, expected {para:?})",
25739                c.destination(),
25740            );
25741            assert_eq!(
25742                c.destination(),
25743                c.para.as_str(),
25744                "WitContract::destination must byte-equal the .para \
25745                 field access",
25746            );
25747        }
25748    }
25749
25750    #[test]
25751    fn wit_contract_destination_borrows_from_para_storage() {
25752        // The borrow-not-copy pin: [`WitContract::destination`] must
25753        // return a `&str` slice that borrows from the typed slot's own
25754        // [`String`] storage — same-address invariant with
25755        // `c.para.as_str()`. Peer of the sibling
25756        // `destination_borrows_from_entrada_para_storage` on the
25757        // per-`:entrada` axis.
25758        let c = WitContract {
25759            de: "cart".into(),
25760            para: "catalog".into(),
25761            wit: "wasi:http/proxy".into(),
25762            endpoint: Some("/lookup".into()),
25763            subject: None,
25764            slot: None,
25765        };
25766        let dest = c.destination();
25767        let para_slice = c.para.as_str();
25768        assert_eq!(
25769            dest.as_ptr(),
25770            para_slice.as_ptr(),
25771            "WitContract::destination must borrow from the .para \
25772             String's backing storage — a fresh allocation here means \
25773             the accessor no longer names the substrate-primitive typed \
25774             dispatch and every downstream consumer would silently \
25775             carry a detached copy",
25776        );
25777        assert_eq!(
25778            dest.len(),
25779            para_slice.len(),
25780            "WitContract::destination and .para.as_str() must byte-equal \
25781             in length as well as in address",
25782        );
25783    }
25784
25785    #[test]
25786    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
25787        // The canonical per-`:contratos` WIT-world-reference scalar pin:
25788        // [`WitContract::world_ref`] must return the `:contratos :wit`
25789        // field byte-for-byte, borrowed from the typed slot's own
25790        // [`String`] storage. Sibling of the peer per-`:contratos`
25791        // [`WitContract::source`] / [`WitContract::destination`]
25792        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
25793        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
25794        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
25795        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
25796        // "the substrate-primitive accessor must byte-equal the raw
25797        // field access verbatim across every author-declared value"
25798        // discipline extended to the per-`:contratos` WIT-world arm.
25799        // Pins against a future silent detour that re-canonicalized the
25800        // WIT world reference (an accidental `.to_lowercase()` pass that
25801        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
25802        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
25803        // gate is already lowercase-prefixed so any re-normalization is
25804        // redundant + a drift surface between the validator and the
25805        // accessor), an M4-promotion-shape rewrite that formatted a
25806        // typed WIT-world enum through [`Display`] and silently drifted
25807        // the printer output from the source `caixa.lisp`, or a per-
25808        // cluster WIT-alias rewrite that didn't land on the peer field-
25809        // access sites. Five values sweep the shape-dispatch accept-set
25810        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
25811        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
25812        // `wasi:keyvalue/`).
25813        for (wit, endpoint, subject, slot) in [
25814            ("wasi:http/proxy", Some("/lookup"), None, None),
25815            ("http:proxy", Some("/health"), None, None),
25816            ("nats:pub-sub", None, Some("orders.paid"), None),
25817            ("kafka:events", None, Some("checkout-events"), None),
25818            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
25819        ] {
25820            let c = WitContract {
25821                de: "cart".into(),
25822                para: "downstream".into(),
25823                wit: wit.into(),
25824                endpoint: endpoint.map(str::to_string),
25825                subject: subject.map(str::to_string),
25826                slot: slot.map(str::to_string),
25827            };
25828            assert_eq!(
25829                c.world_ref(),
25830                wit,
25831                "WitContract::world_ref must return :contratos :wit \
25832                 verbatim (got {:?}, expected {wit:?})",
25833                c.world_ref(),
25834            );
25835            assert_eq!(
25836                c.world_ref(),
25837                c.wit.as_str(),
25838                "WitContract::world_ref must byte-equal the .wit field \
25839                 access",
25840            );
25841        }
25842    }
25843
25844    #[test]
25845    fn wit_contract_world_ref_borrows_from_wit_storage() {
25846        // The borrow-not-copy pin: [`WitContract::world_ref`] must
25847        // return a `&str` slice that borrows from the typed slot's own
25848        // [`String`] storage — same-address invariant with
25849        // `c.wit.as_str()`. Pins against a future silent detour that
25850        // allocated a fresh `String` (`self.wit.clone()` in the body
25851        // would type-check but silently drop the borrow, and every
25852        // downstream consumer that assumed the returned slice outlives
25853        // `&self` would break on a stale-reference use-after-free — the
25854        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
25855        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
25856        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
25857        // / [`is_pubsub`][WitContract::is_pubsub] /
25858        // [`is_store`][WitContract::is_store] methods route through —
25859        // each borrow from the WitContract's own storage and each would
25860        // silently misbehave if this accessor produced a detached copy).
25861        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
25862        // [`WitContract::destination`] and per-`:entrada`
25863        // [`Entrada::destination`] / [`Entrada::hostname`] and
25864        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
25865        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
25866        let c = WitContract {
25867            de: "cart".into(),
25868            para: "catalog".into(),
25869            wit: "wasi:http/proxy".into(),
25870            endpoint: Some("/lookup".into()),
25871            subject: None,
25872            slot: None,
25873        };
25874        let world = c.world_ref();
25875        let wit_slice = c.wit.as_str();
25876        assert_eq!(
25877            world.as_ptr(),
25878            wit_slice.as_ptr(),
25879            "WitContract::world_ref must borrow from the .wit String's \
25880             backing storage — a fresh allocation here means the \
25881             accessor no longer names the substrate-primitive typed \
25882             dispatch and every downstream consumer would silently carry \
25883             a detached copy",
25884        );
25885        assert_eq!(
25886            world.len(),
25887            wit_slice.len(),
25888            "WitContract::world_ref and .wit.as_str() must byte-equal in \
25889             length as well as in address",
25890        );
25891    }
25892
25893    #[test]
25894    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
25895        // Sibling-triple invariant pin composing all three per-`:contratos`
25896        // substrate-primitive typed dispatches — [`WitContract::source`]
25897        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
25898        // [`WitContract::world_ref`] — at the joint
25899        // `(source(), destination(), world_ref())` call shape every
25900        // renderer that fans on per-edge caller-callee-shape identity
25901        // keys off. The invariant, evaluated per-contract:
25902        //
25903        //   (c.source(), c.destination(), c.world_ref())
25904        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
25905        //
25906        // Closes the last unlifted per-`:contratos` scalar axis — every
25907        // downstream consumer that reads the triple now routes through
25908        // exactly three typed dispatches on the substrate primitive,
25909        // not two typed + one open-coded field access. A future refactor
25910        // that silently split any one accessor's projection (an
25911        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
25912        // canonicalization that didn't reach the peer `source`/
25913        // `destination` arms, an accidental `source()` per-cluster
25914        // caller-alias rewrite that didn't land on the `world_ref` peer)
25915        // surfaces at caixa-core build time. Peer of the sibling per-
25916        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
25917        // per-`:entrada` `(hostname(), destination())` (6db982c /
25918        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
25919        // axes, extended to the per-`:contratos` triple.
25920        for (de, para, wit, endpoint, subject, slot) in [
25921            (
25922                "cart",
25923                "catalog",
25924                "wasi:http/proxy",
25925                Some("/lookup"),
25926                None,
25927                None,
25928            ),
25929            (
25930                "checkout",
25931                "orders",
25932                "nats:pub-sub",
25933                None,
25934                Some("orders.paid"),
25935                None,
25936            ),
25937            (
25938                "cart",
25939                "kv",
25940                "wasi:keyvalue/store",
25941                None,
25942                None,
25943                Some("carts/{cart_id}"),
25944            ),
25945            (
25946                "orders-v2",
25947                "inventory-v3",
25948                "http:proxy",
25949                Some("/reserve"),
25950                None,
25951                None,
25952            ),
25953        ] {
25954            let c = WitContract {
25955                de: de.into(),
25956                para: para.into(),
25957                wit: wit.into(),
25958                endpoint: endpoint.map(str::to_string),
25959                subject: subject.map(str::to_string),
25960                slot: slot.map(str::to_string),
25961            };
25962            assert_eq!(
25963                (c.source(), c.destination(), c.world_ref()),
25964                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
25965                "(WitContract::source, ::destination, ::world_ref) must \
25966                 project (.de, .para, .wit) verbatim across every author-\
25967                 declared triple (got ({:?}, {:?}, {:?}), expected \
25968                 ({de:?}, {para:?}, {wit:?}))",
25969                c.source(),
25970                c.destination(),
25971                c.world_ref(),
25972            );
25973        }
25974    }
25975
25976    #[test]
25977    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
25978        // The canonical per-`:contratos` owned-form caller-callee-pair
25979        // pin: [`WitContract::edge_pair`] must return the
25980        // `(source(), destination())` tuple in owned form byte-for-byte,
25981        // projected through the lifted [`WitContract::source`] /
25982        // [`WitContract::destination`] scalar accessors. Pins the
25983        // composite-projection invariant on the per-`:contratos`
25984        // mesh-slot atom — every author-declared `(de, para)` pair must
25985        // round-trip verbatim through the substrate primitive's typed
25986        // dispatch, so the nine [`AplicacaoError`] diagnostic-
25987        // construction sites the accessor now feeds
25988        // ([`AplicacaoError::EmptyWit`],
25989        // [`AplicacaoError::ContratoEndpointEmpty`],
25990        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
25991        // [`AplicacaoError::ContratoEndpointInvalid`],
25992        // [`AplicacaoError::ContratoSubjectEmpty`],
25993        // [`AplicacaoError::ContratoSubjectInvalid`],
25994        // [`AplicacaoError::ContratoSlotEmpty`],
25995        // [`AplicacaoError::ContratoSlotInvalid`],
25996        // [`AplicacaoError::ContratoDuplicate`]) all read the same
25997        // `(de, para)` label pair every author sees at the source
25998        // `caixa.lisp`. Pins against a future silent detour that swapped
25999        // the `.0` / `.1` arms (an accidental `(destination(),
26000        // source())` re-order in the body would silently invert every
26001        // downstream diagnostic's `de:` / `para:` label pair, silently
26002        // reversing the direction of every operator-facing typed error
26003        // arrow), a fresh-allocation shape drift (an accidental
26004        // `.to_string()` on one arm but not the other would leave the
26005        // owned/borrowed pair mismatched vs. the sibling `source()` /
26006        // `destination()` returns), or an M4 per-cluster caller/callee-
26007        // alias rewrite that landed on `source()` without reaching
26008        // `destination()` (or vice versa). Peer of the sibling per-
26009        // `:contratos` `(source, destination, world_ref)` triple
26010        // pin above on the mesh-slot-atom scalar-value axes, extended
26011        // to the owned-form pair-projection axis.
26012        for (de, para, wit, endpoint, subject, slot) in [
26013            (
26014                "cart",
26015                "catalog",
26016                "wasi:http/proxy",
26017                Some("/lookup"),
26018                None,
26019                None,
26020            ),
26021            (
26022                "checkout",
26023                "orders",
26024                "nats:pub-sub",
26025                None,
26026                Some("orders.paid"),
26027                None,
26028            ),
26029            (
26030                "cart",
26031                "kv",
26032                "wasi:keyvalue/store",
26033                None,
26034                None,
26035                Some("carts/{cart_id}"),
26036            ),
26037            (
26038                "orders-v2",
26039                "inventory-v3",
26040                "http:proxy",
26041                Some("/reserve"),
26042                None,
26043                None,
26044            ),
26045        ] {
26046            let c = WitContract {
26047                de: de.into(),
26048                para: para.into(),
26049                wit: wit.into(),
26050                endpoint: endpoint.map(str::to_string),
26051                subject: subject.map(str::to_string),
26052                slot: slot.map(str::to_string),
26053            };
26054            assert_eq!(
26055                c.edge_pair(),
26056                (de.to_string(), para.to_string()),
26057                "WitContract::edge_pair must return (:contratos :de, \
26058                 :contratos :para) as an owned tuple verbatim (got {:?}, \
26059                 expected ({de:?}, {para:?}))",
26060                c.edge_pair(),
26061            );
26062        }
26063    }
26064
26065    #[test]
26066    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
26067        // The composition pin: [`WitContract::edge_pair`] must return
26068        // exactly `(source().to_string(), destination().to_string())` —
26069        // the owned form of the sibling accessor pair — so any future
26070        // refactor that silently re-authored the caller-arm / callee-arm
26071        // projection to bypass the lifted scalar accessors (an accidental
26072        // `(self.de.clone(), self.para.clone())` regression back to the
26073        // raw field-access shape, an M4-typed-caller-enum `Display`
26074        // re-canonicalization on `source()` that didn't reach
26075        // `edge_pair()`, a per-cluster alias rewrite the operator lands
26076        // on `destination()` without reaching this composite projection)
26077        // trips at caixa-core build time. Pins the "typed dispatch
26078        // composes with typed dispatch, not with raw field access"
26079        // discipline every downstream diagnostic-construction site now
26080        // routes through — a `de:` / `para:` label pair whose
26081        // projection silently drifted off the substrate primitive's
26082        // scalar accessors would silently split the diagnostic's self-
26083        // locating signal from the source `caixa.lisp` author's view.
26084        // Peer of the sibling per-`:politicas` `is_empty` /
26085        // `validate_politicas` accessor-routing-pin family on the M3
26086        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
26087        let c = WitContract {
26088            de: "cart".into(),
26089            para: "catalog".into(),
26090            wit: "wasi:http/proxy".into(),
26091            endpoint: Some("/lookup".into()),
26092            subject: None,
26093            slot: None,
26094        };
26095        assert_eq!(
26096            c.edge_pair(),
26097            (c.source().to_string(), c.destination().to_string()),
26098            "WitContract::edge_pair must compose exactly \
26099             (source().to_string(), destination().to_string()) — a \
26100             bypass of either sibling accessor here would silently \
26101             decouple the composite-projection axis from the \
26102             substrate-primitive scalar accessors every downstream \
26103             consumer routes through",
26104        );
26105    }
26106
26107    #[test]
26108    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
26109     {
26110        // The canonical per-`:contratos` owned-form
26111        // caller-callee-world-ref-triple pin:
26112        // [`WitContract::edge_triple`] must return the
26113        // `(source(), destination(), world_ref())` tuple in owned form
26114        // byte-for-byte, projected through the lifted
26115        // [`WitContract::source`] / [`WitContract::destination`] /
26116        // [`WitContract::world_ref`] scalar accessors. Pins the
26117        // composite-projection invariant on the per-`:contratos`
26118        // mesh-slot atom — every author-declared `(de, para, wit)`
26119        // triple must round-trip verbatim through the substrate
26120        // primitive's typed dispatch, so the nine
26121        // [`AplicacaoError`] diagnostic-construction sites the
26122        // accessor now feeds (the [`WitTarget`]-dispatch's eight
26123        // wrong-target / missing-target / invalid-wit / capability-
26124        // with-payload arms in [`WitContract::target`], plus the
26125        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
26126        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
26127        // read the same `(de, para, wit)` triple every author sees at
26128        // the source `caixa.lisp`. Pins against a future silent
26129        // detour that swapped any two arms (an accidental `(destination(),
26130        // source(), world_ref())` re-order in the body would silently
26131        // invert every downstream diagnostic's `de:` / `para:` label
26132        // pair, silently reversing the direction of every operator-
26133        // facing typed error arrow), a fresh-allocation shape drift
26134        // (an accidental `.to_string()` skipped on one arm would leave
26135        // the owned/borrowed triple mismatched vs. the sibling
26136        // `source()` / `destination()` / `world_ref()` returns), or an
26137        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
26138        // canonicalization pass that landed on one accessor without
26139        // reaching the peers. Peer of the sibling per-`:contratos`
26140        // caller-callee-pair
26141        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
26142        // pin on the mesh-slot-atom composite-projection axis,
26143        // extended to the triple-projection axis.
26144        for (de, para, wit, endpoint, subject, slot) in [
26145            (
26146                "cart",
26147                "catalog",
26148                "wasi:http/proxy",
26149                Some("/lookup"),
26150                None,
26151                None,
26152            ),
26153            (
26154                "checkout",
26155                "orders",
26156                "nats:pub-sub",
26157                None,
26158                Some("orders.paid"),
26159                None,
26160            ),
26161            (
26162                "cart",
26163                "kv",
26164                "wasi:keyvalue/store",
26165                None,
26166                None,
26167                Some("carts/{cart_id}"),
26168            ),
26169            (
26170                "orders-v2",
26171                "inventory-v3",
26172                "http:proxy",
26173                Some("/reserve"),
26174                None,
26175                None,
26176            ),
26177        ] {
26178            let c = WitContract {
26179                de: de.into(),
26180                para: para.into(),
26181                wit: wit.into(),
26182                endpoint: endpoint.map(str::to_string),
26183                subject: subject.map(str::to_string),
26184                slot: slot.map(str::to_string),
26185            };
26186            assert_eq!(
26187                c.edge_triple(),
26188                (de.to_string(), para.to_string(), wit.to_string()),
26189                "WitContract::edge_triple must return (:contratos :de, \
26190                 :contratos :para, :contratos :wit) as an owned triple \
26191                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
26192                c.edge_triple(),
26193            );
26194        }
26195    }
26196
26197    #[test]
26198    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
26199        // The composition pin: [`WitContract::edge_triple`] must return
26200        // exactly `(source().to_string(), destination().to_string(),
26201        // world_ref().to_string())` — the owned form of the sibling
26202        // scalar-accessor triple — so any future refactor that silently
26203        // re-authored one arm's projection to bypass the lifted scalar
26204        // accessors (an accidental `(self.de.clone(), self.para.clone(),
26205        // self.wit.clone())` regression back to the raw field-access
26206        // shape the internal `edge` closure and the ContratoDuplicate
26207        // diagnostic both carried before this lift landed, an
26208        // M4-typed-caller-enum `Display` re-canonicalization on
26209        // `source()` that didn't reach `edge_triple()`, a per-cluster
26210        // alias rewrite the operator lands on `destination()` /
26211        // `world_ref()` without reaching this composite projection)
26212        // trips at caixa-core build time. Pins the "typed dispatch
26213        // composes with typed dispatch, not with raw field access"
26214        // discipline every downstream diagnostic-construction site now
26215        // routes through — a `de:` / `para:` / `wit:` triple whose
26216        // projection silently drifted off the substrate primitive's
26217        // scalar accessors would silently split the diagnostic's self-
26218        // locating signal from the source `caixa.lisp` author's view.
26219        // Peer of the sibling per-`:contratos` edge_pair composition-
26220        // pin above on the mesh-slot-atom composite-projection axis.
26221        let c = WitContract {
26222            de: "cart".into(),
26223            para: "catalog".into(),
26224            wit: "wasi:http/proxy".into(),
26225            endpoint: Some("/lookup".into()),
26226            subject: None,
26227            slot: None,
26228        };
26229        assert_eq!(
26230            c.edge_triple(),
26231            (
26232                c.source().to_string(),
26233                c.destination().to_string(),
26234                c.world_ref().to_string(),
26235            ),
26236            "WitContract::edge_triple must compose exactly \
26237             (source().to_string(), destination().to_string(), \
26238             world_ref().to_string()) — a bypass of any sibling accessor \
26239             here would silently decouple the composite-projection axis \
26240             from the substrate-primitive scalar accessors every \
26241             downstream consumer routes through",
26242        );
26243    }
26244
26245    #[test]
26246    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
26247        // The canonical semantics-pin: [`WitContract::edge_triple`] must
26248        // project the full `(de, para, wit)` identity of a `:contratos`
26249        // edge — the sub-triple every triple-carrying
26250        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
26251        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
26252        // missing-target, capability-with-payload, invalid-wit, and the
26253        // duplicate-gate). Rejects a drift in shape (an accidental
26254        // silent detour that returned a `(de, para)` pair or added an
26255        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
26256        // would trip here because the return type would no longer
26257        // pattern-match the eight `let (de, para, wit) = edge();`
26258        // destructures the [`WitContract::target`] dispatch feeds off
26259        // + the paired duplicate-gate `let (de, para, wit) =
26260        // c.edge_triple();` destructure in
26261        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
26262        // `:contratos` caller-callee-pair pin above extended to the
26263        // triple projection surface: closes the "one composite
26264        // accessor per typed diagnostic-construction sub-tuple"
26265        // discipline on the per-`:contratos` mesh-slot-atom axis.
26266        let c = WitContract {
26267            de: "checkout".into(),
26268            para: "orders".into(),
26269            wit: "nats:pub-sub".into(),
26270            endpoint: None,
26271            subject: Some("orders.paid".into()),
26272            slot: None,
26273        };
26274        let (de, para, wit) = c.edge_triple();
26275        assert_eq!(de, "checkout");
26276        assert_eq!(para, "orders");
26277        assert_eq!(wit, "nats:pub-sub");
26278    }
26279
26280    #[test]
26281    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
26282     {
26283        // The composition pin: [`WitContract::identity`] must return
26284        // exactly `(source(), destination(), world_ref(), endpoint(),
26285        // subject(), slot())` — the borrowed form of the six-scalar-
26286        // accessor identity axis. Any future refactor that silently
26287        // re-authored one arm's projection to bypass a scalar accessor
26288        // (a `self.de.as_str()` regression back to raw field access on
26289        // any of the three required arms, a `self.endpoint.as_deref()`
26290        // regression on any of the three optional arms, an M4 per-
26291        // cluster caller/callee-alias rewrite the operator lands on
26292        // `source()` / `destination()` without reaching this composite
26293        // projection) trips at caixa-core build time. Sweeps four
26294        // permutations of the WIT-shape × payload lattice — HTTP with
26295        // endpoint, pub-sub with subject, store with slot, payload-less
26296        // capability — so every payload arm is exercised. Peer of the
26297        // sibling per-`:contratos`
26298        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
26299        // composition pin on the mesh-slot-atom composite-projection
26300        // axis; extends the discipline from the (de, para, wit) prefix
26301        // onto the full-identity axis carrying the three payload arms.
26302        for (de, para, wit, endpoint, subject, slot) in [
26303            (
26304                "cart",
26305                "catalog",
26306                "wasi:http/proxy",
26307                Some("/lookup"),
26308                None,
26309                None,
26310            ),
26311            (
26312                "checkout",
26313                "orders",
26314                "nats:pub-sub",
26315                None,
26316                Some("orders.paid"),
26317                None,
26318            ),
26319            (
26320                "cart",
26321                "kv",
26322                "wasi:keyvalue/store",
26323                None,
26324                None,
26325                Some("carts/{cart_id}"),
26326            ),
26327            ("audit", "sink", "wasi:logging", None, None, None),
26328        ] {
26329            let c = WitContract {
26330                de: de.into(),
26331                para: para.into(),
26332                wit: wit.into(),
26333                endpoint: endpoint.map(str::to_owned),
26334                subject: subject.map(str::to_owned),
26335                slot: slot.map(str::to_owned),
26336            };
26337            assert_eq!(
26338                c.identity(),
26339                (
26340                    c.source(),
26341                    c.destination(),
26342                    c.world_ref(),
26343                    c.endpoint(),
26344                    c.subject(),
26345                    c.slot(),
26346                ),
26347                "WitContract::identity must compose exactly \
26348                 (source(), destination(), world_ref(), endpoint(), \
26349                 subject(), slot()) — a bypass of any sibling accessor \
26350                 here would silently decouple the identity-projection \
26351                 axis from the substrate-primitive scalar accessors \
26352                 every dedup-key consumer routes through",
26353            );
26354        }
26355    }
26356
26357    #[test]
26358    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
26359        // The canonical semantics-pin: [`WitContract::identity`] must
26360        // project the six-axis (de, para, wit, endpoint, subject, slot)
26361        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26362        // gate keys off — two `WitContract`s that agree on all six axes
26363        // are the same typed edge declared twice, the graph-edge
26364        // analogue of duplicate `:membros` / `:placement :clusters` /
26365        // `:entrada :paths` entries. Rejects a shape drift (an
26366        // accidental silent detour that returned a prefix tuple or
26367        // added an extra field) by pattern-matching the six-arm shape.
26368        // Peer of the sibling per-`:contratos`
26369        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
26370        // pin extended from the (de, para, wit) prefix onto the full
26371        // six-axis identity that the dedup key rides.
26372        let c = WitContract {
26373            de: "cart".into(),
26374            para: "catalog".into(),
26375            wit: "wasi:http/proxy".into(),
26376            endpoint: Some("/products/:id".into()),
26377            subject: None,
26378            slot: None,
26379        };
26380        let (de, para, wit, endpoint, subject, slot) = c.identity();
26381        assert_eq!(de, "cart");
26382        assert_eq!(para, "catalog");
26383        assert_eq!(wit, "wasi:http/proxy");
26384        assert_eq!(endpoint, Some("/products/:id"));
26385        assert_eq!(subject, None);
26386        assert_eq!(slot, None);
26387
26388        // Two byte-identical contracts must produce equal identities —
26389        // the dedup key's foundational invariant.
26390        let c2 = c.clone();
26391        assert_eq!(c.identity(), c2.identity());
26392
26393        // Any change on any of the six axes must break the identity —
26394        // sweeps by mutating one axis at a time.
26395        let mut mutated = c.clone();
26396        mutated.de = "search".into();
26397        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
26398        let mut mutated = c.clone();
26399        mutated.para = "warehouse".into();
26400        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
26401        let mut mutated = c.clone();
26402        mutated.wit = "http:legacy".into();
26403        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
26404        let mut mutated = c.clone();
26405        mutated.endpoint = Some("/search".into());
26406        assert_ne!(
26407            c.identity(),
26408            mutated.identity(),
26409            "endpoint axis must partition"
26410        );
26411        let mut mutated = c.clone();
26412        mutated.subject = Some("orders.paid".into());
26413        assert_ne!(
26414            c.identity(),
26415            mutated.identity(),
26416            "subject axis must partition"
26417        );
26418        let mut mutated = c;
26419        mutated.slot = Some("carts/{id}".into());
26420        assert_ne!(mutated.identity().5, None, "slot axis must partition");
26421    }
26422
26423    #[test]
26424    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
26425        // The canonical per-`:contratos` structural-self-edge pin:
26426        // [`WitContract::is_self_loop`] must return `true` when the
26427        // `:de` and `:para` fields agree byte-for-byte, across every
26428        // WIT-shape variant the per-edge shape family carries. Pins
26429        // the shape-agnostic identity-space partition the
26430        // [`AplicacaoSpec::validate`] self-edge gate at
26431        // caixa-core/src/aplicacao.rs:5559 fires against — all four
26432        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
26433        // under the same one predicate. Four permutations sweep the
26434        // accept-set: HTTP with endpoint, pub-sub with subject, KV
26435        // store with slot, and payload-less capability.
26436        for (nome, wit, endpoint, subject, slot) in [
26437            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
26438            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
26439            (
26440                "kv",
26441                "wasi:keyvalue/store",
26442                None,
26443                None,
26444                Some("carts/{cart_id}"),
26445            ),
26446            ("audit", "wasi:logging", None, None, None),
26447        ] {
26448            let c = WitContract {
26449                de: nome.into(),
26450                para: nome.into(),
26451                wit: wit.into(),
26452                endpoint: endpoint.map(str::to_string),
26453                subject: subject.map(str::to_string),
26454                slot: slot.map(str::to_string),
26455            };
26456            assert!(
26457                c.is_self_loop(),
26458                "WitContract::is_self_loop must return true when \
26459                 :contratos :de == :contratos :para (got false on \
26460                 {nome:?} under {wit:?})",
26461            );
26462        }
26463    }
26464
26465    #[test]
26466    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
26467        // The complement pin: [`WitContract::is_self_loop`] must return
26468        // `false` on every well-shaped inter-Servico contract (the
26469        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
26470        // names — "Servico A calls Servico B" between two distinct
26471        // graph nodes). Pins against a future silent detour that
26472        // inverted the predicate (an accidental `!= ` swap for `==`
26473        // would silently reject every legitimate inter-Servico edge
26474        // and admit every self-edge — the exact inversion of the
26475        // author-intended shape). Four permutations sweep the same
26476        // WIT-shape accept-set the sibling positive-arm test carries.
26477        for (de, para, wit, endpoint, subject, slot) in [
26478            (
26479                "cart",
26480                "catalog",
26481                "wasi:http/proxy",
26482                Some("/lookup"),
26483                None,
26484                None,
26485            ),
26486            (
26487                "checkout",
26488                "orders",
26489                "nats:pub-sub",
26490                None,
26491                Some("orders.paid"),
26492                None,
26493            ),
26494            (
26495                "cart",
26496                "kv",
26497                "wasi:keyvalue/store",
26498                None,
26499                None,
26500                Some("carts/{cart_id}"),
26501            ),
26502            ("audit", "sink", "wasi:logging", None, None, None),
26503        ] {
26504            let c = WitContract {
26505                de: de.into(),
26506                para: para.into(),
26507                wit: wit.into(),
26508                endpoint: endpoint.map(str::to_string),
26509                subject: subject.map(str::to_string),
26510                slot: slot.map(str::to_string),
26511            };
26512            assert!(
26513                !c.is_self_loop(),
26514                "WitContract::is_self_loop must return false when \
26515                 :contratos :de differs from :contratos :para (got true \
26516                 on {de:?} → {para:?} under {wit:?})",
26517            );
26518        }
26519    }
26520
26521    #[test]
26522    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
26523        // The composition pin: [`WitContract::is_self_loop`] must
26524        // resolve to exactly `self.source() == self.destination()` —
26525        // the equality probe of the sibling scalar-accessor pair — so
26526        // any future refactor that silently re-authored the predicate
26527        // to bypass the lifted scalar accessors (an accidental
26528        // `self.de == self.para` regression back to the raw field-
26529        // access shape, an M4-typed-caller-enum identity-comparison
26530        // rule that landed on `source()` without reaching
26531        // `destination()`, a per-cluster alias rewrite the operator
26532        // pins on `destination()` without reaching this predicate)
26533        // trips at caixa-core build time. Pins the "typed dispatch
26534        // composes with typed dispatch, not with raw field access"
26535        // discipline the sibling [`WitContract::edge_pair`] /
26536        // [`WitContract::edge_triple`] composite-projection accessors
26537        // already carry, extended onto the per-edge endpoint-equality
26538        // predicate axis. Positive and complement arms both fire.
26539        let self_edge = WitContract {
26540            de: "cart".into(),
26541            para: "cart".into(),
26542            wit: "wasi:http/proxy".into(),
26543            endpoint: Some("/lookup".into()),
26544            subject: None,
26545            slot: None,
26546        };
26547        assert_eq!(
26548            self_edge.is_self_loop(),
26549            self_edge.source() == self_edge.destination(),
26550            "WitContract::is_self_loop must compose exactly \
26551             `source() == destination()` — a bypass of either sibling \
26552             accessor here would silently decouple the endpoint-\
26553             equality predicate from the substrate-primitive scalar \
26554             accessors every downstream consumer routes through",
26555        );
26556        let inter_edge = WitContract {
26557            de: "cart".into(),
26558            para: "catalog".into(),
26559            wit: "wasi:http/proxy".into(),
26560            endpoint: Some("/lookup".into()),
26561            subject: None,
26562            slot: None,
26563        };
26564        assert_eq!(
26565            inter_edge.is_self_loop(),
26566            inter_edge.source() == inter_edge.destination(),
26567            "WitContract::is_self_loop must compose exactly \
26568             `source() == destination()` on the complement arm too",
26569        );
26570    }
26571
26572    #[test]
26573    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
26574        // The composition pin: [`WitContract::target`]'s invalid-wit
26575        // value-shape gate must feed the reason string through the
26576        // lifted [`WitContract::world_ref`] scalar accessor — the same
26577        // typed dispatch on the substrate primitive every peer
26578        // per-`:contratos` payload-carrier extraction in the same
26579        // method body already routes through
26580        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
26581        // [`WitContract::subject`] on the pub-sub-arm target extraction,
26582        // [`WitContract::slot`] on the store-arm target extraction) and
26583        // every peer composite-projection accessor
26584        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
26585        // [`WitContract::identity`]) already composes from. Any future
26586        // refactor that silently re-authored the gate to bypass the
26587        // lifted accessor (an accidental `&self.wit` regression back to
26588        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
26589        // re-canonicalization on `world_ref()` that didn't reach this
26590        // gate, a per-CR lowercasing canonicalization pass the M4
26591        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
26592        // per-tenant that lands on `world_ref()` without reaching this
26593        // gate) would silently split the invalid-wit diagnostic reason
26594        // from the substrate-primitive projection every downstream
26595        // consumer routes through. Same "typed dispatch composes with
26596        // typed dispatch, not with raw field access" discipline the
26597        // sibling
26598        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
26599        // pin already carries on the endpoint-equality predicate axis,
26600        // extended onto the invalid-wit value-shape gate axis inside
26601        // the same [`WitContract::target`] body. Closes the last
26602        // unlifted raw-field-access site inside `impl WitContract`.
26603        //
26604        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
26605        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
26606        // to a capability-only edge; the value-shape gate rejects it
26607        // through [`crate::render::is_wit_world_ref`] on the substrate
26608        // primitive's ASCII-lowercase-only accept-set, with a
26609        // parser-shaped reason string the test asserts round-trips
26610        // byte-for-byte between the direct-dispatch call (through the
26611        // predicate on the accessor's projection) and the
26612        // [`WitContract::target`] gate's produced reason field.
26613        let c = WitContract {
26614            de: "cart".into(),
26615            para: "catalog".into(),
26616            wit: "WASI:HTTP/proxy".into(),
26617            endpoint: Some("/lookup".into()),
26618            subject: None,
26619            slot: None,
26620        };
26621        let err = c.target().unwrap_err();
26622        let AplicacaoError::ContratoWitInvalid {
26623            ref de,
26624            ref para,
26625            ref wit,
26626            ref reason,
26627        } = err
26628        else {
26629            panic!("expected ContratoWitInvalid, got {err:?}");
26630        };
26631        assert_eq!(de, "cart");
26632        assert_eq!(para, "catalog");
26633        assert_eq!(wit, "WASI:HTTP/proxy");
26634        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
26635        assert_eq!(
26636            *reason, expected_reason,
26637            "WitContract::target's invalid-wit value-shape gate reason \
26638             must compose exactly is_wit_world_ref(self.world_ref()) — \
26639             a bypass here (e.g. a raw `&self.wit` field-access \
26640             regression, or a divergent predicate on a different \
26641             projection) would silently decouple the invalid-wit \
26642             diagnostic's reason field from the substrate-primitive \
26643             scalar accessor every peer per-`:contratos` extraction in \
26644             the same method body already routes through",
26645        );
26646    }
26647
26648    #[test]
26649    fn wit_contract_is_self_loop_predicate_is_const_fn() {
26650        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
26651        // caller-callee identity-space predicate's `const`-eval-surface
26652        // posture. The wrapper below dispatches through
26653        // [`WitContract::is_self_loop`] and is well-formed only when the
26654        // callee is itself `pub const fn` — any future accidental
26655        // downgrade to non-`const` fails the wrapper at caixa-core build
26656        // time with E0015 (`cannot call non-const method`), strictly
26657        // stronger than a runtime `assert!` and strictly stronger than a
26658        // module-scope `const _: () = assert!(…)` pin (the type's
26659        // `String` / `Option<String>` carriers rule out `const`-context
26660        // value construction; the `const fn` wrapper is the load-bearing
26661        // shape that side-steps the destructor-in-const restriction on
26662        // the value axis while still pinning the `const`-fn posture on
26663        // the callee — mirror of the sibling
26664        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
26665        // (279823b) and
26666        // [`wit_contract_identity_projection_accessor_is_const_fn`]
26667        // (1ab648c) pins' discipline verbatim on the peer scalar-
26668        // accessor and composite-projection surfaces). Closes the last
26669        // unlifted per-`:contratos` shape/identity predicate on the
26670        // const-eval surface — the peer WIT-shape-partition family
26671        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
26672        // [`WitContract::is_store`] / [`WitContract::is_capability`]
26673        // already carried the `pub const fn` posture on the peer
26674        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
26675        // this pin extends the same posture onto the caller-callee
26676        // identity-space partition. Sweeps every WIT-shape arm on both
26677        // the equal-endpoints (self-edge) and distinct-endpoints
26678        // (inter-edge) arms of the identity-space partition, plus one
26679        // same-length distinct-byte pair to pin the mid-loop `!=` arm
26680        // past the leading length-mismatch shortcut.
26681        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
26682            c.is_self_loop()
26683        }
26684        let mk = |de: &str, para: &str, wit: &str| WitContract {
26685            de: de.into(),
26686            para: para.into(),
26687            wit: wit.into(),
26688            endpoint: None,
26689            subject: None,
26690            slot: None,
26691        };
26692        for (nome, wit) in [
26693            ("cart", "wasi:http/proxy"),
26694            ("checkout", "nats:pub-sub"),
26695            ("kv", "wasi:keyvalue/store"),
26696            ("audit", "wasi:logging"),
26697        ] {
26698            let self_edge = mk(nome, nome, wit);
26699            assert!(
26700                is_self_loop_via_const_fn(&self_edge),
26701                "self-edge {nome:?} under {wit:?}"
26702            );
26703            assert_eq!(
26704                is_self_loop_via_const_fn(&self_edge),
26705                self_edge.is_self_loop()
26706            );
26707        }
26708        for (de, para, wit) in [
26709            ("cart", "catalog", "wasi:http/proxy"),
26710            ("checkout", "orders", "nats:pub-sub"),
26711            ("cart", "kv", "wasi:keyvalue/store"),
26712            ("audit", "sink", "wasi:logging"),
26713        ] {
26714            let inter_edge = mk(de, para, wit);
26715            assert!(
26716                !is_self_loop_via_const_fn(&inter_edge),
26717                "inter-edge {de:?}→{para:?} under {wit:?}",
26718            );
26719            assert_eq!(
26720                is_self_loop_via_const_fn(&inter_edge),
26721                inter_edge.is_self_loop()
26722            );
26723        }
26724        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
26725        // past the leading `a.len() != b.len()` shortcut so the const-fn
26726        // wrapper exercises every arm of the byte-slice equality loop.
26727        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
26728        assert!(
26729            !is_self_loop_via_const_fn(&same_len_pair),
26730            "same-length distinct-byte"
26731        );
26732        assert_eq!(
26733            is_self_loop_via_const_fn(&same_len_pair),
26734            same_len_pair.is_self_loop()
26735        );
26736    }
26737
26738    #[test]
26739    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
26740        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
26741        // pin: [`WitContract::endpoint`] must return the `:contratos
26742        // :endpoint` field byte-for-byte, borrowed from the typed slot's
26743        // own `Option<String>` storage. Peer of the sibling
26744        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
26745        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
26746        // mesh-slot `Option<String>` optional-scalar axes — same "the
26747        // substrate-primitive accessor must byte-equal the raw field
26748        // access verbatim across every author-declared value" discipline
26749        // extended to the per-`:contratos` HTTP-payload-carrier arm.
26750        // Pins against a future silent detour that re-canonicalized the
26751        // endpoint (an accidental percent-encoding pass that didn't
26752        // reach the peer field-access site at the dedup key, a per-CR
26753        // fully-qualified prefix rewrite the operator authors on one
26754        // consumer without the other, or an M4 typed-path-template
26755        // `Display` re-canonicalization that silently drifted the
26756        // printer output from the source `caixa.lisp`). Four values
26757        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
26758        // gate upstream admits (short root-path, dashed, param-shaped,
26759        // deep-hierarchy).
26760        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
26761            let c = WitContract {
26762                de: "cart".into(),
26763                para: "catalog".into(),
26764                wit: "wasi:http/proxy".into(),
26765                endpoint: Some(endpoint.into()),
26766                subject: None,
26767                slot: None,
26768            };
26769            assert_eq!(
26770                c.endpoint(),
26771                Some(endpoint),
26772                "WitContract::endpoint must return :contratos :endpoint \
26773                 verbatim (got {:?}, expected Some({endpoint:?}))",
26774                c.endpoint(),
26775            );
26776            assert_eq!(
26777                c.endpoint(),
26778                c.endpoint.as_deref(),
26779                "WitContract::endpoint must byte-equal the .endpoint \
26780                 field's `.as_deref()` projection",
26781            );
26782        }
26783    }
26784
26785    #[test]
26786    fn wit_contract_endpoint_none_when_field_is_none() {
26787        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
26788        // payload-carrier accessor pin: when the typed slot is absent —
26789        // the canonical shape under a non-HTTP `:wit` world per the
26790        // [`WitContract::target`]-enforced shape ↔ target partition
26791        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
26792        // carries `:slot`, [`WitTarget::Capability`] carries none) —
26793        // [`WitContract::endpoint`] must return `None`. Pins against a
26794        // future silent detour that projected the absent slot to a
26795        // `Some("")` empty-string default (the canonical `Option<String>`
26796        // → `String` collapse footgun the sibling M2
26797        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26798        // emptiness predicates already guard on the peer M2 typed-slot
26799        // surfaces), a `Some("None")` stringified-None round-trip, or a
26800        // `Some` arm whose contents were derived from a sibling slot (an
26801        // accidental fallback to the `:subject` / `:slot` payload that
26802        // read the pub-sub / store payload into the endpoint axis).
26803        // Three contracts sweep the accept-set every non-HTTP `:wit`
26804        // world lands on — pub-sub NATS, key/value, and payload-less
26805        // capability.
26806        for (wit, subject, slot) in [
26807            ("nats:pub-sub", Some("orders.paid"), None),
26808            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
26809            ("wasi:cli/environment", None, None),
26810        ] {
26811            let c = WitContract {
26812                de: "cart".into(),
26813                para: "downstream".into(),
26814                wit: wit.into(),
26815                endpoint: None,
26816                subject: subject.map(str::to_string),
26817                slot: slot.map(str::to_string),
26818            };
26819            assert!(
26820                c.endpoint().is_none(),
26821                "WitContract::endpoint must return None when the typed \
26822                 slot is absent under :wit {wit:?} (got {:?})",
26823                c.endpoint(),
26824            );
26825            assert_eq!(
26826                c.endpoint(),
26827                c.endpoint.as_deref(),
26828                "WitContract::endpoint must byte-equal the .endpoint \
26829                 field's `.as_deref()` projection in the absent arm",
26830            );
26831        }
26832    }
26833
26834    #[test]
26835    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
26836        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
26837        // an `Option<&str>` whose `Some` arm borrows from the typed
26838        // slot's own [`String`] storage — same-address invariant with
26839        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
26840        // detour that allocated a fresh `String`
26841        // (`self.endpoint.clone().map(...)` in the body would type-check
26842        // but silently drop the borrow, and every downstream consumer
26843        // that assumed the returned slice outlives `&self` would break
26844        // on a stale-reference use-after-free — the [`WitContract::target`]
26845        // Http-arm payload extraction rebinds the returned `Option<&str>`
26846        // through `.ok_or_else(...)` and threads the `&str` payload into
26847        // [`WitTarget::Http { endpoint: &'a str }`], the
26848        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
26849        // [`ContratoIdentity`] dedup key threads the returned
26850        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
26851        // from the WitContract's own storage and each would silently
26852        // misbehave if this accessor produced a detached copy). Peer of
26853        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
26854        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
26855        // shaped optional-scalar axes — first extension of the
26856        // `Option<&str>` borrow-not-copy discipline onto the
26857        // per-`:contratos` HTTP-shaped payload-carrier axis.
26858        let c = WitContract {
26859            de: "cart".into(),
26860            para: "catalog".into(),
26861            wit: "wasi:http/proxy".into(),
26862            endpoint: Some("/lookup".into()),
26863            subject: None,
26864            slot: None,
26865        };
26866        let ep = c.endpoint().expect("Some arm");
26867        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
26868        assert_eq!(
26869            ep.as_ptr(),
26870            storage_slice.as_ptr(),
26871            "WitContract::endpoint must borrow from the .endpoint \
26872             String's backing storage — a fresh allocation here means \
26873             the accessor no longer names the substrate-primitive typed \
26874             dispatch and every downstream consumer would silently \
26875             carry a detached copy",
26876        );
26877        assert_eq!(
26878            ep.len(),
26879            storage_slice.len(),
26880            "WitContract::endpoint and .endpoint.as_deref() must byte-\
26881             equal in length as well as in address",
26882        );
26883    }
26884
26885    #[test]
26886    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
26887        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
26888        // pin: [`WitContract::subject`] must return the `:contratos
26889        // :subject` field byte-for-byte, borrowed from the typed slot's
26890        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
26891        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
26892        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
26893        // optional-scalar axis — same "the substrate-primitive accessor
26894        // must byte-equal the raw field access verbatim across every
26895        // author-declared value" discipline extended to the pub-sub arm.
26896        // Pins against a future silent detour that re-canonicalized the
26897        // subject (an accidental `.to_lowercase()` normalization that
26898        // didn't reach the peer field-access site at the dedup key, a
26899        // per-CR fully-qualified prefix rewrite the operator authors on
26900        // one consumer without the other, or an M4 typed-subject-template
26901        // `Display` re-canonicalization that silently drifted the printer
26902        // output from the source `caixa.lisp`). Four values sweep the
26903        // NATS accept-set every pub-sub author-declared subject lands on
26904        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
26905        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
26906            let c = WitContract {
26907                de: "cart".into(),
26908                para: "notifier".into(),
26909                wit: "nats:pub-sub".into(),
26910                endpoint: None,
26911                subject: Some(subject.into()),
26912                slot: None,
26913            };
26914            assert_eq!(
26915                c.subject(),
26916                Some(subject),
26917                "WitContract::subject must return :contratos :subject \
26918                 verbatim (got {:?}, expected Some({subject:?}))",
26919                c.subject(),
26920            );
26921            assert_eq!(
26922                c.subject(),
26923                c.subject.as_deref(),
26924                "WitContract::subject must byte-equal the .subject \
26925                 field's `.as_deref()` projection",
26926            );
26927        }
26928    }
26929
26930    #[test]
26931    fn wit_contract_subject_none_when_field_is_none() {
26932        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
26933        // shaped payload-carrier accessor pin: when the typed slot is
26934        // absent — the canonical shape under a non-pub-sub `:wit` world
26935        // per the [`WitContract::target`]-enforced shape ↔ target
26936        // partition ([`WitTarget::Http`] carries `:endpoint`,
26937        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
26938        // carries none) — [`WitContract::subject`] must return `None`.
26939        // Pins against a future silent detour that projected the absent
26940        // slot to a `Some("")` empty-string default (the canonical
26941        // `Option<String>` → `String` collapse footgun the sibling M2
26942        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
26943        // emptiness predicates already guard on the peer M2 typed-slot
26944        // surfaces), a `Some("None")` stringified-None round-trip, or a
26945        // `Some` arm whose contents were derived from a sibling slot (an
26946        // accidental fallback to the `:endpoint` / `:slot` payload that
26947        // read the HTTP / store payload into the subject axis). Three
26948        // contracts sweep the accept-set every non-pub-sub `:wit` world
26949        // lands on — HTTP proxy, key/value store, and payload-less
26950        // capability.
26951        for (wit, endpoint, slot) in [
26952            ("wasi:http/proxy", Some("/lookup"), None),
26953            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
26954            ("wasi:cli/environment", None, None),
26955        ] {
26956            let c = WitContract {
26957                de: "cart".into(),
26958                para: "downstream".into(),
26959                wit: wit.into(),
26960                endpoint: endpoint.map(str::to_string),
26961                subject: None,
26962                slot: slot.map(str::to_string),
26963            };
26964            assert!(
26965                c.subject().is_none(),
26966                "WitContract::subject must return None when the typed \
26967                 slot is absent under :wit {wit:?} (got {:?})",
26968                c.subject(),
26969            );
26970            assert_eq!(
26971                c.subject(),
26972                c.subject.as_deref(),
26973                "WitContract::subject must byte-equal the .subject \
26974                 field's `.as_deref()` projection in the absent arm",
26975            );
26976        }
26977    }
26978
26979    #[test]
26980    fn wit_contract_subject_borrows_from_subject_storage() {
26981        // The borrow-not-copy pin: [`WitContract::subject`] must return
26982        // an `Option<&str>` whose `Some` arm borrows from the typed
26983        // slot's own [`String`] storage — same-address invariant with
26984        // `c.subject.as_deref().unwrap()`. Pins against a future silent
26985        // detour that allocated a fresh `String`
26986        // (`self.subject.clone().map(...)` in the body would type-check
26987        // but silently drop the borrow, and every downstream consumer
26988        // that assumed the returned slice outlives `&self` would break
26989        // on a stale-reference use-after-free — the [`WitContract::target`]
26990        // PubSub-arm payload extraction rebinds the returned
26991        // `Option<&str>` through `.ok_or_else(...)` and threads the
26992        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
26993        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
26994        // [`ContratoIdentity`] dedup key threads the returned
26995        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
26996        // from the WitContract's own storage and each would silently
26997        // misbehave if this accessor produced a detached copy). Peer of
26998        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
26999        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
27000        // shaped optional-scalar axis — second extension of the
27001        // `Option<&str>` borrow-not-copy discipline onto the
27002        // per-`:contratos` payload-carrier family, this time on the
27003        // pub-sub arm.
27004        let c = WitContract {
27005            de: "cart".into(),
27006            para: "notifier".into(),
27007            wit: "nats:pub-sub".into(),
27008            endpoint: None,
27009            subject: Some("orders.paid".into()),
27010            slot: None,
27011        };
27012        let sub = c.subject().expect("Some arm");
27013        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
27014        assert_eq!(
27015            sub.as_ptr(),
27016            storage_slice.as_ptr(),
27017            "WitContract::subject must borrow from the .subject \
27018             String's backing storage — a fresh allocation here means \
27019             the accessor no longer names the substrate-primitive typed \
27020             dispatch and every downstream consumer would silently \
27021             carry a detached copy",
27022        );
27023        assert_eq!(
27024            sub.len(),
27025            storage_slice.len(),
27026            "WitContract::subject and .subject.as_deref() must byte-\
27027             equal in length as well as in address",
27028        );
27029    }
27030
27031    #[test]
27032    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
27033        // The canonical per-`:contratos` key/value-store-shaped
27034        // `:slot`-scalar pin: [`WitContract::slot`] must return the
27035        // `:contratos :slot` field byte-for-byte, borrowed from the
27036        // typed slot's own `Option<String>` storage. Peer of the
27037        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
27038        // [`WitContract::subject`] (90de675) accessor pins on the M3
27039        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
27040        // optional-scalar axis — same "the substrate-primitive
27041        // accessor must byte-equal the raw field access verbatim
27042        // across every author-declared value" discipline extended to
27043        // the store arm. Pins against a future silent detour that
27044        // re-canonicalized the slot template (an accidental
27045        // `.to_lowercase()` bucket-prefix normalization that didn't
27046        // reach the peer field-access site at the dedup key, a per-CR
27047        // fully-qualified prefix rewrite the operator authors on one
27048        // consumer without the other, or an M4 typed-key-template
27049        // `Display` re-canonicalization that silently drifted the
27050        // printer output from the source `caixa.lisp`). Four values
27051        // sweep the wasi:keyvalue accept-set every store-shaped
27052        // author-declared slot lands on (flat bucket, single-param
27053        // template, multi-param template, nested-hierarchy template).
27054        for slot in [
27055            "sessions",
27056            "carts/{cart_id}",
27057            "orders/{tenant}/{order_id}",
27058            "cache/tenant-a/orders/{id}",
27059        ] {
27060            let c = WitContract {
27061                de: "cart".into(),
27062                para: "kv".into(),
27063                wit: "wasi:keyvalue/store".into(),
27064                endpoint: None,
27065                subject: None,
27066                slot: Some(slot.into()),
27067            };
27068            assert_eq!(
27069                c.slot(),
27070                Some(slot),
27071                "WitContract::slot must return :contratos :slot \
27072                 verbatim (got {:?}, expected Some({slot:?}))",
27073                c.slot(),
27074            );
27075            assert_eq!(
27076                c.slot(),
27077                c.slot.as_deref(),
27078                "WitContract::slot must byte-equal the .slot field's \
27079                 `.as_deref()` projection",
27080            );
27081        }
27082    }
27083
27084    #[test]
27085    fn wit_contract_slot_none_when_field_is_none() {
27086        // The absent-`:slot` arm of the per-`:contratos` store-shaped
27087        // payload-carrier accessor pin: when the typed slot is absent —
27088        // the canonical shape under a non-store `:wit` world per the
27089        // [`WitContract::target`]-enforced shape ↔ target partition
27090        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
27091        // carries `:subject`, [`WitTarget::Capability`] carries none) —
27092        // [`WitContract::slot`] must return `None`. Pins against a
27093        // future silent detour that projected the absent slot to a
27094        // `Some("")` empty-string default (the canonical
27095        // `Option<String>` → `String` collapse footgun the sibling M2
27096        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
27097        // emptiness predicates already guard on the peer M2 typed-slot
27098        // surfaces), a `Some("None")` stringified-None round-trip, or
27099        // a `Some` arm whose contents were derived from a sibling
27100        // slot (an accidental fallback to the `:endpoint` / `:subject`
27101        // payload that read the HTTP / pub-sub payload into the store
27102        // axis). Three contracts sweep the accept-set every non-store
27103        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
27104        // payload-less capability.
27105        for (wit, endpoint, subject) in [
27106            ("wasi:http/proxy", Some("/lookup"), None),
27107            ("nats:pub-sub", None, Some("orders.paid")),
27108            ("wasi:cli/environment", None, None),
27109        ] {
27110            let c = WitContract {
27111                de: "cart".into(),
27112                para: "downstream".into(),
27113                wit: wit.into(),
27114                endpoint: endpoint.map(str::to_string),
27115                subject: subject.map(str::to_string),
27116                slot: None,
27117            };
27118            assert!(
27119                c.slot().is_none(),
27120                "WitContract::slot must return None when the typed \
27121                 slot is absent under :wit {wit:?} (got {:?})",
27122                c.slot(),
27123            );
27124            assert_eq!(
27125                c.slot(),
27126                c.slot.as_deref(),
27127                "WitContract::slot must byte-equal the .slot field's \
27128                 `.as_deref()` projection in the absent arm",
27129            );
27130        }
27131    }
27132
27133    #[test]
27134    fn wit_contract_slot_borrows_from_slot_storage() {
27135        // The borrow-not-copy pin: [`WitContract::slot`] must return
27136        // an `Option<&str>` whose `Some` arm borrows from the typed
27137        // slot's own [`String`] storage — same-address invariant with
27138        // `c.slot.as_deref().unwrap()`. Pins against a future silent
27139        // detour that allocated a fresh `String`
27140        // (`self.slot.clone().map(...)` in the body would type-check
27141        // but silently drop the borrow, and every downstream consumer
27142        // that assumed the returned slice outlives `&self` would
27143        // break on a stale-reference use-after-free — the
27144        // [`WitContract::target`] Store-arm payload extraction rebinds
27145        // the returned `Option<&str>` through `.ok_or_else(...)` and
27146        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
27147        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
27148        // [`ContratoIdentity`] dedup key threads the returned
27149        // `Option<&str>` into the six-tuple's store arm — each borrow
27150        // from the WitContract's own storage and each would silently
27151        // misbehave if this accessor produced a detached copy). Peer
27152        // of the sibling per-`:contratos` [`WitContract::endpoint`]
27153        // (7020470) / [`WitContract::subject`] (90de675)
27154        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
27155        // shaped optional-scalar axis — third and final extension of
27156        // the `Option<&str>` borrow-not-copy discipline onto the
27157        // per-`:contratos` payload-carrier family, this time on the
27158        // store arm.
27159        let c = WitContract {
27160            de: "cart".into(),
27161            para: "kv".into(),
27162            wit: "wasi:keyvalue/store".into(),
27163            endpoint: None,
27164            subject: None,
27165            slot: Some("carts/{cart_id}".into()),
27166        };
27167        let slot = c.slot().expect("Some arm");
27168        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
27169        assert_eq!(
27170            slot.as_ptr(),
27171            storage_slice.as_ptr(),
27172            "WitContract::slot must borrow from the .slot String's \
27173             backing storage — a fresh allocation here means the \
27174             accessor no longer names the substrate-primitive typed \
27175             dispatch and every downstream consumer would silently \
27176             carry a detached copy",
27177        );
27178        assert_eq!(
27179            slot.len(),
27180            storage_slice.len(),
27181            "WitContract::slot and .slot.as_deref() must byte-equal \
27182             in length as well as in address",
27183        );
27184    }
27185
27186    #[test]
27187    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
27188        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
27189        // [`Membro::nome`] must return the `:membros :caixa` field
27190        // byte-for-byte, borrowed from the typed slot's own [`String`]
27191        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
27192        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
27193        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
27194        // slot-atom scalar-value axes — same "the substrate-primitive
27195        // accessor must byte-equal the raw field access verbatim across
27196        // every author-declared value" discipline extended to the
27197        // per-`:membros` member-identity arm. Pins against a future
27198        // silent detour that re-normalized the member identity (an
27199        // accidental `.to_lowercase()` — every `:membros :caixa` is
27200        // validated as a DNS-1123 label upstream via
27201        // [`validate_membro_caixa`], so any re-normalization is
27202        // redundant + a drift surface between the validator and the
27203        // accessor), a namespace-prefix rewrite (an accidental
27204        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
27205        // rewrite that didn't land on the peer axes), or a per-cluster
27206        // alias stamp the operator authors on one consumer without the
27207        // other. Four values sweep the accept-set the DNS-1123 gate
27208        // upstream admits (short single-word / dashed / v-suffixed
27209        // member names).
27210        for name in ["cart", "checkout", "catalog", "orders-v2"] {
27211            let m = Membro {
27212                caixa: name.into(),
27213                versao: "^0.1".into(),
27214            };
27215            assert_eq!(
27216                m.nome(),
27217                name,
27218                "Membro::nome must return :membros :caixa verbatim \
27219                 (got {:?}, expected {name:?})",
27220                m.nome(),
27221            );
27222            assert_eq!(
27223                m.nome(),
27224                m.caixa.as_str(),
27225                "Membro::nome must byte-equal the .caixa field access",
27226            );
27227        }
27228    }
27229
27230    #[test]
27231    fn membro_nome_borrows_from_caixa_storage() {
27232        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
27233        // slice that borrows from the typed slot's own [`String`]
27234        // storage — same-address invariant with `m.caixa.as_str()`. Pins
27235        // against a future silent detour that allocated a fresh `String`
27236        // (`self.caixa.clone()` in the body would type-check but
27237        // silently drop the borrow, and every downstream consumer that
27238        // assumed the returned slice outlives `&self` would break on a
27239        // stale-reference use-after-free — the `HashSet<&str>` collector
27240        // at [`AplicacaoSpec::validate`]'s `names` seed, the
27241        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
27242        // [`AplicacaoSpec::detect_sync_cycles`], the
27243        // [`crate::render::insert_first_seen`] dedup key at
27244        // [`AplicacaoSpec::validate_membros`] — each borrow from the
27245        // Membro's own storage and each would silently misbehave if
27246        // this accessor produced a detached copy). Peer of the sibling
27247        // per-`:contratos` [`WitContract::source`] /
27248        // [`WitContract::destination`] and per-`:entrada`
27249        // [`Entrada::destination`] borrow-invariant pins on the mesh-
27250        // slot-atom scalar-value axes.
27251        let m = Membro {
27252            caixa: "checkout".into(),
27253            versao: "^0.1".into(),
27254        };
27255        let name = m.nome();
27256        let caixa_slice = m.caixa.as_str();
27257        assert_eq!(
27258            name.as_ptr(),
27259            caixa_slice.as_ptr(),
27260            "Membro::nome must borrow from the .caixa String's backing \
27261             storage — a fresh allocation here means the accessor no \
27262             longer names the substrate-primitive typed dispatch and \
27263             every downstream consumer would silently carry a detached \
27264             copy",
27265        );
27266        assert_eq!(
27267            name.len(),
27268            caixa_slice.len(),
27269            "Membro::nome and .caixa.as_str() must byte-equal in length \
27270             as well as in address",
27271        );
27272    }
27273
27274    #[test]
27275    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
27276        // The canonical per-`:membros` member-`:versao`-scalar pin:
27277        // [`Membro::versao_requirement`] must return the
27278        // `:membros :versao` field byte-for-byte, borrowed from the typed
27279        // slot's own [`String`] storage. Sibling of the peer
27280        // `membro_nome_returns_caixa_byte_equal_across_permutations`
27281        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
27282        // — same "the substrate-primitive accessor must byte-equal the
27283        // raw field access verbatim across every author-declared value"
27284        // discipline extended to the per-`:membros` member-`:versao`
27285        // requirement-string arm. Pins against a future silent detour
27286        // that re-canonicalized the requirement (an accidental
27287        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
27288        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
27289        // drifted the printer output away from the source `caixa.lisp`,
27290        // an accidental whitespace trim on `"^ 0.1"` that no consumer
27291        // ever produced from the field-access side, an accidental
27292        // per-cluster lacre-projected concrete-version rewrite that
27293        // didn't land on the peer field-access sites). Five values sweep
27294        // the accept-set the shared
27295        // [`crate::render::require_valid_versao_requirement`] gate
27296        // admits (caret / tilde / exact / wildcard / bare-major).
27297        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
27298            let m = Membro {
27299                caixa: "cart".into(),
27300                versao: req.into(),
27301            };
27302            assert_eq!(
27303                m.versao_requirement(),
27304                req,
27305                "Membro::versao_requirement must return :membros :versao \
27306                 verbatim (got {:?}, expected {req:?})",
27307                m.versao_requirement(),
27308            );
27309            assert_eq!(
27310                m.versao_requirement(),
27311                m.versao.as_str(),
27312                "Membro::versao_requirement must byte-equal the .versao \
27313                 field access",
27314            );
27315        }
27316    }
27317
27318    #[test]
27319    fn membro_versao_requirement_borrows_from_versao_storage() {
27320        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
27321        // return a `&str` slice that borrows from the typed slot's own
27322        // [`String`] storage — same-address invariant with
27323        // `m.versao.as_str()`. Pins against a future silent detour that
27324        // allocated a fresh `String` (`self.versao.clone()` in the body
27325        // would type-check but silently drop the borrow, and every
27326        // downstream consumer that assumed the returned slice outlives
27327        // `&self` would break on a stale-reference use-after-free). Peer
27328        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
27329        // per-`:contratos` [`WitContract::source`] /
27330        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
27331        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
27332        // the mesh-slot-atom scalar-value axes.
27333        let m = Membro {
27334            caixa: "checkout".into(),
27335            versao: "^0.1".into(),
27336        };
27337        let req = m.versao_requirement();
27338        let versao_slice = m.versao.as_str();
27339        assert_eq!(
27340            req.as_ptr(),
27341            versao_slice.as_ptr(),
27342            "Membro::versao_requirement must borrow from the .versao \
27343             String's backing storage — a fresh allocation here means \
27344             the accessor no longer names the substrate-primitive typed \
27345             dispatch and every downstream consumer would silently carry \
27346             a detached copy",
27347        );
27348        assert_eq!(
27349            req.len(),
27350            versao_slice.len(),
27351            "Membro::versao_requirement and .versao.as_str() must byte-\
27352             equal in length as well as in address",
27353        );
27354    }
27355
27356    #[test]
27357    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
27358        // Sibling-pair invariant pin composing both per-`:membros`
27359        // substrate-primitive typed dispatches — [`Membro::nome`]
27360        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
27361        // `(nome(), versao_requirement())` call shape every renderer
27362        // that fans on per-member identity + version pin keys off. The
27363        // invariant, evaluated per-member:
27364        //
27365        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
27366        //
27367        // Closes the last unlifted per-`:membros` scalar axis — every
27368        // downstream consumer that reads the pair now routes through
27369        // exactly two typed dispatches on the substrate primitive, not
27370        // one typed + one open-coded field access. A future refactor
27371        // that silently split either accessor's projection (an
27372        // accidental `nome()` namespace-prefix rewrite that didn't
27373        // reach the peer, an accidental `versao_requirement()` lacre-
27374        // projected concrete-version rewrite that didn't land on the
27375        // `nome()` peer) surfaces at caixa-core build time. Peer of the
27376        // sibling per-`:entrada` `(hostname(), destination())` and
27377        // per-`:contratos` `(source(), destination())` pair invariants
27378        // on the mesh-slot-atom scalar-value axes.
27379        for (caixa, versao) in [
27380            ("cart", "^0.1"),
27381            ("checkout", "~0.1.2"),
27382            ("catalog", "0.1.0"),
27383            ("orders-v2", "*"),
27384        ] {
27385            let m = Membro {
27386                caixa: caixa.into(),
27387                versao: versao.into(),
27388            };
27389            assert_eq!(
27390                (m.nome(), m.versao_requirement()),
27391                (m.caixa.as_str(), m.versao.as_str()),
27392                "(Membro::nome, Membro::versao_requirement) must project \
27393                 (.caixa, .versao) verbatim across every author-declared \
27394                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
27395                m.nome(),
27396                m.versao_requirement(),
27397            );
27398        }
27399    }
27400
27401    #[test]
27402    fn validate_membros_empty_gate_routes_through_nome_accessor() {
27403        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
27404        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
27405        // not the raw `.caixa` field access. Structurally: setting
27406        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
27407        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
27408        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
27409        // (i.e. the empty string) — so the emptiness predicate the
27410        // refusal arm reaches under is the accessor-projected value,
27411        // not a peer field that would silently drift under a future
27412        // accessor-side rewrite.
27413        //
27414        // Pins against a future silent detour that (a) re-derived the
27415        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
27416        // instead of `self.nome().is_empty()`, silently disagreeing with
27417        // every peer consumer (the `validate_membro_caixa(m.nome())`
27418        // per-slot helper — which now owns the emptiness arm outright —
27419        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
27420        // below, and the emit-side per-`programs[]` entry-`name:` at
27421        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
27422        // per-tenant alias arm the caller was unaware of, silently
27423        // rewriting an author-declared `:caixa "checkout"` to `""` —
27424        // the raw-field-access gate would fail-open while the
27425        // accessor-routed peer consumers would fail-closed, splitting
27426        // the diagnostic from the actual failure surface.
27427        //
27428        // Peer of the sibling
27429        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
27430        // (c0110f1) composition pin — same "the shape-gate predicate
27431        // must route through the substrate-primitive typed dispatch"
27432        // discipline extended onto the per-`:membros` empty-`:caixa`
27433        // refusal-arm axis. Closes the last unlifted `.caixa` production-
27434        // code read site on `Membro` — after this converge every
27435        // caixa-core `.caixa` field access outside the accessor's own
27436        // body is either a test-side field-setter (in-module tests
27437        // constructing invalid-shape inputs) or a doc-comment reference.
27438        let mut s = three_member_spec();
27439        s.membros[1].caixa = String::new();
27440        assert!(
27441            s.membros[1].nome().is_empty(),
27442            "Membro::nome must byte-equal the .caixa field access — an \
27443             accessor-side detour that no longer projects the raw field \
27444             would silently split this drift-detection test from the \
27445             validate() refusal arm",
27446        );
27447        assert_eq!(
27448            s.membros[1].nome(),
27449            s.membros[1].caixa.as_str(),
27450            "Membro::nome and .caixa.as_str() must byte-equal on an \
27451             empty-`:caixa` entry — the emptiness gate keys off the \
27452             accessor by construction",
27453        );
27454        assert_eq!(
27455            s.validate().unwrap_err(),
27456            AplicacaoError::MembroCaixaEmpty,
27457            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
27458             on an entry whose accessor-projected `nome()` is empty",
27459        );
27460    }
27461
27462    #[test]
27463    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
27464        // Convergence pin, paired with the deletion of the redundant
27465        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
27466        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
27467        // after the collapse, the `MembroCaixaEmpty` refusal on every
27468        // empty-`:caixa` per-member input is owned solely by the shared
27469        // [`validate_membro_caixa`] helper — the same per-slot substrate
27470        // primitive routing empty + shape arms uniformly onto
27471        // [`crate::render::require_valid_dns_1123_label`] that every
27472        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
27473        // on `:placement :clusters`, [`validate_entrada_para`] on
27474        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
27475        // :de`/`:para`) already funnels its own empty arm through.
27476        //
27477        // Two arms pin the collapse:
27478        //
27479        //   (1) The per-slot helper called with the empty string returns
27480        //       byte-equal to the previous inline arm's diagnostic — so
27481        //       a future rebrand of [`validate_membro_caixa`] that
27482        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
27483        //       empty input (an inadvertent switch to
27484        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
27485        //       `on_invalid` arm, an accidental re-routing to a shared
27486        //       `MembroError::Empty` under a future error-hierarchy
27487        //       flattening) would silently split the drift from the
27488        //       [`validate_membros`] caller and surface the wrong
27489        //       diagnostic on the author-facing empty-`:caixa` footgun.
27490        //
27491        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
27492        //       anywhere in the `:membros` fan-out still trips
27493        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
27494        //       no outer inline guard needed. Same shape as the
27495        //       whole-spec arm on [`validate_placement_cluster`] /
27496        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
27497        //       one substrate primitive per axis, folding empty + shape.
27498        //
27499        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
27500        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
27501        // MeshPolicy::validate) already extend across the M3 mesh-slot
27502        // family — closes the last per-slot gate on the family carrying
27503        // an inline empty guard duplicating its own helper.
27504        assert_eq!(
27505            validate_membro_caixa(""),
27506            Err(AplicacaoError::MembroCaixaEmpty),
27507            "validate_membro_caixa must own the empty arm outright — a \
27508             regression here would silently split MembroCaixaEmpty from \
27509             validate_membros' end-to-end refusal shape after the outer \
27510             inline `if m.nome().is_empty()` guard collapse",
27511        );
27512        let mut s = three_member_spec();
27513        s.membros[0].caixa = String::new();
27514        assert_eq!(
27515            s.validate().unwrap_err(),
27516            AplicacaoError::MembroCaixaEmpty,
27517            "an empty-`:caixa` :membros head entry must trip \
27518             MembroCaixaEmpty end-to-end via validate() with the outer \
27519             inline guard removed — the per-slot helper alone is now \
27520             load-bearing",
27521        );
27522        let mut s = three_member_spec();
27523        s.membros[2].caixa = String::new();
27524        assert_eq!(
27525            s.validate().unwrap_err(),
27526            AplicacaoError::MembroCaixaEmpty,
27527            "an empty-`:caixa` :membros tail entry must trip \
27528             MembroCaixaEmpty end-to-end via validate() with the outer \
27529             inline guard removed — the per-slot helper alone reaches \
27530             every fan-out position",
27531        );
27532    }
27533
27534    #[test]
27535    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
27536        // The canonical per-`:placement` Akka-cluster-sharding
27537        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
27538        // the `:placement :shard-key` field byte-for-byte, borrowed
27539        // from the typed slot's own `Option<String>` storage. Peer of
27540        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
27541        // per-`:contratos` [`WitContract::source`] /
27542        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
27543        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
27544        // slot-atom scalar-value axes — same "the substrate-primitive
27545        // accessor must byte-equal the raw field access verbatim across
27546        // every author-declared value" discipline extended to the
27547        // per-`:placement` Akka-cluster-sharding key extractor arm.
27548        // Pins against a future silent detour that re-normalized the
27549        // key (an accidental `.to_lowercase()` — every non-empty
27550        // `:shard-key` is validated as a printable-ASCII single-token
27551        // reference upstream via [`validate_placement_shard_key`], so
27552        // any re-normalization is redundant + a drift surface between
27553        // the validator and the accessor), a per-cluster alias rewrite
27554        // the operator authors on one consumer without the other, or an
27555        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
27556        // that didn't land on the peer field-access sites. Four values
27557        // sweep the accept-set the shape gate admits — bare identifier,
27558        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
27559        // the four canonical Akka-style entity-id extractor shapes the
27560        // future M4 cluster-sharding reconciler hashes.
27561        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
27562            let p = Placement {
27563                estrategia: PlacementStrategy::Sharded,
27564                clusters: vec!["rio".into()],
27565                affinity: None,
27566                shard_key: Some(key.into()),
27567            };
27568            assert_eq!(
27569                p.shard_key(),
27570                Some(key),
27571                "Placement::shard_key must return :placement :shard-key \
27572                 verbatim (got {:?}, expected Some({key:?}))",
27573                p.shard_key(),
27574            );
27575            assert_eq!(
27576                p.shard_key(),
27577                p.shard_key.as_deref(),
27578                "Placement::shard_key must byte-equal the .shard_key \
27579                 field's `.as_deref()` projection",
27580            );
27581        }
27582    }
27583
27584    #[test]
27585    fn placement_shard_key_none_when_field_is_none() {
27586        // The absent-`:shard-key` arm of the per-`:placement`
27587        // Akka-cluster-sharding accessor pin: when the typed slot is
27588        // absent — the canonical shape under `:estrategia Replicated` /
27589        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
27590        // enforced `shard_key.is_some() == matches!(estrategia,
27591        // Sharded)` partition — [`Placement::shard_key`] must return
27592        // `None`. Pins against a future silent detour that projected
27593        // the absent slot to a `Some("")` empty-string default (the
27594        // canonical `Option<String>` → `String` collapse footgun the
27595        // sibling M2 [`crate::LimitsSpec::is_empty`] /
27596        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
27597        // already guard on the peer M2 typed-slot surfaces), a
27598        // `Some("None")` stringified-None round-trip, or a `Some` arm
27599        // whose contents were derived from a sibling slot (an
27600        // accidental fallback to `estrategia.as_str()` that read the
27601        // strategy discriminator into the key axis). Two placements
27602        // sweep the accept-set every `validate`-passing non-`Sharded`
27603        // shape lands on — `Replicated` (Erlang/OTP distributed-app
27604        // takeover) and `SingleNode` (single-node hosting).
27605        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
27606            let p = Placement {
27607                estrategia,
27608                clusters: vec!["rio".into()],
27609                affinity: None,
27610                shard_key: None,
27611            };
27612            assert!(
27613                p.shard_key().is_none(),
27614                "Placement::shard_key must return None when the typed \
27615                 slot is absent under :estrategia {estrategia:?} (got {:?})",
27616                p.shard_key(),
27617            );
27618            assert_eq!(
27619                p.shard_key(),
27620                p.shard_key.as_deref(),
27621                "Placement::shard_key must byte-equal the .shard_key \
27622                 field's `.as_deref()` projection in the absent arm",
27623            );
27624        }
27625    }
27626
27627    #[test]
27628    fn placement_shard_key_borrows_from_shard_key_storage() {
27629        // The borrow-not-copy pin: [`Placement::shard_key`] must return
27630        // an `Option<&str>` whose `Some` arm borrows from the typed
27631        // slot's own [`String`] storage — same-address invariant with
27632        // `p.shard_key.as_deref().unwrap()`. Pins against a future
27633        // silent detour that allocated a fresh `String`
27634        // (`self.shard_key.clone().map(...)` in the body would type-
27635        // check but silently drop the borrow, and every downstream
27636        // consumer that assumed the returned slice outlives `&self`
27637        // would break on a stale-reference use-after-free — the
27638        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
27639        // gate's `Some(k)`-bound match arm reads `k: &str` under the
27640        // accessor's return type and would silently misbehave if this
27641        // accessor produced a detached copy). Peer of the sibling
27642        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
27643        // [`WitContract::source`] / [`WitContract::destination`]
27644        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
27645        // (6db982c) borrow-invariant pins on the mesh-slot-atom
27646        // scalar-value axes — first extension of the discipline onto
27647        // an `Option<String>`-shaped optional-scalar axis.
27648        let p = Placement {
27649            estrategia: PlacementStrategy::Sharded,
27650            clusters: vec!["rio".into()],
27651            affinity: None,
27652            shard_key: Some("tenantId".into()),
27653        };
27654        let key = p.shard_key().expect("Some arm");
27655        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
27656        assert_eq!(
27657            key.as_ptr(),
27658            storage_slice.as_ptr(),
27659            "Placement::shard_key must borrow from the .shard_key \
27660             String's backing storage — a fresh allocation here means \
27661             the accessor no longer names the substrate-primitive typed \
27662             dispatch and every downstream consumer would silently \
27663             carry a detached copy",
27664        );
27665        assert_eq!(
27666            key.len(),
27667            storage_slice.len(),
27668            "Placement::shard_key and .shard_key.as_deref() must byte-\
27669             equal in length as well as in address",
27670        );
27671    }
27672
27673    #[test]
27674    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
27675        // The canonical per-`:placement` M3-Adaptive-compression-hint
27676        // scalar pin: [`Placement::affinity`] must return the
27677        // `:placement :affinity` field byte-for-byte, borrowed from the
27678        // typed slot's own `Option<String>` storage. Peer of the sibling
27679        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
27680        // pin on the sibling `Option<&str>` optional-scalar axis — same
27681        // "the substrate-primitive accessor must byte-equal the raw
27682        // field access verbatim across every author-declared value"
27683        // discipline extended to the peer per-`:placement` M3-Adaptive-
27684        // compression-hint arm. Pins against a future silent detour
27685        // that re-normalized the hint (an accidental `.to_lowercase()`
27686        // — every `:affinity` is already validated as a DNS-1123 label
27687        // upstream via [`validate_placement_affinity`], so any re-
27688        // normalization is redundant + a drift surface between the
27689        // validator and the accessor), a per-cluster alias rewrite the
27690        // operator authors on one consumer without the other, or an
27691        // accidental hint-family collapse (`low-latency` → `latency`
27692        // that dropped the qualifier prefix). Four values sweep the
27693        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
27694        // canonical adaptive-compression-weight biases the future M4
27695        // placement engine reads.
27696        for hint in [
27697            "data-locality",
27698            "low-latency",
27699            "high-throughput",
27700            "cost-optimized",
27701        ] {
27702            let p = Placement {
27703                estrategia: PlacementStrategy::Replicated,
27704                clusters: vec!["rio".into()],
27705                affinity: Some(hint.into()),
27706                shard_key: None,
27707            };
27708            assert_eq!(
27709                p.affinity(),
27710                Some(hint),
27711                "Placement::affinity must return :placement :affinity \
27712                 verbatim (got {:?}, expected Some({hint:?}))",
27713                p.affinity(),
27714            );
27715            assert_eq!(
27716                p.affinity(),
27717                p.affinity.as_deref(),
27718                "Placement::affinity must byte-equal the .affinity \
27719                 field's `.as_deref()` projection",
27720            );
27721        }
27722    }
27723
27724    #[test]
27725    fn placement_affinity_none_when_field_is_none() {
27726        // The absent-`:affinity` arm of the per-`:placement`
27727        // M3-Adaptive-compression-hint accessor pin: when the typed
27728        // slot is absent — the canonical shape of an Aplicacao that
27729        // leaves the compression weighting up to the placement engine's
27730        // cluster-default arm — [`Placement::affinity`] must return
27731        // `None`. Pins against a future silent detour that projected
27732        // the absent slot to a `Some("")` empty-string default (the
27733        // canonical `Option<String>` → `String` collapse footgun the
27734        // sibling M2 [`crate::LimitsSpec::is_empty`] /
27735        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
27736        // already guard on the peer M2 typed-slot surfaces), a
27737        // `Some("None")` stringified-None round-trip, a `Some` arm
27738        // whose contents were derived from a sibling slot (an
27739        // accidental fallback to `estrategia.as_str()` that read the
27740        // strategy discriminator into the hint axis), or a
27741        // `Some("default")` implicit-default that would silently biases
27742        // the routing without the author having written one. Three
27743        // placements sweep the accept-set every `validate`-passing
27744        // `:affinity None` shape lands on — one per PlacementStrategy
27745        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
27746        // with a shard-key), since `:affinity` is orthogonal to
27747        // `:estrategia` in the typed grammar.
27748        for (estrategia, shard_key) in [
27749            (PlacementStrategy::SingleNode, None),
27750            (PlacementStrategy::Replicated, None),
27751            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
27752        ] {
27753            let p = Placement {
27754                estrategia,
27755                clusters: vec!["rio".into()],
27756                affinity: None,
27757                shard_key,
27758            };
27759            assert!(
27760                p.affinity().is_none(),
27761                "Placement::affinity must return None when the typed \
27762                 slot is absent under :estrategia {estrategia:?} (got {:?})",
27763                p.affinity(),
27764            );
27765            assert_eq!(
27766                p.affinity(),
27767                p.affinity.as_deref(),
27768                "Placement::affinity must byte-equal the .affinity \
27769                 field's `.as_deref()` projection in the absent arm",
27770            );
27771        }
27772    }
27773
27774    #[test]
27775    fn placement_affinity_borrows_from_affinity_storage() {
27776        // The borrow-not-copy pin: [`Placement::affinity`] must return
27777        // an `Option<&str>` whose `Some` arm borrows from the typed
27778        // slot's own [`String`] storage — same-address invariant with
27779        // `p.affinity.as_deref().unwrap()`. Pins against a future
27780        // silent detour that allocated a fresh `String`
27781        // (`self.affinity.clone().map(...)` in the body would type-
27782        // check but silently drop the borrow, and every downstream
27783        // consumer that assumed the returned slice outlives `&self`
27784        // would break on a stale-reference use-after-free — the
27785        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
27786        // gate reads the accessor's `&str` return through the
27787        // [`validate_placement_affinity`] `&str` parameter and would
27788        // silently misbehave if this accessor produced a detached
27789        // copy). Peer of the sibling per-`:placement`
27790        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
27791        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
27792        // extends the discipline onto the sibling per-`:placement`
27793        // M3-Adaptive-compression-hint arm.
27794        let p = Placement {
27795            estrategia: PlacementStrategy::Replicated,
27796            clusters: vec!["rio".into()],
27797            affinity: Some("data-locality".into()),
27798            shard_key: None,
27799        };
27800        let hint = p.affinity().expect("Some arm");
27801        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
27802        assert_eq!(
27803            hint.as_ptr(),
27804            storage_slice.as_ptr(),
27805            "Placement::affinity must borrow from the .affinity \
27806             String's backing storage — a fresh allocation here means \
27807             the accessor no longer names the substrate-primitive typed \
27808             dispatch and every downstream consumer would silently \
27809             carry a detached copy",
27810        );
27811        assert_eq!(
27812            hint.len(),
27813            storage_slice.len(),
27814            "Placement::affinity and .affinity.as_deref() must byte-\
27815             equal in length as well as in address",
27816        );
27817    }
27818
27819    #[test]
27820    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
27821        // The canonical per-`:placement` distribution-strategy-scalar
27822        // pin: [`Placement::estrategia`] must return the `:placement
27823        // :estrategia` field verbatim as a [`PlacementStrategy`],
27824        // `Copy`-projected from the typed slot's own `PlacementStrategy`
27825        // storage across every variant in the closed accept-set
27826        // (`SingleNode` — Erlang/OTP distributed-app takeover;
27827        // `Replicated` — active-active across every named cluster;
27828        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
27829        // against a future silent detour that re-derived the strategy
27830        // from a peer axis (an accidental fallback to
27831        // `if shard_key.is_some() { Sharded } else { Replicated }`
27832        // collapse that read the shard-key axis into the strategy
27833        // discriminator), a variant remap the operator authors on one
27834        // consumer without the other, or a stale-derive detour that
27835        // substituted [`PlacementStrategy::default`] when the field
27836        // held any explicit variant (which would silently collapse the
27837        // distinction between "author explicitly declared `:estrategia
27838        // Replicated`" and "author omitted the slot and inherited the
27839        // default" the future per-cluster override slot depends on).
27840        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
27841        // pin on the `Copy`-return `u16` scalar axis — same "the
27842        // substrate-primitive accessor must byte-equal the raw field
27843        // access verbatim across every author-declared value" discipline
27844        // extended onto the per-`:placement` distribution-strategy
27845        // `Copy`-composite-enum scalar axis.
27846        for estrategia in [
27847            PlacementStrategy::SingleNode,
27848            PlacementStrategy::Replicated,
27849            PlacementStrategy::Sharded,
27850        ] {
27851            // Route the paired `:shard-key` fixture-builder through the
27852            // typed cross-slot invariant predicate
27853            // [`PlacementStrategy::requires_shard_key`] rather than the
27854            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
27855            // arm-identity predicate — same discipline the sibling
27856            // `placement_strategy_variants_round_trip` fixture builder now
27857            // reads through.
27858            let shard_key = estrategia
27859                .requires_shard_key()
27860                .then(|| "tenantId".to_string());
27861            let p = Placement {
27862                estrategia,
27863                clusters: vec!["rio".into()],
27864                affinity: None,
27865                shard_key,
27866            };
27867            assert_eq!(
27868                p.estrategia(),
27869                estrategia,
27870                "Placement::estrategia must return :placement :estrategia \
27871                 verbatim (got {:?}, expected {estrategia:?})",
27872                p.estrategia(),
27873            );
27874            assert_eq!(
27875                p.estrategia(),
27876                p.estrategia,
27877                "Placement::estrategia accessor and .estrategia field \
27878                 access must byte-equal — the accessor is the substrate-\
27879                 primitive typed dispatch every downstream distribution-\
27880                 strategy consumer must route through",
27881            );
27882        }
27883    }
27884
27885    #[test]
27886    fn validate_placement_reads_through_lifted_estrategia_accessor() {
27887        // Three-consumer coherence pin: the
27888        // [`AplicacaoSpec::validate_placement`]
27889        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
27890        // `estrategia:` field (which reads through
27891        // [`Placement::estrategia`] to name the strategy the empty
27892        // `:clusters` list was declared against), the same method's
27893        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
27894        // reads through [`Placement::estrategia`] to fan across the
27895        // shape-gate cascades), and the non-`Sharded`-arm
27896        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
27897        // `estrategia:` field (which reads through
27898        // [`Placement::estrategia`] to name the strategy the declared-
27899        // but-inert `:shard-key` was authored under) must all key off
27900        // the lifted accessor, so any future rebrand on the typed
27901        // slot's reader shape lands at exactly one place. Pins the
27902        // three-site coherence by exercising each error surface end-
27903        // to-end and asserting the surfaced `estrategia:` field byte-
27904        // equals the accessor's return. Peer of the sibling per-
27905        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
27906        // pin on the M3 mesh-slot `Copy`-return scalar axis.
27907
27908        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
27909        // whose `estrategia:` field must byte-equal the accessor's return
27910        // for every variant in the closed accept-set.
27911        for estrategia in [
27912            PlacementStrategy::SingleNode,
27913            PlacementStrategy::Replicated,
27914            PlacementStrategy::Sharded,
27915        ] {
27916            let mut spec = three_member_spec();
27917            spec.placement.estrategia = estrategia;
27918            spec.placement.clusters = Vec::new();
27919            // Route the paired `:shard-key` spec-mutator through the typed
27920            // cross-slot invariant predicate
27921            // [`PlacementStrategy::requires_shard_key`] rather than the
27922            // [`gen_platform::IsVariant`]-derived
27923            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
27924            // same discipline the sibling
27925            // `placement_strategy_variants_round_trip` and
27926            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
27927            // fixture builders now read through.
27928            spec.placement.shard_key = estrategia
27929                .requires_shard_key()
27930                .then(|| "tenantId".to_string());
27931            let err = spec.validate().unwrap_err();
27932            match err {
27933                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
27934                    assert_eq!(
27935                        e,
27936                        spec.placement.estrategia(),
27937                        "PlacementWithoutClusters.estrategia must byte-equal \
27938                         Placement::estrategia() — the error carrier reads \
27939                         through the lifted accessor",
27940                    );
27941                }
27942                other => panic!(
27943                    "expected PlacementWithoutClusters, got {other:?} for \
27944                     estrategia={estrategia:?}"
27945                ),
27946            }
27947        }
27948
27949        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
27950        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
27951        // must byte-equal the accessor's return for both non-`Sharded`
27952        // strategies.
27953        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
27954            let mut spec = three_member_spec();
27955            spec.placement.estrategia = estrategia;
27956            spec.placement.shard_key = Some("tenantId".into());
27957            let err = spec.validate().unwrap_err();
27958            match err {
27959                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
27960                    assert_eq!(
27961                        e,
27962                        spec.placement.estrategia(),
27963                        "ShardKeyOnNonSharded.estrategia must byte-equal \
27964                         Placement::estrategia() — the non-Sharded-arm \
27965                         refusal reads through the lifted accessor",
27966                    );
27967                }
27968                other => panic!(
27969                    "expected ShardKeyOnNonSharded, got {other:?} for \
27970                     estrategia={estrategia:?}"
27971                ),
27972            }
27973        }
27974    }
27975
27976    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
27977    //
27978    // The [`Placement::clusters`] accessor lift is the second slice-return
27979    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
27980    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
27981    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
27982    // below cover (1) the accessor's byte-equal projection against the raw
27983    // field access across the empty / singleton / cohort fixtures the
27984    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
27985    // and the per-cluster validate loop fan between, and (2) the two-
27986    // consumer coherence of the paired pre-flight refusal probe and the
27987    // per-cluster validate loop routing through the accessor on both arms.
27988
27989    #[test]
27990    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
27991        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
27992        // [`Placement::clusters`] must return the `:placement :clusters`
27993        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
27994        // the same backing buffer the raw `self.clusters.as_slice()`
27995        // field access borrows from, byte-equal across every
27996        // representative fixture in the accept-set — the empty slice
27997        // (the pre-validation sentinel every
27998        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
27999        // the singleton slice (the minimal `SingleNode`-shape cohort),
28000        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
28001        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
28002        //
28003        // Pins against a future silent detour that returned
28004        // `&Vec<String>` (which would type-check but leak the storage-
28005        // side `Vec`'s grow/push/reserve surface no consumer of the
28006        // typed view reaches for), a fresh-allocated `Vec<String>` copy
28007        // (which would type-check via a coercion but silently break
28008        // every downstream caller that relied on the slice sharing the
28009        // backing buffer's identity), or an out-of-order or length-
28010        // drifted projection (which would silently split the paired
28011        // pre-flight `.is_empty()` refusal probe's input from the per-
28012        // cluster validate loop's traversal input).
28013        //
28014        // Peer of the sibling M2
28015        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
28016        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
28017        // `:supervisor` static-child-list axis, extended onto the M3
28018        // per-`:placement` distribution-target-list `Vec`-carry axis.
28019        let fixtures: Vec<Vec<String>> = vec![
28020            Vec::new(),
28021            vec!["rio".into()],
28022            vec!["rio".into(), "mar".into()],
28023            vec!["rio".into(), "mar".into(), "plo".into()],
28024        ];
28025        for clusters in fixtures {
28026            let p = Placement {
28027                clusters: clusters.clone(),
28028                ..Placement::default()
28029            };
28030            assert_eq!(
28031                p.clusters(),
28032                clusters.as_slice(),
28033                "Placement::clusters must return :placement :clusters \
28034                 verbatim (got {:?}, expected {:?})",
28035                p.clusters(),
28036                clusters.as_slice(),
28037            );
28038            assert_eq!(
28039                p.clusters(),
28040                p.clusters.as_slice(),
28041                "Placement::clusters accessor and .clusters.as_slice() \
28042                 field access must byte-equal — the accessor is the \
28043                 substrate-primitive typed dispatch every downstream \
28044                 cluster-pool consumer must route through",
28045            );
28046            assert_eq!(
28047                p.clusters().len(),
28048                p.clusters.len(),
28049                "Placement::clusters().len() must byte-equal \
28050                 self.clusters.len() — a length-drift would silently \
28051                 split the paired pre-flight `.is_empty()` refusal \
28052                 probe input from the per-cluster validate loop's \
28053                 traversal input",
28054            );
28055        }
28056    }
28057
28058    #[test]
28059    fn validate_placement_reads_through_lifted_clusters_accessor() {
28060        // Two-consumer coherence pin: the
28061        // [`AplicacaoSpec::validate_placement`] pre-flight
28062        // `self.placement.clusters().is_empty()` refusal probe (which
28063        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
28064        // the accessor projects the empty slice) and the per-cluster
28065        // validate loop's `for c in self.placement.clusters()`
28066        // traversal (which must reach every entry in the same order
28067        // the accessor projects, so both the per-entry value-shape
28068        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
28069        // and the duplicate-detection HashSet insert that trips
28070        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
28071        // accessor's projection) must both key off the lifted
28072        // accessor, so any future rebrand on the typed slot's reader
28073        // shape lands at exactly one place. Pins the two-site
28074        // coherence by exercising each production consumer end-to-end:
28075        // (1) the `PlacementWithoutClusters` refusal under the empty
28076        // slice, (2) the `PlacementClusterInvalid` refusal fires on
28077        // the second entry of a two-cluster cohort whose head is
28078        // valid but tail is not (which requires the loop to reach the
28079        // second entry through the accessor), and (3) the
28080        // `PlacementClusterDuplicate` refusal fires on the second
28081        // entry of a two-cluster cohort that shares a name (which
28082        // requires the loop to reach both entries — a first-entry-only
28083        // projection would silently pass since the dedup HashSet has
28084        // room for the first insert).
28085        //
28086        // Peer of the sibling M2
28087        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
28088        // (bc92bce) coherence pin on the per-`:supervisor` static-
28089        // child-list axis, extended onto the M3 per-`:placement`
28090        // distribution-target-list `Vec`-carry axis.
28091
28092        // (1) Pre-flight `.is_empty()` probe: the empty slice must
28093        // trip `PlacementWithoutClusters`.
28094        let mut spec = three_member_spec();
28095        spec.placement.clusters = Vec::new();
28096        match spec.validate().unwrap_err() {
28097            AplicacaoError::PlacementWithoutClusters { .. } => {}
28098            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
28099        }
28100        assert!(
28101            spec.placement.clusters().is_empty(),
28102            "the pre-flight refusal input must be the empty slice per \
28103             the accessor's projection",
28104        );
28105
28106        // (2) Per-cluster validate loop: a two-cluster cohort with an
28107        // invalid tail entry must trip `PlacementClusterInvalid` on
28108        // the tail — the loop must reach the second entry through
28109        // the accessor.
28110        let mut spec = three_member_spec();
28111        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
28112        match spec.validate().unwrap_err() {
28113            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
28114                assert_eq!(
28115                    cluster, "BAD_CLUSTER",
28116                    "PlacementClusterInvalid.cluster must carry the \
28117                     tail entry the loop reached through the accessor",
28118                );
28119            }
28120            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
28121        }
28122        assert_eq!(
28123            spec.placement.clusters().len(),
28124            2,
28125            "the per-cluster validate loop's traversal input must be \
28126             a two-element slice per the accessor's projection",
28127        );
28128
28129        // (3) Per-cluster validate loop: a two-cluster cohort that
28130        // shares a name must trip `PlacementClusterDuplicate` on the
28131        // second entry — the loop must reach both entries through the
28132        // accessor for the dedup HashSet's second insert to collide.
28133        let mut spec = three_member_spec();
28134        spec.placement.clusters = vec!["rio".into(), "rio".into()];
28135        match spec.validate().unwrap_err() {
28136            AplicacaoError::PlacementClusterDuplicate { cluster } => {
28137                assert_eq!(
28138                    cluster, "rio",
28139                    "PlacementClusterDuplicate.cluster must carry the \
28140                     shared cluster name verbatim",
28141                );
28142            }
28143            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
28144        }
28145        assert_eq!(
28146            spec.placement.clusters().len(),
28147            2,
28148            "the per-cluster validate loop's traversal input must be \
28149             a two-element slice per the accessor's projection",
28150        );
28151    }
28152
28153    #[test]
28154    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
28155        // The canonical per-`:membros` member-list-slice-shape pin:
28156        // [`AplicacaoSpec::membros`] must return the `:membros` typed
28157        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
28158        // same backing buffer the raw `self.membros.as_slice()` field
28159        // access borrows from, byte-equal across every representative
28160        // fixture in the accept-set — the empty slice (the pre-
28161        // validation sentinel every [`AplicacaoError::NoMembros`]
28162        // refusal keys off), the singleton slice (the minimal one-
28163        // Servico Aplicacao shape), and multi-entry cohorts (the peer
28164        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
28165        // load-bearing identity of the application graph).
28166        //
28167        // Pins against a future silent detour that returned
28168        // `&Vec<Membro>` (which would type-check but leak the storage-
28169        // side `Vec`'s grow/push/reserve surface no consumer of the
28170        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
28171        // (which would type-check via a coercion but silently break
28172        // every downstream caller that relied on the slice sharing the
28173        // backing buffer's identity), or an out-of-order or length-
28174        // drifted projection (which would silently split the paired
28175        // `HashSet<&str>` name-set seed's collect input from the
28176        // pre-flight `.is_empty()` refusal probe's input from the per-
28177        // member validate loop's traversal input from the
28178        // programs.yaml emitter's per-entry fan-out loop's input from
28179        // the `feira app graph` per-member print traversal's input).
28180        //
28181        // Peer of the sibling M2
28182        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
28183        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
28184        // `:supervisor` static-child-list axis and the sibling M3
28185        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
28186        // (a6e18d7) `&[String]` byte-equal pin on the per-
28187        // `:placement` distribution-target-list axis — extends the
28188        // slice-return-accessor byte-equal-projection discipline onto
28189        // the outermost M3 mesh-slot type's per-Aplicacao member-list
28190        // `Vec`-carry axis.
28191        let fixtures: Vec<Vec<Membro>> = vec![
28192            Vec::new(),
28193            vec![membro("catalog", "^0.1")],
28194            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28195            vec![
28196                membro("catalog", "^0.1"),
28197                membro("cart", "^0.1"),
28198                membro("payment", "^0.2"),
28199            ],
28200        ];
28201        for membros in fixtures {
28202            let s = AplicacaoSpec {
28203                membros: membros.clone(),
28204                contratos: Vec::new(),
28205                politicas: MeshPolicy::default(),
28206                placement: Placement::default(),
28207                entrada: None,
28208            };
28209            assert_eq!(
28210                s.membros(),
28211                membros.as_slice(),
28212                "AplicacaoSpec::membros must return :membros verbatim \
28213                 (got {:?}, expected {:?})",
28214                s.membros(),
28215                membros.as_slice(),
28216            );
28217            assert_eq!(
28218                s.membros(),
28219                s.membros.as_slice(),
28220                "AplicacaoSpec::membros accessor and .membros.as_slice() \
28221                 field access must byte-equal — the accessor is the \
28222                 substrate-primitive typed dispatch every downstream \
28223                 member-list consumer must route through",
28224            );
28225            assert_eq!(
28226                s.membros().len(),
28227                s.membros.len(),
28228                "AplicacaoSpec::membros().len() must byte-equal \
28229                 self.membros.len() — a length-drift would silently \
28230                 split the paired `HashSet<&str>` name-set seed's \
28231                 collect input from the pre-flight `.is_empty()` \
28232                 refusal probe input from the per-member validate \
28233                 loop's traversal input",
28234            );
28235        }
28236    }
28237
28238    #[test]
28239    fn validate_reads_through_lifted_membros_accessor() {
28240        // Three-consumer coherence pin: the
28241        // [`AplicacaoSpec::validate_membros`] pre-flight
28242        // `self.membros().is_empty()` refusal probe (which must trip
28243        // [`AplicacaoError::NoMembros`] when the accessor projects the
28244        // empty slice), the same method's per-member validate loop's
28245        // `for m in self.membros()` traversal (which must reach every
28246        // entry in the same order the accessor projects, so both the
28247        // per-entry empty-`:caixa` gate that trips
28248        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
28249        // detection `insert_first_seen` that trips
28250        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
28251        // projection), and the peer [`AplicacaoSpec::validate`]'s
28252        // `HashSet<&str>` name-set seed's
28253        // `self.membros().iter().map(Membro::nome).collect()` collect
28254        // input (which every `:contratos` `:de` / `:para` membership
28255        // lookup rejects an unknown name against) must all three key
28256        // off the lifted accessor, so any future rebrand on the typed
28257        // slot's reader shape lands at exactly one place. Pins the
28258        // three-site coherence by exercising each production consumer
28259        // end-to-end: (1) the `NoMembros` refusal under the empty
28260        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
28261        // second entry of a two-member cohort whose head is valid but
28262        // tail has an empty `:caixa` (which requires the loop to
28263        // reach the second entry through the accessor), and (3) the
28264        // `MembroDuplicate` refusal fires on the second entry of a
28265        // two-member cohort that shares a `:caixa` name (which
28266        // requires the loop to reach both entries through the
28267        // accessor for the dedup HashSet's second insert to collide).
28268        //
28269        // Peer of the sibling M2
28270        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
28271        // (bc92bce) coherence pin on the per-`:supervisor` static-
28272        // child-list axis and the sibling M3
28273        // `validate_placement_reads_through_lifted_clusters_accessor`
28274        // (a6e18d7) coherence pin on the per-`:placement` distribution-
28275        // target-list axis — extends the slice-return-accessor
28276        // multi-consumer coherence discipline onto the outermost M3
28277        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
28278
28279        // (1) Pre-flight `.is_empty()` probe: the empty slice must
28280        // trip `NoMembros`.
28281        let mut spec = three_member_spec();
28282        spec.membros = Vec::new();
28283        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
28284        assert!(
28285            spec.membros().is_empty(),
28286            "the pre-flight refusal input must be the empty slice per \
28287             the accessor's projection",
28288        );
28289
28290        // (2) Per-member validate loop: a two-member cohort with an
28291        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
28292        // the tail — the loop must reach the second entry through
28293        // the accessor.
28294        let mut spec = three_member_spec();
28295        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
28296        assert_eq!(
28297            spec.validate().unwrap_err(),
28298            AplicacaoError::MembroCaixaEmpty,
28299        );
28300        assert_eq!(
28301            spec.membros().len(),
28302            2,
28303            "the per-member validate loop's traversal input must be \
28304             a two-element slice per the accessor's projection",
28305        );
28306
28307        // (3) Per-member validate loop: a two-member cohort that
28308        // shares a `:caixa` name must trip `MembroDuplicate` on the
28309        // second entry — the loop must reach both entries through the
28310        // accessor for the dedup HashSet's second insert to collide.
28311        let mut spec = three_member_spec();
28312        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
28313        match spec.validate().unwrap_err() {
28314            AplicacaoError::MembroDuplicate { caixa } => {
28315                assert_eq!(
28316                    caixa, "catalog",
28317                    "MembroDuplicate.caixa must carry the shared \
28318                     member name verbatim",
28319                );
28320            }
28321            other => panic!("expected MembroDuplicate, got {other:?}"),
28322        }
28323        assert_eq!(
28324            spec.membros().len(),
28325            2,
28326            "the per-member validate loop's traversal input must be \
28327             a two-element slice per the accessor's projection",
28328        );
28329    }
28330
28331    #[test]
28332    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
28333        // The canonical per-`:contratos` contract-list-slice-shape pin:
28334        // [`AplicacaoSpec::contratos`] must return the `:contratos`
28335        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
28336        // slice-view over the same backing buffer the raw
28337        // `self.contratos.as_slice()` field access borrows from, byte-
28338        // equal across every representative fixture in the accept-set —
28339        // the empty slice (the pre-validation "internal-only mesh" shape
28340        // an Aplicacao whose members exchange no typed edges renders
28341        // through), the singleton slice (the minimal one-edge Aplicacao
28342        // shape), and multi-entry cohorts (the peer multi-edge shapes
28343        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
28344        // of the application graph).
28345        //
28346        // Pins against a future silent detour that returned
28347        // `&Vec<WitContract>` (which would type-check but leak the
28348        // storage-side `Vec`'s grow/push/reserve surface no consumer of
28349        // the typed view reaches for), a fresh-allocated
28350        // `Vec<WitContract>` copy (which would type-check via a coercion
28351        // but silently break every downstream caller that relied on the
28352        // slice sharing the backing buffer's identity), or an out-of-
28353        // order or length-drifted projection (which would silently split
28354        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
28355        // seed's traversal input from the `detect_sync_cycles` per-edge
28356        // adjacency-list seed's traversal input from the
28357        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
28358        // BTreeMap grouping loop's traversal input from the
28359        // `feira app graph` per-contract print traversal's input).
28360        //
28361        // Peer of the immediately-adjacent sibling M3
28362        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
28363        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
28364        // node-list axis, the sibling M3
28365        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
28366        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
28367        // distribution-target-list axis, and the sibling M2
28368        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
28369        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
28370        // `:supervisor` static-child-list axis — extends the slice-
28371        // return-accessor byte-equal-projection discipline onto the
28372        // outermost M3 mesh-slot type's per-Aplicacao contract-list
28373        // `Vec`-carry axis, closing the last unlifted per-
28374        // `AplicacaoSpec` `Vec`-carry axis.
28375        let fixtures: Vec<Vec<WitContract>> = vec![
28376            Vec::new(),
28377            vec![contract_http("cart", "catalog", "/products/:id")],
28378            vec![
28379                contract_http("cart", "catalog", "/products/:id"),
28380                contract_http("cart", "payment", "/charge"),
28381            ],
28382            vec![
28383                contract_http("cart", "catalog", "/products/:id"),
28384                contract_http("cart", "payment", "/charge"),
28385                contract_http("payment", "catalog", "/audit"),
28386            ],
28387        ];
28388        for contratos in fixtures {
28389            let s = AplicacaoSpec {
28390                membros: vec![
28391                    membro("catalog", "^0.1"),
28392                    membro("cart", "^0.1"),
28393                    membro("payment", "^0.2"),
28394                ],
28395                contratos: contratos.clone(),
28396                politicas: MeshPolicy::default(),
28397                placement: Placement::default(),
28398                entrada: None,
28399            };
28400            assert_eq!(
28401                s.contratos(),
28402                contratos.as_slice(),
28403                "AplicacaoSpec::contratos must return :contratos verbatim \
28404                 (got {:?}, expected {:?})",
28405                s.contratos(),
28406                contratos.as_slice(),
28407            );
28408            assert_eq!(
28409                s.contratos(),
28410                s.contratos.as_slice(),
28411                "AplicacaoSpec::contratos accessor and \
28412                 .contratos.as_slice() field access must byte-equal — \
28413                 the accessor is the substrate-primitive typed dispatch \
28414                 every downstream contract-list consumer must route \
28415                 through",
28416            );
28417            assert_eq!(
28418                s.contratos().len(),
28419                s.contratos.len(),
28420                "AplicacaoSpec::contratos().len() must byte-equal \
28421                 self.contratos.len() — a length-drift would silently \
28422                 split the paired per-edge validate-loop's traversal \
28423                 input from the sync-cycle adjacency-list seed's \
28424                 traversal input from the cilium_network_policies \
28425                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
28426                 input from the `feira app graph` per-contract print \
28427                 traversal's input",
28428            );
28429        }
28430    }
28431
28432    #[test]
28433    fn validate_reads_through_lifted_contratos_accessor() {
28434        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
28435        // per-`:contratos` validate-loop's `for c in self.contratos()`
28436        // traversal (which must reach every entry in the same order the
28437        // accessor projects, so both the per-entry
28438        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
28439        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
28440        // dedup `HashSet` insert key off the accessor's projection),
28441        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
28442        // `for c in self.contratos()` adjacency-list seed (which drives
28443        // the sync-subgraph deadlock-detection gate via
28444        // [`AplicacaoError::SyncCycle`]), and the peer
28445        // [`caixa_mesh::cilium_network_policies`]'s
28446        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
28447        // grouping loop (which drives the per-CNP fan-out) must all
28448        // three key off the lifted accessor, so any future rebrand on
28449        // the typed slot's reader shape lands at exactly one place. Pins
28450        // the three-site coherence by exercising the two caixa-core
28451        // production consumers end-to-end: (1) the empty-`:contratos`
28452        // slice must validate without a per-edge diagnostic (the
28453        // per-edge loop is a no-op under the empty projection), (2) the
28454        // `ContratoMemberMissing` refusal fires on the second entry of a
28455        // two-edge cohort whose head references a valid member but tail
28456        // references a phantom name (which requires the loop to reach
28457        // the second entry through the accessor), and (3) the
28458        // `SyncCycle` refusal fires on a self-referential two-edge
28459        // cohort through the sync-cycle detector's peer projection
28460        // (which requires the detector to iterate the accessor's
28461        // projection to add the back-edge to its adjacency list).
28462        //
28463        // Peer of the sibling M3
28464        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28465        // three-consumer coherence pin on the per-`:membros` node-list
28466        // axis and the sibling M3
28467        // `validate_placement_reads_through_lifted_clusters_accessor`
28468        // (a6e18d7) coherence pin on the per-`:placement` distribution-
28469        // target-list axis — extends the slice-return-accessor multi-
28470        // consumer coherence discipline onto the outermost M3 mesh-slot
28471        // type's per-Aplicacao contract-list `Vec`-carry axis.
28472
28473        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
28474        // and no per-edge diagnostic surfaces. Validate succeeds on
28475        // the well-formed `:membros` head.
28476        let mut spec = three_member_spec();
28477        spec.contratos = Vec::new();
28478        assert!(
28479            spec.validate().is_ok(),
28480            "empty :contratos must validate — the per-edge loop is a \
28481             no-op under the accessor's empty projection",
28482        );
28483        assert!(
28484            spec.contratos().is_empty(),
28485            "the per-edge validate loop's traversal input must be the \
28486             empty slice per the accessor's projection",
28487        );
28488
28489        // (2) Per-edge validate loop: a two-edge cohort whose tail
28490        // references a phantom `:para` member must trip
28491        // `ContratoMemberMissing` on the tail — the loop must reach
28492        // the second entry through the accessor for the membership
28493        // lookup to fail on the phantom name.
28494        let mut spec = three_member_spec();
28495        spec.contratos = vec![
28496            contract_http("cart", "catalog", "/products/:id"),
28497            contract_http("cart", "phantom", "/x"),
28498        ];
28499        let err = spec.validate().unwrap_err();
28500        assert!(
28501            matches!(
28502                err,
28503                AplicacaoError::ContratoMemberMissing { ref caixa }
28504                    if caixa == "phantom"
28505            ),
28506            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
28507        );
28508        assert_eq!(
28509            spec.contratos().len(),
28510            2,
28511            "the per-edge validate loop's traversal input must be \
28512             a two-element slice per the accessor's projection",
28513        );
28514
28515        // (3) Sync-cycle detector: a two-edge synchronous cohort
28516        // whose second edge closes the sync-subgraph back onto the
28517        // first must trip [`AplicacaoError::ContratoCycle`] — the
28518        // detector must iterate the accessor's projection to add
28519        // both edges to its adjacency list, so a length-drift on
28520        // the accessor's projection would silently disagree with
28521        // the sync-cycle detector on which edge closes the loop.
28522        // Peer projection to the `validate` per-edge loop above:
28523        // the sync-cycle detector routes through the same lifted
28524        // accessor, so a rebrand of the reader shape lands at one
28525        // place. Uses a two-edge cohort (cart → catalog → cart)
28526        // because the per-edge `ContratoSelfLoop` gate fires before
28527        // the sync-cycle detector on a single self-referential edge
28528        // (`cart → cart`) — the cycle-detector's input must be a
28529        // multi-edge cohort for its per-edge traversal input to be
28530        // observably wider than the per-edge validate loop's input.
28531        let mut spec = three_member_spec();
28532        spec.contratos = vec![
28533            contract_http("cart", "catalog", "/products/:id"),
28534            contract_http("catalog", "cart", "/callback"),
28535        ];
28536        let err = spec.validate().unwrap_err();
28537        assert!(
28538            matches!(err, AplicacaoError::ContratoCycle { .. }),
28539            "expected ContratoCycle from the sync-cycle detector on a \
28540             two-edge back-edge cohort, got {err:?}",
28541        );
28542        assert_eq!(
28543            spec.contratos().len(),
28544            2,
28545            "the sync-cycle detector's traversal input must be a \
28546             two-element slice per the accessor's projection",
28547        );
28548    }
28549
28550    #[test]
28551    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
28552        // The canonical per-`:politicas` outer-composite-reference-shape
28553        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
28554        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
28555        // the same backing storage the raw `&self.politicas` field
28556        // access borrows from, byte-equal across every representative
28557        // fixture in the accept-set — the default `MeshPolicy` (the
28558        // author-empty "no policy on any axis" shape whose
28559        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
28560        // shapes carrying one axis at a time
28561        // (`{mtls_required, timeout, retries, circuit_breaker,
28562        // rate_limit}` — the minimal five-axis fan-out over the
28563        // per-axis lifted accessor family every downstream mesh-artifact
28564        // emitter dispatches on), and the multi-axis composite (the
28565        // canonical `three_member_spec` fixture's `{timeout, retries,
28566        // mtls_required}` triple — the load-bearing shape every
28567        // Aplicacao-scoped fixture in this suite constructs).
28568        //
28569        // Pins against a future silent detour that returned a fresh-
28570        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
28571        // impl but silently break every downstream caller that relied
28572        // on the reference sharing the composite's backing identity), a
28573        // reference to an operator-resolved overlay (the future
28574        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
28575        // acknowledges — its resolution must land at exactly this
28576        // accessor body, not silently divert the raw slot away from a
28577        // second consumer), or an axis-shuffled projection (a future
28578        // detour that swapped `timeout` and `retries` through the
28579        // accessor would silently split the paired `validate_politicas`
28580        // per-axis bracket-dispatch's traversal input from the peer
28581        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
28582        // emitter's fan-out input from the peer
28583        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
28584        // overlay emitter's fan-out input).
28585        //
28586        // Peer of the sibling M3
28587        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
28588        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
28589        // node-list `Vec`-carry axis and the sibling M3
28590        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
28591        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
28592        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
28593        // accessor byte-equal-projection discipline onto the outermost
28594        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
28595        // reference axis, the first `&Composite`-return accessor on the
28596        // outer [`AplicacaoSpec`] type.
28597        let fixtures: Vec<MeshPolicy> = vec![
28598            MeshPolicy::default(),
28599            MeshPolicy {
28600                mtls_required: Some(true),
28601                ..MeshPolicy::default()
28602            },
28603            MeshPolicy {
28604                mtls_required: Some(false),
28605                ..MeshPolicy::default()
28606            },
28607            MeshPolicy {
28608                timeout: Some(Duration::from_secs(30)),
28609                ..MeshPolicy::default()
28610            },
28611            MeshPolicy {
28612                retries: Some(3),
28613                ..MeshPolicy::default()
28614            },
28615            MeshPolicy {
28616                circuit_breaker: Some(CircuitBreaker {
28617                    max_failures: 5,
28618                    window: Duration::from_secs(30),
28619                }),
28620                ..MeshPolicy::default()
28621            },
28622            MeshPolicy {
28623                rate_limit: Some(RateLimit {
28624                    rate: 100,
28625                    window: Duration::from_secs(1),
28626                }),
28627                ..MeshPolicy::default()
28628            },
28629            MeshPolicy {
28630                timeout: Some(Duration::from_secs(30)),
28631                retries: Some(3),
28632                mtls_required: Some(true),
28633                ..MeshPolicy::default()
28634            },
28635        ];
28636        for politicas in fixtures {
28637            let s = AplicacaoSpec {
28638                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
28639                contratos: Vec::new(),
28640                politicas: politicas.clone(),
28641                placement: Placement::default(),
28642                entrada: None,
28643            };
28644            assert_eq!(
28645                *s.politicas(),
28646                politicas,
28647                "AplicacaoSpec::politicas must return :politicas verbatim \
28648                 (got {:?}, expected {:?})",
28649                s.politicas(),
28650                politicas,
28651            );
28652            assert!(
28653                std::ptr::eq(s.politicas(), &s.politicas),
28654                "AplicacaoSpec::politicas accessor and &self.politicas \
28655                 field access must borrow the same backing storage — \
28656                 the accessor is the substrate-primitive typed dispatch \
28657                 every downstream mesh-policy composite consumer must \
28658                 route through, and a reference-identity split would \
28659                 silently break every consumer that relied on the \
28660                 borrow sharing the composite's storage",
28661            );
28662            assert_eq!(
28663                s.politicas().is_empty(),
28664                s.politicas.is_empty(),
28665                "AplicacaoSpec::politicas().is_empty() must byte-equal \
28666                 self.politicas.is_empty() — an emptiness-drift would \
28667                 silently split the paired `validate_politicas` \
28668                 per-axis bracket-dispatch's seed from the peer \
28669                 caixa-mesh CNP mTLS-overlay emitter's key from the \
28670                 peer caixa-mesh HTTPRoute timeout+retry overlay \
28671                 emitter's key",
28672            );
28673        }
28674    }
28675
28676    #[test]
28677    fn validate_politicas_reads_through_lifted_politicas_accessor() {
28678        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
28679        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
28680        // followed by the per-axis fan-out `p.timeout()` /
28681        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
28682        // the lifted axis-level accessor family) must key off the
28683        // lifted outer accessor, so any future rebrand on the typed
28684        // slot's outer-composite reader shape lands at exactly one
28685        // place. Pins the multi-axis coherence by exercising each
28686        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
28687        // a `Some(Duration::ZERO)` timeout under the outer accessor's
28688        // reference projection, (2) `PolicyRetriesZero` fires on a
28689        // `Some(0)` retries under the same projection, and (3) an
28690        // empty [`MeshPolicy::default`] passes `validate_politicas` —
28691        // the outer accessor's reference-projection reaches every
28692        // per-axis branch without silently short-circuiting any.
28693        //
28694        // Peer of the sibling M3
28695        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28696        // three-consumer coherence pin on the per-`:membros` node-list
28697        // axis and the sibling M3
28698        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
28699        // three-consumer coherence pin on the per-`:contratos`
28700        // edge-list axis — extends the multi-consumer coherence
28701        // discipline onto the outermost M3 mesh-slot type's per-
28702        // Aplicacao mesh-policy composite-reference axis, the first
28703        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
28704        // type.
28705
28706        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
28707        // reference projection: a `Some(Duration::ZERO)` timeout must
28708        // trip the zero-floor gate. The bracket-dispatch's first arm
28709        // reads `p.timeout()` on the reference returned by the outer
28710        // accessor.
28711        let mut spec = three_member_spec();
28712        spec.politicas.timeout = Some(Duration::ZERO);
28713        spec.politicas.retries = None;
28714        spec.politicas.circuit_breaker = None;
28715        spec.politicas.rate_limit = None;
28716        assert_eq!(
28717            spec.validate().unwrap_err(),
28718            AplicacaoError::PolicyTimeoutZero,
28719        );
28720        assert!(
28721            std::ptr::eq(spec.politicas(), &spec.politicas),
28722            "the `validate_politicas` per-axis bracket-dispatch's \
28723             traversal input must be the same backing composite the \
28724             accessor's reference projection borrows from",
28725        );
28726
28727        // (2) `PolicyRetriesZero` refusal under the outer accessor's
28728        // reference projection: a `Some(0)` retries must trip the
28729        // zero-floor gate. The bracket-dispatch's second arm reads
28730        // `p.retries()` on the reference returned by the outer accessor.
28731        let mut spec = three_member_spec();
28732        spec.politicas.timeout = None;
28733        spec.politicas.retries = Some(0);
28734        spec.politicas.circuit_breaker = None;
28735        spec.politicas.rate_limit = None;
28736        assert_eq!(
28737            spec.validate().unwrap_err(),
28738            AplicacaoError::PolicyRetriesZero,
28739        );
28740
28741        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
28742        // — every per-axis arm short-circuits on `None`, so the outer
28743        // accessor's reference projection reaches the fall-through
28744        // `Ok(())` without any per-axis refusal firing.
28745        let mut spec = three_member_spec();
28746        spec.politicas = MeshPolicy::default();
28747        assert!(
28748            spec.validate().is_ok(),
28749            "an empty `MeshPolicy` must pass `validate_politicas` — \
28750             every per-axis arm short-circuits on `None` under the \
28751             outer accessor's reference projection",
28752        );
28753        assert!(
28754            spec.politicas().is_empty(),
28755            "the outer accessor's reference projection must be the \
28756             empty composite per the `MeshPolicy::default()` fixture",
28757        );
28758    }
28759
28760    #[test]
28761    #[allow(clippy::too_many_lines)]
28762    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
28763        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
28764        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
28765        // must both key off the lifted axis-level accessors
28766        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
28767        // the peer `:circuit-breaker` / `:rate-limit` arms already
28768        // routing through [`MeshPolicy::circuit_breaker`] /
28769        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
28770        // per axis on the substrate primitive" shape at the fan-out
28771        // (four axes, four accessors, no raw-field-access site
28772        // anywhere on the bracket-dispatch). Pins the per-axis
28773        // coherence at the accept-set boundaries the bracket carves:
28774        //   1. accessor byte-equal to raw field on every representative
28775        //      accept-set value (`None`, sub-cap, at-cap, past-cap
28776        //      sentinel) — a future accessor drift that no longer
28777        //      shipped the raw slot verbatim would surface here,
28778        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
28779        //      routed through the accessor's projection, proving the
28780        //      first arm reads through the accessor rather than a
28781        //      silent-detour peer-axis field access,
28782        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
28783        //      through the accessor's projection, proving the second
28784        //      arm reads through the accessor,
28785        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
28786        //      passes validate under the accessor projection (paired
28787        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
28788        //      sibling axis), pinning the upper-boundary accept-arm
28789        //      also routes through the accessor.
28790        //
28791        // Peer of the sibling M3
28792        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
28793        // outer-composite-reference coherence pin (which asserts the
28794        // `let p = self.politicas()` seed); extends the discipline onto
28795        // the per-axis fan-out layer that consumes the seed's
28796        // reference. Same shape as
28797        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
28798        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
28799        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
28800        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
28801
28802        // (1) Accessor byte-equal to raw field on the `:timeout` axis
28803        // across the accept-set boundaries the bracket dispatch's
28804        // three-arm gate carves out
28805        // ([`crate::render::require_positive_canonical_bounded_duration`]
28806        // — zero-floor + canonical-form + upper-cap).
28807        for timeout in [
28808            None,
28809            Some(Duration::ZERO),
28810            Some(Duration::from_millis(1)),
28811            Some(POLICY_TIMEOUT_MAX),
28812        ] {
28813            let p = MeshPolicy {
28814                timeout,
28815                ..MeshPolicy::default()
28816            };
28817            assert_eq!(
28818                p.timeout(),
28819                p.timeout,
28820                "MeshPolicy::timeout accessor must byte-equal the raw \
28821                 .timeout field across every accept-set boundary the \
28822                 validate_politicas :timeout arm carves out — a drift \
28823                 here would silently split the validate bracket's arm \
28824                 from the peer caixa-mesh HTTPRoute timeout-overlay \
28825                 emitter's read",
28826            );
28827        }
28828
28829        // (2) Accessor byte-equal to raw field on the `:retries` axis
28830        // across the accept-set boundaries the bracket dispatch's
28831        // two-arm gate carves out
28832        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
28833        // + upper-cap).
28834        for retries in [
28835            None,
28836            Some(0u32),
28837            Some(1u32),
28838            Some(POLICY_RETRIES_MAX),
28839            Some(POLICY_RETRIES_MAX + 1),
28840            Some(u32::MAX),
28841        ] {
28842            let p = MeshPolicy {
28843                retries,
28844                ..MeshPolicy::default()
28845            };
28846            assert_eq!(
28847                p.retries(),
28848                p.retries,
28849                "MeshPolicy::retries accessor must byte-equal the raw \
28850                 .retries field across every accept-set boundary the \
28851                 validate_politicas :retries arm carves out — a drift \
28852                 here would silently split the validate bracket's arm \
28853                 from the peer caixa-mesh HTTPRoute retry-overlay \
28854                 emitter's read",
28855            );
28856        }
28857
28858        // (3) `PolicyTimeoutZero` fires on the accessor-projected
28859        // zero-floor boundary. A silent detour that no longer read
28860        // through `p.timeout()` (a peer-axis field read, an accidental
28861        // Option::and-then chain that collapsed the None arm to Some,
28862        // an accessor rebrand that clamped the return through the
28863        // upper cap) would fail to refuse here.
28864        let mut spec = three_member_spec();
28865        spec.politicas.timeout = Some(Duration::ZERO);
28866        spec.politicas.retries = None;
28867        spec.politicas.circuit_breaker = None;
28868        spec.politicas.rate_limit = None;
28869        assert_eq!(
28870            spec.politicas().timeout(),
28871            Some(Duration::ZERO),
28872            "the accessor projection must reflect the fixture's \
28873             `Some(Duration::ZERO)` :timeout verbatim",
28874        );
28875        assert_eq!(
28876            spec.validate().unwrap_err(),
28877            AplicacaoError::PolicyTimeoutZero,
28878            "the validate_politicas :timeout zero-floor arm must fire \
28879             through the lifted accessor's projection — a silent \
28880             detour to a peer-axis field would fail to refuse",
28881        );
28882
28883        // (4) `PolicyRetriesZero` fires on the accessor-projected
28884        // zero-floor boundary on the sibling `:retries` axis.
28885        let mut spec = three_member_spec();
28886        spec.politicas.timeout = None;
28887        spec.politicas.retries = Some(0);
28888        spec.politicas.circuit_breaker = None;
28889        spec.politicas.rate_limit = None;
28890        assert_eq!(
28891            spec.politicas().retries(),
28892            Some(0),
28893            "the accessor projection must reflect the fixture's \
28894             `Some(0)` :retries verbatim",
28895        );
28896        assert_eq!(
28897            spec.validate().unwrap_err(),
28898            AplicacaoError::PolicyRetriesZero,
28899            "the validate_politicas :retries zero-floor arm must fire \
28900             through the lifted accessor's projection — a silent \
28901             detour to a peer-axis field would fail to refuse",
28902        );
28903
28904        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
28905        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
28906        // must pass validate under the accessor projection — pins the
28907        // upper-boundary accept-arm also routes through the lifted
28908        // accessor (a drift that clamped or short-circuited at the
28909        // upper boundary would fail the whole-spec validate here).
28910        let mut spec = three_member_spec();
28911        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
28912        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
28913        spec.politicas.circuit_breaker = None;
28914        spec.politicas.rate_limit = None;
28915        assert_eq!(
28916            spec.politicas().timeout(),
28917            Some(POLICY_TIMEOUT_MAX),
28918            "the accessor projection must reflect the fixture's \
28919             at-cap :timeout verbatim",
28920        );
28921        assert_eq!(
28922            spec.politicas().retries(),
28923            Some(POLICY_RETRIES_MAX),
28924            "the accessor projection must reflect the fixture's \
28925             at-cap :retries verbatim",
28926        );
28927        assert!(
28928            spec.validate().is_ok(),
28929            "at-cap :timeout + :retries must pass validate under the \
28930             accessor projection — the upper-boundary accept-arm on \
28931             both axes routes through the lifted accessor",
28932        );
28933    }
28934
28935    #[test]
28936    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
28937        // The canonical per-`:placement` outer-composite-reference-shape
28938        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
28939        // typed `Placement` verbatim as a `&Placement` reference over the
28940        // same backing storage the raw `&self.placement` field access
28941        // borrows from, byte-equal across every representative fixture in
28942        // the accept-set — the default `Placement` (the substrate seed
28943        // shape whose [`PlacementStrategy::default`] evaluates to
28944        // `SingleNode` with an empty `:clusters` pool and both
28945        // optional-scalar axes `None`), and every canonical strategy /
28946        // cluster-pool / optional-scalar combination the
28947        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
28948        // three [`PlacementStrategy`] variants — `SingleNode`,
28949        // `Replicated`, `Sharded` — cross-projected with a non-empty
28950        // `:clusters` pool and, on the `Sharded` arm, a non-empty
28951        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
28952        // canonical `three_member_spec` `Replicated` fixture's
28953        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
28954        //
28955        // Pins against a future silent detour that returned a fresh-
28956        // cloned `Placement` copy (which would type-check via a `Clone`
28957        // impl but silently break every downstream caller that relied on
28958        // the reference sharing the composite's backing identity), a
28959        // reference to an operator-resolved overlay (the future per-
28960        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
28961        // acknowledges — its resolution must land at exactly this
28962        // accessor body, not silently divert the raw slot away from a
28963        // second consumer), or an axis-shuffled projection (a future
28964        // detour that swapped `clusters` and `affinity` through the
28965        // accessor would silently split the paired `validate_placement`
28966        // per-axis bracket-dispatch's traversal input from the peer
28967        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
28968        // programs.yaml distribution-annotation emitter's fan-out input
28969        // from the peer `feira app graph` per-Aplicacao print line's
28970        // input).
28971        //
28972        // Peer of the sibling M3
28973        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
28974        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
28975        // outer mesh-policy composite-reference axis, and of the sibling
28976        // slice-return `aplicacao_spec_membros_returns_membros_slice_
28977        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
28978        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
28979        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
28980        // the outer-accessor byte-equal-projection discipline onto the
28981        // outermost M3 mesh-slot type's per-Aplicacao distribution
28982        // composite-reference axis, the second `&Composite`-return
28983        // accessor on the outer [`AplicacaoSpec`] type.
28984        let fixtures: Vec<Placement> = vec![
28985            Placement::default(),
28986            Placement {
28987                estrategia: PlacementStrategy::SingleNode,
28988                clusters: vec!["rio".into()],
28989                affinity: None,
28990                shard_key: None,
28991            },
28992            Placement {
28993                estrategia: PlacementStrategy::Replicated,
28994                clusters: vec!["rio".into(), "mar".into()],
28995                affinity: None,
28996                shard_key: None,
28997            },
28998            Placement {
28999                estrategia: PlacementStrategy::Replicated,
29000                clusters: vec!["rio".into(), "mar".into()],
29001                affinity: Some("data-locality".into()),
29002                shard_key: None,
29003            },
29004            Placement {
29005                estrategia: PlacementStrategy::Sharded,
29006                clusters: vec!["rio".into(), "mar".into()],
29007                affinity: None,
29008                shard_key: Some("tenantId".into()),
29009            },
29010            Placement {
29011                estrategia: PlacementStrategy::Sharded,
29012                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
29013                affinity: Some("low-latency".into()),
29014                shard_key: Some("metadata.tenantId".into()),
29015            },
29016        ];
29017        for placement in fixtures {
29018            let s = AplicacaoSpec {
29019                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
29020                contratos: Vec::new(),
29021                politicas: MeshPolicy::default(),
29022                placement: placement.clone(),
29023                entrada: None,
29024            };
29025            assert_eq!(
29026                *s.placement(),
29027                placement,
29028                "AplicacaoSpec::placement must return :placement verbatim \
29029                 (got {:?}, expected {:?})",
29030                s.placement(),
29031                placement,
29032            );
29033            assert!(
29034                std::ptr::eq(s.placement(), &s.placement),
29035                "AplicacaoSpec::placement accessor and &self.placement \
29036                 field access must borrow the same backing storage — the \
29037                 accessor is the substrate-primitive typed dispatch every \
29038                 downstream distribution-composite consumer must route \
29039                 through, and a reference-identity split would silently \
29040                 break every consumer that relied on the borrow sharing \
29041                 the composite's storage",
29042            );
29043            assert_eq!(
29044                s.placement().estrategia(),
29045                s.placement.estrategia,
29046                "AplicacaoSpec::placement().estrategia() must byte-equal \
29047                 self.placement.estrategia — a strategy-drift would \
29048                 silently split the paired `validate_placement` \
29049                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
29050                 peer caixa-mesh programs.yaml `placement.estrategia` \
29051                 emitter's key from the peer `feira app graph` printer's \
29052                 strategy label",
29053            );
29054            assert_eq!(
29055                s.placement().clusters(),
29056                s.placement.clusters.as_slice(),
29057                "AplicacaoSpec::placement().clusters() must byte-equal \
29058                 self.placement.clusters — a cluster-pool drift would \
29059                 silently split the paired `validate_placement` \
29060                 pre-flight `.is_empty()` refusal probe's traversal from \
29061                 the peer caixa-mesh programs.yaml `placement.clusters` \
29062                 emitter's fan-out from the peer `feira app graph` \
29063                 printer's cluster list",
29064            );
29065        }
29066    }
29067
29068    #[test]
29069    fn validate_placement_reads_through_lifted_placement_accessor() {
29070        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
29071        // per-axis bracket-dispatch seed (`let p = self.placement();`,
29072        // followed by the per-axis fan-out `p.clusters()` /
29073        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
29074        // lifted axis-level accessor family) must key off the lifted
29075        // outer accessor, so any future rebrand on the typed slot's
29076        // outer-composite reader shape lands at exactly one place. Pins
29077        // the multi-axis coherence by exercising each per-axis refusal
29078        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
29079        // `:clusters` pool under the outer accessor's reference
29080        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
29081        // strategy with a `None` `:shard-key` under the same projection,
29082        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
29083        // with a `Some` `:shard-key` under the same projection, and
29084        // (4) the canonical `three_member_spec` `Replicated` fixture
29085        // passes `validate_placement` under the outer accessor's
29086        // reference projection — the accessor's reference-projection
29087        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
29088        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
29089        // without silently short-circuiting any.
29090        //
29091        // Peer of the sibling M3
29092        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
29093        // (534dc21) multi-axis coherence pin on the per-`:politicas`
29094        // outer mesh-policy composite-reference axis — extends the
29095        // multi-consumer coherence discipline onto the outermost M3
29096        // mesh-slot type's per-Aplicacao distribution composite-
29097        // reference axis, the second `&Composite`-return accessor on
29098        // the outer [`AplicacaoSpec`] type.
29099
29100        // (1) `PlacementWithoutClusters` refusal under the outer
29101        // accessor's reference projection: an empty `:clusters` pool
29102        // must trip the pre-flight refusal probe. The bracket-dispatch's
29103        // first arm reads `p.clusters()` on the reference returned by
29104        // the outer accessor.
29105        let mut spec = three_member_spec();
29106        spec.placement.clusters = Vec::new();
29107        assert_eq!(
29108            spec.validate().unwrap_err(),
29109            AplicacaoError::PlacementWithoutClusters {
29110                estrategia: PlacementStrategy::Replicated,
29111            },
29112        );
29113        assert!(
29114            std::ptr::eq(spec.placement(), &spec.placement),
29115            "the `validate_placement` per-axis bracket-dispatch's \
29116             traversal input must be the same backing composite the \
29117             accessor's reference projection borrows from",
29118        );
29119
29120        // (2) `ShardedWithoutKey` refusal under the outer accessor's
29121        // reference projection: a `Sharded` strategy with a `None`
29122        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
29123        // The bracket-dispatch's third arm reads `p.estrategia()` for
29124        // the match scrutinee then `p.shard_key()` for the cascade
29125        // scrutinee, both on the reference returned by the outer
29126        // accessor.
29127        let mut spec = three_member_spec();
29128        spec.placement.estrategia = PlacementStrategy::Sharded;
29129        spec.placement.shard_key = None;
29130        assert_eq!(
29131            spec.validate().unwrap_err(),
29132            AplicacaoError::ShardedWithoutKey,
29133        );
29134
29135        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
29136        // reference projection: a non-`Sharded` strategy with a `Some`
29137        // `:shard-key` must trip the declared-but-inert refusal. The
29138        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
29139        // + `p.estrategia()` for the diagnostic on the reference
29140        // returned by the outer accessor.
29141        let mut spec = three_member_spec();
29142        spec.placement.estrategia = PlacementStrategy::Replicated;
29143        spec.placement.shard_key = Some("tenantId".into());
29144        assert_eq!(
29145            spec.validate().unwrap_err(),
29146            AplicacaoError::ShardKeyOnNonSharded {
29147                estrategia: PlacementStrategy::Replicated,
29148                shard_key: "tenantId".into(),
29149            },
29150        );
29151
29152        // (4) Canonical `three_member_spec` `Replicated` fixture passes
29153        // `validate_placement` — every per-axis arm reaches the fall-
29154        // through `Ok(())` without any per-axis refusal firing under the
29155        // outer accessor's reference projection.
29156        let spec = three_member_spec();
29157        assert!(
29158            spec.validate().is_ok(),
29159            "the canonical Replicated placement fixture must pass \
29160             `validate_placement` — every per-axis arm short-circuits on \
29161             valid input under the outer accessor's reference projection",
29162        );
29163        assert_eq!(
29164            spec.placement().estrategia(),
29165            PlacementStrategy::Replicated,
29166            "the outer accessor's reference projection must be the \
29167             canonical Replicated fixture's strategy",
29168        );
29169        assert_eq!(
29170            spec.placement().clusters(),
29171            &["rio", "mar"],
29172            "the outer accessor's reference projection must be the \
29173             canonical Replicated fixture's cluster pool",
29174        );
29175    }
29176
29177    #[test]
29178    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
29179        // The canonical per-`:entrada` outer-composite-optional-
29180        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
29181        // the `:entrada` typed `Option<Entrada>` verbatim as an
29182        // `Option<&Entrada>` reference over the same backing storage
29183        // the raw `self.entrada.as_ref()` field access borrows from,
29184        // byte-equal across every representative fixture in the
29185        // accept-set — the author-omitted `None` shape (the
29186        // "internal-only mesh" partition every downstream external-
29187        // gateway emitter treats as "emit nothing"), the minimal
29188        // singleton `:entrada` composite (host + destination + empty
29189        // paths + default port), the paths-carrying composite (the
29190        // canonical `three_member_spec` fixture's ["/api" "/health"]
29191        // path-list shape every HTTPRoute per-rule fan-out emitter
29192        // reads), and the non-default port composite (the canonical
29193        // custom-port shape the port-fallback resolver reads).
29194        //
29195        // Pins against a future silent detour that returned a fresh-
29196        // cloned `Entrada` copy (which would type-check via a `Clone`
29197        // impl but silently break every downstream caller that
29198        // relied on the reference sharing the composite's backing
29199        // identity), a reference to an operator-resolved overlay
29200        // (the future per-cluster `:entrada-overrides` slot the
29201        // MESH-COMPOSITION §V federation roadmap acknowledges — its
29202        // resolution must land at exactly this accessor body, not
29203        // silently divert the raw slot away from a second consumer),
29204        // a `None` → `Some(Entrada::default)` cluster-default
29205        // projection (which would collapse the load-bearing
29206        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
29207        // the peer `gateway_routes` early-return + `feira app graph`
29208        // internal-only-mesh partition both read), or an axis-
29209        // shuffled projection (a future detour that swapped
29210        // `host` and `para` through the accessor would silently
29211        // split the paired `validate` per-`:entrada` shape-and-
29212        // membership gate's traversal input from the peer
29213        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
29214        // fan-out input from the peer `feira app graph` external-
29215        // gateway summary line).
29216        //
29217        // Peer of the sibling M3
29218        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
29219        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
29220        // `:politicas` outer mesh-policy composite-reference axis
29221        // and of the sibling M3
29222        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
29223        // (9abb8f0) `&Placement` byte-equal pin on the per-
29224        // `:placement` outer distribution-composite composite-
29225        // reference axis — extends the outer-accessor byte-equal-
29226        // projection discipline onto the last unlifted outermost M3
29227        // mesh-slot type's per-Aplicacao external-gateway composite-
29228        // reference axis, the third and final `&Composite`-return
29229        // accessor on the outer [`AplicacaoSpec`] type.
29230        let fixtures: Vec<Option<Entrada>> = vec![
29231            None,
29232            Some(Entrada {
29233                host: "checkout.quero.cloud".into(),
29234                para: "cart".into(),
29235                paths: Vec::new(),
29236                port: DEFAULT_SERVICO_PORT,
29237            }),
29238            Some(Entrada {
29239                host: "checkout.quero.cloud".into(),
29240                para: "cart".into(),
29241                paths: vec!["/api".into(), "/health".into()],
29242                port: DEFAULT_SERVICO_PORT,
29243            }),
29244            Some(Entrada {
29245                host: "checkout.quero.cloud".into(),
29246                para: "cart".into(),
29247                paths: vec!["/api".into()],
29248                port: 9443,
29249            }),
29250        ];
29251        for entrada in fixtures {
29252            let s = AplicacaoSpec {
29253                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
29254                contratos: Vec::new(),
29255                politicas: MeshPolicy::default(),
29256                placement: Placement::default(),
29257                entrada: entrada.clone(),
29258            };
29259            assert_eq!(
29260                s.entrada(),
29261                entrada.as_ref(),
29262                "AplicacaoSpec::entrada must return :entrada verbatim \
29263                 (got {:?}, expected {:?})",
29264                s.entrada(),
29265                entrada.as_ref(),
29266            );
29267            match (s.entrada(), s.entrada.as_ref()) {
29268                (Some(a), Some(b)) => assert!(
29269                    std::ptr::eq(a, b),
29270                    "AplicacaoSpec::entrada accessor and \
29271                     self.entrada.as_ref() field access must borrow \
29272                     the same backing storage — the accessor is the \
29273                     substrate-primitive typed dispatch every \
29274                     downstream external-gateway composite consumer \
29275                     must route through, and a reference-identity \
29276                     split would silently break every consumer that \
29277                     relied on the borrow sharing the composite's \
29278                     storage",
29279                ),
29280                (None, None) => {}
29281                _ => panic!(
29282                    "AplicacaoSpec::entrada presence bit must byte-\
29283                     equal self.entrada.is_some() — a presence-bit \
29284                     drift would silently split the paired `validate` \
29285                     per-`:entrada` shape-and-membership gate's \
29286                     traversal head from the peer \
29287                     caixa-mesh gateway_routes early-return partition \
29288                     from the peer `feira app graph` internal-only-\
29289                     mesh partition",
29290                ),
29291            }
29292            assert_eq!(
29293                s.entrada().is_some(),
29294                s.entrada.is_some(),
29295                "AplicacaoSpec::entrada().is_some() must byte-equal \
29296                 self.entrada.is_some() — a presence-bit drift would \
29297                 silently split every downstream `Option<&Entrada>` \
29298                 consumer's partition on the internal-only-mesh arm",
29299            );
29300        }
29301    }
29302
29303    #[test]
29304    fn validate_reads_through_lifted_entrada_accessor() {
29305        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
29306        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
29307        // self.entrada() { … }`, followed by the per-axis fan-out
29308        // `validate_entrada_para(&e.para)` /
29309        // `EntradaMemberMissing` membership lookup /
29310        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
29311        // per-`e.paths` `validate_entrada_path` traversal) must key
29312        // off the lifted outer accessor, so any future rebrand on
29313        // the typed slot's outer-composite reader shape lands at
29314        // exactly one place. Pins the multi-axis coherence by
29315        // exercising each per-axis refusal end-to-end: (1) the
29316        // author-omitted `None` shape short-circuits past every
29317        // per-`:entrada` refusal (the internal-only mesh partition
29318        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
29319        // fires on a well-shaped but phantom `:para` under the outer
29320        // accessor's reference projection, and (3) the canonical
29321        // `three_member_spec` `:entrada` fixture passes `validate`
29322        // under the outer accessor's reference projection.
29323        //
29324        // Peer of the sibling M3
29325        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
29326        // (534dc21) multi-axis coherence pin on the per-`:politicas`
29327        // outer mesh-policy composite-reference axis and the sibling
29328        // M3
29329        // [`validate_placement_reads_through_lifted_placement_accessor`]
29330        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
29331        // outer distribution-composite composite-reference axis —
29332        // extends the multi-consumer coherence discipline onto the
29333        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
29334        // external-gateway composite-reference axis, the third and
29335        // final `&Composite`-return accessor on the outer
29336        // [`AplicacaoSpec`] type.
29337
29338        // (1) `None` :entrada — the internal-only-mesh partition
29339        // short-circuits past every per-`:entrada` refusal. The outer
29340        // accessor's reference projection reaches the fall-through
29341        // `Ok(())` on the `None` arm without any per-axis refusal
29342        // firing.
29343        let mut spec = three_member_spec();
29344        spec.entrada = None;
29345        assert!(
29346            spec.validate().is_ok(),
29347            "an author-omitted `:entrada` must pass `validate` — the \
29348             internal-only-mesh partition short-circuits past every \
29349             per-`:entrada` refusal under the outer accessor's \
29350             reference projection",
29351        );
29352        assert!(
29353            spec.entrada().is_none(),
29354            "the outer accessor's reference projection must name the \
29355             internal-only-mesh partition per the `None` fixture",
29356        );
29357
29358        // (2) `EntradaMemberMissing` refusal under the outer accessor's
29359        // reference projection: a well-shaped but phantom `:para` must
29360        // trip the membership-lookup refusal. The gate's second arm
29361        // reads `e.para` on the reference returned by the outer
29362        // accessor.
29363        let mut spec = three_member_spec();
29364        if let Some(e) = spec.entrada.as_mut() {
29365            e.para = "phantom".into();
29366        }
29367        assert_eq!(
29368            spec.validate().unwrap_err(),
29369            AplicacaoError::EntradaMemberMissing {
29370                para: "phantom".into(),
29371            },
29372        );
29373        match (spec.entrada(), spec.entrada.as_ref()) {
29374            (Some(a), Some(b)) => assert!(
29375                std::ptr::eq(a, b),
29376                "the `validate` per-`:entrada` gate's traversal head \
29377                 must be the same backing composite the accessor's \
29378                 reference projection borrows from",
29379            ),
29380            _ => panic!("fixture must carry Some(:entrada)"),
29381        }
29382
29383        // (3) Canonical `three_member_spec` `:entrada` fixture passes
29384        // `validate` — every per-axis arm reaches the fall-through
29385        // `Ok(())` without any per-axis refusal firing under the
29386        // outer accessor's reference projection.
29387        let spec = three_member_spec();
29388        assert!(
29389            spec.validate().is_ok(),
29390            "the canonical `:entrada` fixture must pass `validate` — \
29391             every per-axis arm short-circuits on valid input under \
29392             the outer accessor's reference projection",
29393        );
29394        assert!(
29395            spec.entrada().is_some(),
29396            "the outer accessor's reference projection must be the \
29397             canonical `:entrada` fixture's composite",
29398        );
29399    }
29400
29401    #[test]
29402    fn membro_names_matches_inline_membros_projection() {
29403        // Substrate-primitive ≡ inline-projection pin on
29404        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
29405        // must be byte-for-byte the set the pre-lift inline
29406        // `self.membros().iter().map(Membro::nome).collect()` builder
29407        // produced, on every membership shape the three
29408        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
29409        // :para`, `:entrada :para`) resolve against. Pins the
29410        // projection so a future rebrand of the node-identity axis
29411        // lands at the primitive rather than diverging between the
29412        // per-`:contratos` membership arms still inline at `validate`
29413        // and the lifted `validate_entrada` gate.
29414        for membros in [
29415            vec![],
29416            vec![membro("cart", "^0.1")],
29417            vec![
29418                membro("catalog", "^0.1"),
29419                membro("cart", "^0.1"),
29420                membro("payment", "^0.2"),
29421            ],
29422        ] {
29423            let mut spec = three_member_spec();
29424            spec.membros = membros;
29425            let inline: std::collections::HashSet<&str> =
29426                spec.membros().iter().map(Membro::nome).collect();
29427            assert_eq!(
29428                spec.membro_names(),
29429                inline,
29430                "the lifted membership oracle must discriminate the \
29431                 same node set as the pre-lift inline projection",
29432            );
29433        }
29434    }
29435
29436    #[test]
29437    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
29438        // Per-slot-gate ≡ validate equivalence pin on the lifted
29439        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
29440        // must discriminate the same set as [`AplicacaoSpec::validate`]
29441        // on every `:entrada`-covered input, so a future consumer that
29442        // re-validates the one slot (the M4 admission webhook
29443        // re-checking `:entrada` after a gateway-host patch) accepts
29444        // exactly what `feira build` accepts and surfaces the same
29445        // diagnostic on the same input. Covers each of the five gated
29446        // axes plus the two clean-pass shapes (`None` — the
29447        // internal-only-mesh partition — and the canonical fixture).
29448        //
29449        // Peer of the sibling per-slot equivalence pins
29450        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29451        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
29452        // `:politicas` slot's compound entry gate, extended here onto
29453        // the `:entrada` slot's newly-named per-slot gate.
29454        /// One `:entrada` equivalence case: a label, the per-axis
29455        /// mutation applied to the canonical fixture's composite, and
29456        /// the diagnostic both the per-slot gate and `validate` must
29457        /// surface on it (`None` = clean pass).
29458        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
29459
29460        let cases: &[EntradaCase] = &[
29461            (
29462                ":para shape — empty",
29463                |e| e.para = String::new(),
29464                Some(AplicacaoError::EntradaParaEmpty),
29465            ),
29466            (
29467                ":para membership — well-shaped phantom",
29468                |e| e.para = "phantom".into(),
29469                Some(AplicacaoError::EntradaMemberMissing {
29470                    para: "phantom".into(),
29471                }),
29472            ),
29473            (
29474                ":host emptiness",
29475                |e| e.host = String::new(),
29476                Some(AplicacaoError::EmptyEntradaHost),
29477            ),
29478            (
29479                ":port structural floor",
29480                |e| e.port = 0,
29481                Some(AplicacaoError::EntradaPortZero),
29482            ),
29483            (
29484                ":paths per-entry emptiness",
29485                |e| e.paths = vec![String::new()],
29486                Some(AplicacaoError::EntradaPathEmpty),
29487            ),
29488            (
29489                ":paths leading-slash grammar",
29490                |e| e.paths = vec!["api/cart".into()],
29491                Some(AplicacaoError::EntradaPathNotAbsolute {
29492                    path: "api/cart".into(),
29493                }),
29494            ),
29495            (
29496                ":paths set-not-multiset",
29497                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
29498                Some(AplicacaoError::EntradaPathDuplicate {
29499                    path: "/api/cart".into(),
29500                }),
29501            ),
29502            ("clean pass — canonical fixture", |_| {}, None),
29503        ];
29504        for (label, mutate, expected) in cases {
29505            let mut spec = three_member_spec();
29506            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
29507            assert_eq!(
29508                spec.validate_entrada().err(),
29509                *expected,
29510                "per-slot gate disagreed with the expected diagnostic on {label}",
29511            );
29512            assert_eq!(
29513                spec.validate().err(),
29514                *expected,
29515                "`validate` disagreed with the per-slot gate on {label}",
29516            );
29517        }
29518
29519        // The `None` arm is the internal-only-mesh partition: a clean
29520        // pass through both the per-slot gate and `validate`, not a
29521        // refusal.
29522        let mut spec = three_member_spec();
29523        spec.entrada = None;
29524        assert_eq!(spec.validate_entrada().err(), None);
29525        assert_eq!(spec.validate().err(), None);
29526    }
29527
29528    #[test]
29529    fn validate_entrada_resolves_membership_through_own_oracle() {
29530        // Self-containment pin on the lifted per-slot gate:
29531        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
29532        // against the oracle *it* builds through
29533        // [`AplicacaoSpec::membro_names`], not one threaded down from
29534        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
29535        // longer contains the `:entrada :para` target must trip
29536        // `EntradaMemberMissing` when the per-slot gate is called
29537        // directly — the shape a future single-slot re-validator
29538        // (the M4 admission webhook) reaches the axis through, without
29539        // re-walking `:membros` / `:contratos` / the sync-cycle
29540        // detector first. Same self-contained posture
29541        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
29542        // the M4 per-edge policy resolver.
29543        let mut spec = three_member_spec();
29544        spec.membros.retain(|m| m.nome() != "cart");
29545        assert_eq!(
29546            spec.validate_entrada().unwrap_err(),
29547            AplicacaoError::EntradaMemberMissing {
29548                para: "cart".into(),
29549            },
29550            "the per-slot gate must resolve `:para` against the oracle \
29551             it builds itself, with no membership set threaded in",
29552        );
29553        assert!(
29554            !spec.membro_names().contains("cart"),
29555            "fixture must have dropped the `:entrada :para` target \
29556             from the graph's node set",
29557        );
29558    }
29559
29560    #[test]
29561    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
29562        // Per-slot-gate ≡ validate equivalence pin on the lifted
29563        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
29564        // gate must discriminate the same set as
29565        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
29566        // input, so a future consumer that re-validates the one slot
29567        // (the M4 admission webhook re-checking `:contratos` after a
29568        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
29569        // `:politicas` override MESH-COMPOSITION §III.2 #3
29570        // acknowledges — which resolves an effective per-edge
29571        // [`MeshPolicy`] and must re-check the edge's identity closure
29572        // before it can key a per-edge override off the endpoint
29573        // tuple) accepts exactly what `feira build` accepts and
29574        // surfaces the same diagnostic on the same input. Covers each
29575        // of the six gated axes (`:de`/`:para` per-arm shape,
29576        // per-arm graph-membership, structural self-loop, `:wit`
29577        // emptiness) plus the clean-pass canonical fixture; the
29578        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
29579        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
29580        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
29581        // `target:` carriers depend on library implementation
29582        // details are pinned separately below with a `matches!`
29583        // predicate on the arm identity plus the mirror equivalence
29584        // between the two entry points.
29585        //
29586        // Peer of the sibling per-slot equivalence pins
29587        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29588        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
29589        // `:politicas` slot's compound entry gate, and
29590        // `validate_entrada_matches_gate_on_every_per_axis_shape`
29591        // (20cd523) on the `:entrada` slot's per-slot gate — extended
29592        // here onto the `:contratos` slot's newly-named per-slot gate,
29593        // closing the last unlifted per-slot gate on the M3 mesh-slot
29594        // family.
29595        /// One `:contratos` equivalence case: a label, the per-axis
29596        /// mutation applied to the canonical fixture's spec, and the
29597        /// diagnostic both the per-slot gate and `validate` must
29598        /// surface on it (`None` = clean pass).
29599        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
29600
29601        let cases: &[ContratoCase] = &[
29602            (
29603                ":de shape — empty",
29604                |s| s.contratos[0].de = String::new(),
29605                Some(AplicacaoError::ContratoCaixaEmpty {
29606                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
29607                }),
29608            ),
29609            (
29610                ":para shape — empty",
29611                |s| s.contratos[0].para = String::new(),
29612                Some(AplicacaoError::ContratoCaixaEmpty {
29613                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
29614                }),
29615            ),
29616            (
29617                ":de membership — well-shaped phantom",
29618                |s| s.contratos[0].de = "phantom".into(),
29619                Some(AplicacaoError::ContratoMemberMissing {
29620                    caixa: "phantom".into(),
29621                }),
29622            ),
29623            (
29624                ":para membership — well-shaped phantom",
29625                |s| s.contratos[0].para = "phantom".into(),
29626                Some(AplicacaoError::ContratoMemberMissing {
29627                    caixa: "phantom".into(),
29628                }),
29629            ),
29630            (
29631                "structural self-loop",
29632                |s| s.contratos[0].para = "cart".into(),
29633                Some(AplicacaoError::ContratoSelfLoop {
29634                    caixa: "cart".into(),
29635                    wit: "wasi:http/proxy".into(),
29636                }),
29637            ),
29638            (
29639                ":wit emptiness",
29640                |s| s.contratos[0].wit = String::new(),
29641                Some(AplicacaoError::EmptyWit {
29642                    de: "cart".into(),
29643                    para: "catalog".into(),
29644                }),
29645            ),
29646            ("clean pass — canonical fixture", |_| {}, None),
29647        ];
29648        for (label, mutate, expected) in cases {
29649            let mut spec = three_member_spec();
29650            mutate(&mut spec);
29651            assert_eq!(
29652                spec.validate_contratos().err(),
29653                *expected,
29654                "per-slot gate disagreed with the expected diagnostic on {label}",
29655            );
29656            assert_eq!(
29657                spec.validate().err(),
29658                *expected,
29659                "`validate` disagreed with the per-slot gate on {label}",
29660            );
29661        }
29662    }
29663
29664    #[test]
29665    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
29666        // Companion pin to
29667        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
29668        // the per-slot gate ≡ `validate` equivalence on the three
29669        // `:contratos` refusal arms whose diagnostic carries a
29670        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
29671        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
29672        // `is_dns_1123_label` / `WitContract::target` shape helpers,
29673        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
29674        // library-formatted `target:` scalar). Value equality between
29675        // the per-slot gate and `validate` outputs pins the full
29676        // `Option<AplicacaoError>` (including reason-strings), and the
29677        // per-arm `matches!` predicate pins the arm-discriminator
29678        // identity on the specific `Contrato*` variant. Split from
29679        // the primary equivalence pin so each pin body stays under
29680        // [`clippy::too_many_lines`], the same shape the peer
29681        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
29682        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
29683        // carries on the `:politicas` slot's compound entry gate.
29684        type ContratoReasonCase = (
29685            &'static str,
29686            fn(&mut AplicacaoSpec),
29687            fn(&AplicacaoError) -> bool,
29688        );
29689        let cases: &[ContratoReasonCase] = &[
29690            (
29691                ":de shape — DNS-1123 invalid",
29692                |s| s.contratos[0].de = "Cart".into(),
29693                |err| {
29694                    matches!(
29695                        err,
29696                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
29697                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
29698                    )
29699                },
29700            ),
29701            (
29702                ":wit target-shape mismatch — payload on capability arm",
29703                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
29704                |err| {
29705                    matches!(
29706                        err,
29707                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
29708                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
29709                    )
29710                },
29711            ),
29712            (
29713                "whole-edge dedup — six-axis identity collision",
29714                |s| {
29715                    let dup = s.contratos[0].clone();
29716                    s.contratos.push(dup);
29717                },
29718                |err| {
29719                    matches!(
29720                        err,
29721                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
29722                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
29723                    )
29724                },
29725            ),
29726        ];
29727        for (label, mutate, arm_matches) in cases {
29728            let mut spec = three_member_spec();
29729            mutate(&mut spec);
29730            let per_slot = spec.validate_contratos().err();
29731            let gate = spec.validate().err();
29732            assert_eq!(
29733                per_slot, gate,
29734                "per-slot gate and `validate` must return byte-equal \
29735                 `Option<AplicacaoError>` on {label} (including \
29736                 library-owned reason strings)",
29737            );
29738            let err = per_slot
29739                .as_ref()
29740                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
29741            assert!(
29742                arm_matches(err),
29743                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
29744            );
29745        }
29746    }
29747
29748    #[test]
29749    fn validate_contratos_resolves_membership_through_own_oracle() {
29750        // Self-containment pin on the lifted per-slot gate:
29751        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
29752        // `:de` / `:para` against the oracle *it* builds through
29753        // [`AplicacaoSpec::membro_names`], not one threaded down from
29754        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
29755        // longer contains a `:contratos` edge's endpoint must trip
29756        // `ContratoMemberMissing` when the per-slot gate is called
29757        // directly — the shape a future single-slot re-validator
29758        // (the M4 admission webhook re-checking `:contratos` after a
29759        // per-`(:de, :para)` edge patch, the M4 per-edge policy
29760        // resolver on the `:politicas` override axis) reaches the
29761        // axis through, without re-walking `:membros` / `:entrada` /
29762        // `:placement` / `:politicas` first. Same self-contained
29763        // posture the peer per-slot gates
29764        // [`AplicacaoSpec::detect_sync_cycles`] and
29765        // [`AplicacaoSpec::validate_entrada`] already carry for the
29766        // same M4 consumers.
29767        let mut spec = three_member_spec();
29768        spec.membros.retain(|m| m.nome() != "catalog");
29769        assert_eq!(
29770            spec.validate_contratos().unwrap_err(),
29771            AplicacaoError::ContratoMemberMissing {
29772                caixa: "catalog".into(),
29773            },
29774            "the per-slot gate must resolve `:de` / `:para` against \
29775             the oracle it builds itself, with no membership set \
29776             threaded in",
29777        );
29778        assert!(
29779            !spec.membro_names().contains("catalog"),
29780            "fixture must have dropped the `:contratos` edge's \
29781             `:para` target from the graph's node set",
29782        );
29783    }
29784
29785    #[test]
29786    fn validate_contratos_folds_cycle_axis_matches_gate() {
29787        // Fold-into-per-slot-gate equivalence pin on the
29788        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
29789        // surfaces byte-equal through both
29790        // [`AplicacaoSpec::validate_contratos`] and
29791        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
29792        // a synchronous-edge cycle in `:contratos`. Pins the fold that
29793        // moved the cross-edge cycle axis onto the per-slot gate — a
29794        // future silent regression that de-folded the axis back to the
29795        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
29796        // a peer per-slot gate lift that skipped the cross-axis half of
29797        // the [`MeshPolicy::validate`]-analogous discipline) would
29798        // surface here as `Some(ContratoCycle)` from `validate` and
29799        // `None` from `validate_contratos`.
29800        //
29801        // Cycle fixture is the same shape as the peer
29802        // [`rejects_three_node_synchronous_cycle`] test carries: a
29803        // clean 3-cycle over the HTTP subgraph (catalog → cart →
29804        // payment → catalog), so the per-entry cascade (shape +
29805        // membership + self-loop + `:wit` emptiness + WIT-target +
29806        // whole-edge dedup) passes cleanly and the sole surviving
29807        // refusal shape is the cross-edge cycle axis. The `cycle`
29808        // vector is normalized to a sorted body set for the equality
29809        // compare (the traversal path's starting node depends on
29810        // BTreeMap iteration order, which is deterministic but is not
29811        // the load-bearing property this pin covers).
29812        //
29813        // Peer of the sibling per-slot ≡ `validate` equivalence pins
29814        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
29815        // (per-entry axes) and
29816        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
29817        // (parser-owned reason arms) already carry on the six
29818        // per-entry axes — this extends the discipline onto the
29819        // cross-edge cycle axis newly folded into the per-slot gate,
29820        // matching the peer per-slot compound gate
29821        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
29822        // both per-axis and cross-axis surfaces on `:politicas`.
29823        let mut spec = three_member_spec();
29824        spec.contratos = vec![
29825            contract_http("catalog", "cart", "/x"),
29826            contract_http("cart", "payment", "/y"),
29827            contract_http("payment", "catalog", "/z"),
29828        ];
29829        let per_slot_err = spec.validate_contratos().unwrap_err();
29830        let gate_err = spec.validate().unwrap_err();
29831        assert_eq!(
29832            per_slot_err, gate_err,
29833            "the per-slot gate and `validate` must return byte-equal \
29834             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
29835             — the fold pins the cross-edge axis onto the per-slot \
29836             gate the same way the peer `validate_politicas` fold \
29837             pinned the `:politicas` cross-axis surface",
29838        );
29839        match per_slot_err {
29840            AplicacaoError::ContratoCycle { ref cycle } => {
29841                assert_eq!(
29842                    cycle.first(),
29843                    cycle.last(),
29844                    "cycle traversal must close on the back-edge \
29845                     target — the diagnostic shape the peer \
29846                     `rejects_three_node_synchronous_cycle` pins",
29847                );
29848                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
29849                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
29850                assert!(body.contains("cart"));
29851                assert!(body.contains("catalog"));
29852                assert!(body.contains("payment"));
29853            }
29854            other => panic!("expected ContratoCycle, got {other:?}"),
29855        }
29856    }
29857
29858    #[test]
29859    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
29860        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
29861        // carrying *both* a per-entry defect (a self-loop, the
29862        // structural-self-edge arm on the per-entry cascade — chosen
29863        // because it never masks or is masked by the cycle diagnostic
29864        // on the peer arms) *and* a would-be synchronous-edge cycle in
29865        // the remaining edges must surface the per-entry diagnostic
29866        // first through both [`AplicacaoSpec::validate_contratos`] and
29867        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
29868        // per-entry-before-cross-edge dispatch ordering, byte-equal to
29869        // the pre-fold `validate`-side sequence
29870        // (`validate_contratos()? → detect_sync_cycles()?`) the
29871        // dispatch encoded verbatim. A silent regression that reversed
29872        // the ordering inside the fold would surface here as a cycle
29873        // diagnostic on a fixture carrying an earlier per-entry defect
29874        // — masking the narrower "this edge is degenerate" arm behind
29875        // the coarser "this graph deadlocks" arm.
29876        //
29877        // Peer of the diagnostic-ordering property the pre-fold
29878        // dispatch encoded at the [`AplicacaoSpec::validate`]
29879        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
29880        // now enforced inside the per-slot gate's own body, so a future
29881        // consumer that reaches only the per-slot gate (the M4
29882        // admission webhook re-checking `:contratos` after a per-edge
29883        // patch) inherits the ordering property by construction.
29884        let mut spec = three_member_spec();
29885        // The three-member fixture already has cart → catalog and
29886        // cart → payment; adding catalog → cart closes a 2-cycle on
29887        // the HTTP subgraph.
29888        spec.contratos
29889            .push(contract_http("catalog", "cart", "/refresh"));
29890        // Add a self-loop on `payment` — the per-entry structural-
29891        // self-edge arm — which must surface first.
29892        spec.contratos
29893            .push(contract_http("payment", "payment", "/loop"));
29894        let per_slot_err = spec.validate_contratos().unwrap_err();
29895        let gate_err = spec.validate().unwrap_err();
29896        assert_eq!(
29897            per_slot_err, gate_err,
29898            "per-slot gate and `validate` must agree on the ordering \
29899             fixture's surfaced diagnostic — a divergence here means \
29900             the fold reshaped one dispatch's ordering without the \
29901             other",
29902        );
29903        assert!(
29904            matches!(
29905                per_slot_err,
29906                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
29907                    if caixa == "payment"
29908            ),
29909            "the per-entry structural-self-edge arm must fire before \
29910             the cross-edge cycle arm — pinning the fold's per-entry-\
29911             before-cross-edge dispatch ordering byte-equal to the \
29912             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
29913             sequence; got {per_slot_err:?}",
29914        );
29915    }
29916
29917    #[test]
29918    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
29919        // Self-containment pin on the folded cross-edge cycle axis:
29920        // [`AplicacaoSpec::validate_contratos`] surfaces
29921        // [`AplicacaoError::ContratoCycle`] directly against `&self`
29922        // without depending on the peer per-slot gates
29923        // ([`AplicacaoSpec::validate_membros`],
29924        // [`AplicacaoSpec::validate_entrada`],
29925        // [`AplicacaoSpec::validate_placement`],
29926        // [`AplicacaoSpec::validate_politicas`]) running first — the
29927        // shape a future single-slot re-validator (the M4 admission
29928        // webhook re-checking `:contratos` after a per-`(:de, :para)`
29929        // edge patch, the per-edge policy resolver MESH-COMPOSITION
29930        // §III.2 #3 acknowledges) reaches *both* structural axes on
29931        // the slot through one call. A spec with a per-`:politicas`
29932        // refusal shape (zero `:timeout`, the first per-axis arm the
29933        // peer [`MeshPolicy::validate`] gate covers) AND a
29934        // synchronous-edge cycle in `:contratos` must:
29935        //
29936        //   - surface [`AplicacaoError::ContratoCycle`] through the
29937        //     per-slot gate `validate_contratos` directly (proves the
29938        //     cycle axis reaches the per-slot altitude without the
29939        //     peer `:politicas` gate running first);
29940        //   - surface [`AplicacaoError::ContratoCycle`] through
29941        //     `validate` (which reaches `validate_contratos` before
29942        //     `validate_politicas` per the fixed dispatch order), so
29943        //     the fold's cross-slot ordering (`:membros` →
29944        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
29945        //     is byte-equal to the pre-fold dispatch's ordering.
29946        //
29947        // Same self-contained-on-`&self` posture the peer per-slot
29948        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
29949        // [`AplicacaoSpec::validate_contratos`] per-entry axis
29950        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
29951        // (f03a154) already carry — extended here onto the newly-
29952        // folded cross-edge cycle axis. Peer of the sibling per-slot
29953        // self-containment pins
29954        // `validate_entrada_resolves_membership_through_own_oracle`
29955        // and `validate_contratos_resolves_membership_through_own_oracle`
29956        // on the per-entry membership axis — extends the discipline
29957        // onto the cross-edge cycle axis of the same per-slot gate.
29958        let mut spec = three_member_spec();
29959        // Poison `:politicas` — zero-`:timeout` trips the first per-
29960        // axis arm the [`MeshPolicy::validate`] gate covers, so any
29961        // dispatch that reached `:politicas` would surface a
29962        // `:politicas` diagnostic instead of `ContratoCycle`.
29963        spec.politicas.timeout = Some(Duration::from_secs(0));
29964        // Close a synchronous-edge cycle on the HTTP subgraph.
29965        spec.contratos
29966            .push(contract_http("catalog", "cart", "/refresh"));
29967        let per_slot_err = spec.validate_contratos().unwrap_err();
29968        assert!(
29969            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
29970            "the per-slot gate must surface `ContratoCycle` directly \
29971             against `&self` — a peer per-slot gate's regression \
29972             would surface a non-`ContratoCycle` diagnostic here; \
29973             got {per_slot_err:?}",
29974        );
29975        let gate_err = spec.validate().unwrap_err();
29976        assert!(
29977            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
29978            "`validate`'s five-slot dispatch must reach the fold's \
29979             cross-edge cycle axis on `:contratos` before the peer \
29980             `:politicas` gate — a dispatch-order regression would \
29981             surface a `:politicas` diagnostic here; got {gate_err:?}",
29982        );
29983        // Sanity: the poisoned `:politicas` alone would trip
29984        // [`MeshPolicy::validate`] under the peer per-slot gate, so
29985        // the cycle-first surfacing above is a real ordering property,
29986        // not a case where the `:politicas` axis silently accepts the
29987        // fixture.
29988        let mut politicas_only = three_member_spec();
29989        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
29990        assert!(
29991            politicas_only.validate_politicas().is_err(),
29992            "the poisoned `:politicas` fixture must trip the peer \
29993             per-slot gate on its own — otherwise the self-contained \
29994             cycle-first surfacing above would not be an ordering \
29995             property",
29996        );
29997    }
29998
29999    #[test]
30000    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
30001        // Fail-before-pass-after equivalence pin on the lifted
30002        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
30003        // both arms (`:de` phantom and `:para` phantom) must fire the
30004        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
30005        // `caixa` carrier byte-equal to the offending accessor's
30006        // projection, and `:de` must fire before `:para` when both
30007        // arms would trip on the same call — preserving the canonical
30008        // edge-direction order the peer per-arm shape gate
30009        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
30010        // diagnostic, and every peer per-arm ordering in
30011        // [`AplicacaoSpec::validate_contratos`] already carry.
30012        //
30013        // Two-endpoint oracle covers exactly enough graph nodes to
30014        // exercise each arm in isolation: the `:de` arm fires when
30015        // the source is off-oracle and the destination is on-oracle,
30016        // the `:para` arm fires when the source is on-oracle and the
30017        // destination is off-oracle, and the `:de`-before-`:para`
30018        // ordering falls out from a probe where *both* endpoints are
30019        // off-oracle — the diagnostic's `caixa` field must byte-equal
30020        // the source, not the destination, pinning the primitive's
30021        // arm ordering as `:de` first.
30022        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
30023        names.insert("cart");
30024        names.insert("catalog");
30025
30026        // `:de` phantom, `:para` on-oracle
30027        let de_phantom = contract_http("phantom-de", "catalog", "/x");
30028        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
30029        assert_eq!(
30030            err,
30031            AplicacaoError::ContratoMemberMissing {
30032                caixa: de_phantom.source().to_string(),
30033            },
30034            "the `:de` phantom arm must fire ContratoMemberMissing \
30035             with `caixa` byte-equal to `WitContract::source` — a \
30036             bypass here (a raw `.de.clone()` regression, a divergent \
30037             accessor on a per-CR alias table) would silently split \
30038             the primitive's diagnostic from the substrate-primitive \
30039             scalar accessor every downstream consumer routes through",
30040        );
30041
30042        // `:de` on-oracle, `:para` phantom
30043        let para_phantom = contract_http("cart", "phantom-para", "/x");
30044        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
30045        assert_eq!(
30046            err,
30047            AplicacaoError::ContratoMemberMissing {
30048                caixa: para_phantom.destination().to_string(),
30049            },
30050            "the `:para` phantom arm must fire ContratoMemberMissing \
30051             with `caixa` byte-equal to `WitContract::destination` — \
30052             symmetric callee-side pin to the `:de` arm above",
30053        );
30054
30055        // Both endpoints off-oracle: the `:de` arm must fire first,
30056        // pinning the primitive's canonical edge-direction order.
30057        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
30058        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
30059        assert_eq!(
30060            err,
30061            AplicacaoError::ContratoMemberMissing {
30062                caixa: both_phantom.source().to_string(),
30063            },
30064            "when both endpoints are off-oracle, the `:de` arm must \
30065             fire before the `:para` arm — preserving byte-equal \
30066             ordering with the pre-lift inline cascade in \
30067             `validate_contratos` and with every peer per-arm \
30068             ordering the sibling per-edge substrate primitives \
30069             already carry",
30070        );
30071
30072        // Both endpoints on-oracle: clean pass.
30073        let clean = contract_http("cart", "catalog", "/x");
30074        clean.require_endpoints_in(&names).unwrap();
30075    }
30076
30077    #[test]
30078    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
30079        // Convergence pin: the whole-spec end-to-end route through
30080        // [`AplicacaoSpec::validate_contratos`] must reach the
30081        // per-edge substrate primitive
30082        // [`WitContract::require_endpoints_in`] on every membership
30083        // arm — the diagnostic fired at the per-slot altitude must
30084        // byte-equal the diagnostic the primitive fires when called
30085        // directly on the same edge and the same oracle. Pins the
30086        // primitive as the sole load-bearing gate on the membership
30087        // axis, so any future silent detour that re-inlined the twin
30088        // `if !names.contains(...)` cascade back into the per-slot
30089        // gate (a rebase-artifact regression, an M4 admission-webhook
30090        // consumer that bypassed the primitive) would surface here as
30091        // a byte-equal miss between the two dispatches.
30092        //
30093        // Same equivalence-pin discipline the peer
30094        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
30095        // pin already carries on the per-slot gate ≡ `validate` axis,
30096        // extended here onto the per-slot gate ≡ per-edge primitive
30097        // axis at one altitude deeper.
30098        for phantom_edge in [
30099            contract_http("phantom-de", "catalog", "/x"),
30100            contract_http("cart", "phantom-para", "/x"),
30101        ] {
30102            let mut spec = three_member_spec();
30103            spec.contratos.push(phantom_edge.clone());
30104            let per_slot_err = spec.validate_contratos().unwrap_err();
30105            let primitive_err = phantom_edge
30106                .require_endpoints_in(&spec.membro_names())
30107                .unwrap_err();
30108            assert_eq!(
30109                per_slot_err, primitive_err,
30110                "the per-slot gate must reach the per-edge substrate \
30111                 primitive on every membership arm — a bypass here \
30112                 would silently split the two dispatches on the \
30113                 same edge + same oracle input",
30114            );
30115            // And the diagnostic's `caixa` carrier must byte-equal
30116            // the offending accessor's projection at both altitudes,
30117            // pinning the accessor routing across the whole-spec
30118            // path.
30119            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
30120                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
30121            };
30122            let expected = if spec.membro_names().contains(phantom_edge.source()) {
30123                phantom_edge.destination()
30124            } else {
30125                phantom_edge.source()
30126            };
30127            assert_eq!(
30128                caixa, expected,
30129                "the whole-spec ContratoMemberMissing.caixa carrier \
30130                 must byte-equal the offending edge's accessor \
30131                 projection — a bypass here would silently split \
30132                 the wrap envelope's `caixa` field from the \
30133                 substrate-primitive scalar accessor every \
30134                 downstream consumer routes through",
30135            );
30136        }
30137    }
30138
30139    #[test]
30140    fn port_for_destination_reads_through_lifted_entrada_accessor() {
30141        // Peer coherence pin: the
30142        // [`AplicacaoSpec::port_for_destination`] per-destination
30143        // L4-port fallback resolver's composite-projection seed
30144        // (`self.entrada().filter(…).map_or(…)`) must key off the
30145        // lifted outer accessor. Pins the coherence by exercising
30146        // the resolver end-to-end: (1) the `None` `:entrada` shape
30147        // falls through to `DEFAULT_SERVICO_PORT` under the outer
30148        // accessor's reference projection, (2) a non-matching
30149        // destination falls through to `DEFAULT_SERVICO_PORT` under
30150        // the outer accessor's reference projection, and (3) the
30151        // matching destination resolves to the `:entrada :port`
30152        // value under the outer accessor's reference projection.
30153        //
30154        // Peer of the sibling
30155        // [`validate_reads_through_lifted_entrada_accessor`] multi-
30156        // consumer coherence pin on the same per-`:entrada` outer-
30157        // composite axis — extends the multi-consumer coherence
30158        // discipline onto the second per-`:entrada` production
30159        // consumer, the L4-port fallback resolver.
30160
30161        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
30162        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
30163        // arm under the outer accessor's reference projection.
30164        let mut spec = three_member_spec();
30165        spec.entrada = None;
30166        assert_eq!(
30167            spec.port_for_destination("cart"),
30168            DEFAULT_SERVICO_PORT,
30169            "the port-fallback resolver must fall through to \
30170             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
30171             under the outer accessor's reference projection",
30172        );
30173
30174        // (2) Non-matching destination — the resolver's `filter(…)`
30175        // arm rejects a mismatched destination and falls through
30176        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
30177        // reference projection.
30178        let mut spec = three_member_spec();
30179        if let Some(e) = spec.entrada.as_mut() {
30180            e.para = "cart".into();
30181            e.port = 9443;
30182        }
30183        assert_eq!(
30184            spec.port_for_destination("catalog"),
30185            DEFAULT_SERVICO_PORT,
30186            "the port-fallback resolver must fall through to \
30187             DEFAULT_SERVICO_PORT on a non-matching destination \
30188             under the outer accessor's reference projection",
30189        );
30190
30191        // (3) Matching destination — the resolver's `map_or(…)` arm
30192        // returns the `:entrada :port` value under the outer
30193        // accessor's reference projection.
30194        let mut spec = three_member_spec();
30195        if let Some(e) = spec.entrada.as_mut() {
30196            e.para = "cart".into();
30197            e.port = 9443;
30198        }
30199        assert_eq!(
30200            spec.port_for_destination("cart"),
30201            9443,
30202            "the port-fallback resolver must return the \
30203             `:entrada :port` value on a matching destination \
30204             under the outer accessor's reference projection",
30205        );
30206    }
30207
30208    #[test]
30209    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
30210        // The canonical per-`:politicas` `:mtls-required` mTLS-
30211        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
30212        // must return the `:politicas :mtls-required` typed bool
30213        // verbatim as an `Option<bool>`, byte-equal to the raw field
30214        // access across every value in the three-way accept-set —
30215        // `None` (cluster default applies), `Some(true)` (mTLS
30216        // handshake enforced — the sandboxing-by-default arm the
30217        // MeshPolicy's docstring names), `Some(false)` (handshake
30218        // skipped — the explicit debug-edge opt-out).
30219        //
30220        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
30221        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
30222        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
30223        // shape — first `Option<Copy-T>`-return accessor on the M3
30224        // mesh-slot family. Pins against a future silent detour that
30225        // re-derived the toggle from a peer axis (an accidental
30226        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
30227        // whenever a breaker is set), a `None` → `Some(false)` cluster-
30228        // default projection (the canonical `Option<bool>` → `bool`
30229        // collapse footgun the surrounding `is_empty()` predicate
30230        // guards on the peer emptiness axis), or a `Some(true)` /
30231        // `Some(false)` variant swap that landed on one consumer
30232        // without the other.
30233        for required in [None, Some(true), Some(false)] {
30234            let p = MeshPolicy {
30235                mtls_required: required,
30236                ..MeshPolicy::default()
30237            };
30238            assert_eq!(
30239                p.mtls_required(),
30240                required,
30241                "MeshPolicy::mtls_required must return :politicas \
30242                 :mtls-required verbatim (got {:?}, expected {required:?})",
30243                p.mtls_required(),
30244            );
30245            assert_eq!(
30246                p.mtls_required(),
30247                p.mtls_required,
30248                "MeshPolicy::mtls_required must byte-equal the raw \
30249                 .mtls_required field access across every value in the \
30250                 three-way accept-set",
30251            );
30252        }
30253    }
30254
30255    #[test]
30256    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
30257        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
30258        // arm must key off [`MeshPolicy::mtls_required`], not the raw
30259        // `.mtls_required` field access. Structurally: toggling ONLY
30260        // the `mtls_required` slot on an otherwise-default MeshPolicy
30261        // must flip `is_empty()` from `true` (all-`None`) to `false`
30262        // (one axis carries a value); the flip must be observed for
30263        // both `Some(true)` and `Some(false)` since the emptiness
30264        // semantic reads "any axis carries a value" — not "any axis
30265        // carries a truthy value" — the same non-collapsing shape the
30266        // sibling M2 [`crate::LimitsSpec::is_empty`] /
30267        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
30268        // peer `Option<T>`-typed slot surfaces.
30269        //
30270        // Pins against a future silent detour that re-derived the
30271        // emptiness predicate off a peer axis (an accidental
30272        // `.rate_limit.is_none()`-only chain that dropped the
30273        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
30274        // collapse to a truthy-only check (which would silently
30275        // classify `Some(false)` as empty), or an accessor-side
30276        // detour that no longer names the substrate-primitive typed
30277        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
30278        // == false` fallback in the accessor that would silently
30279        // classify both `None` and `Some(false)` as the same value).
30280        //
30281        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
30282        // (7cd2a28) accessor-composition pin on the sibling optional-
30283        // scalar axis — same "the emptiness / shape-gate predicate
30284        // must route through the substrate-primitive typed dispatch"
30285        // discipline extended onto the peer per-`:politicas` emptiness
30286        // predicate.
30287        let empty = MeshPolicy::default();
30288        assert!(
30289            empty.is_empty(),
30290            "MeshPolicy::default() must be is_empty() — every axis \
30291             defaults to None",
30292        );
30293        for required in [Some(true), Some(false)] {
30294            let p = MeshPolicy {
30295                mtls_required: required,
30296                ..MeshPolicy::default()
30297            };
30298            assert!(
30299                !p.is_empty(),
30300                "MeshPolicy::is_empty must return false when \
30301                 :mtls-required is {required:?} — the emptiness \
30302                 predicate reads \"any axis carries a value\", not \
30303                 \"any axis carries a truthy value\"",
30304            );
30305            assert_eq!(
30306                p.mtls_required().is_none(),
30307                p.is_empty(),
30308                "when :mtls-required is the only set axis, \
30309                 is_empty() must equal mtls_required().is_none() — \
30310                 the accessor and the emptiness predicate must \
30311                 route through the same substrate-primitive typed \
30312                 dispatch on the :mtls-required arm",
30313            );
30314        }
30315    }
30316
30317    #[test]
30318    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
30319        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
30320        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
30321        // accessor must return by value, not by reference. Peer of the
30322        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
30323        // borrow-invariant pin on the sibling `Option<String>` slot,
30324        // but extended onto the peer `Option<bool>` copy-invariant
30325        // shape — the accessor's returned `Option<bool>` must outlive
30326        // `&self` (multiple calls must return equal values from a
30327        // dropped-`&self` copy, since the returned Option carries no
30328        // borrow), and calling the accessor twice on the same
30329        // MeshPolicy must yield the same `Option<bool>` verbatim
30330        // (idempotent, no side effects on `&self`).
30331        //
30332        // Pins against a future silent detour that returned
30333        // `Option<&bool>` (which would type-check but silently break
30334        // every downstream caller — [`single_field_overlay`]'s first
30335        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
30336        // detached copy at the call site), an accidental
30337        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
30338        // would also type-check but return `Option<&bool>`), or a
30339        // one-arm-only accessor that reads `Some(*b)` in the Some arm
30340        // but reads a fresh Default::default() in the None arm.
30341        for required in [None, Some(true), Some(false)] {
30342            let p = MeshPolicy {
30343                mtls_required: required,
30344                ..MeshPolicy::default()
30345            };
30346            let first = p.mtls_required();
30347            let second = p.mtls_required();
30348            assert_eq!(
30349                first, second,
30350                "MeshPolicy::mtls_required must be idempotent — two \
30351                 successive calls on the same &self must return the \
30352                 same Option<bool>",
30353            );
30354            assert_eq!(
30355                first, required,
30356                "MeshPolicy::mtls_required must return :politicas \
30357                 :mtls-required verbatim by copy — got {first:?}, \
30358                 expected {required:?}",
30359            );
30360        }
30361    }
30362
30363    #[test]
30364    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
30365        // The canonical per-`:politicas` `:retries` transient-failure-
30366        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
30367        // the `:politicas :retries` typed `u32` verbatim as an
30368        // `Option<u32>`, byte-equal to the raw field access across every
30369        // representative value in the accept-set — `None` (cluster
30370        // default applies — typically "no retries beyond a single
30371        // dispatch attempt" the caixa-mesh `retry_overlay` builder
30372        // documents), `Some(1)` (the lower boundary of the
30373        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
30374        // `AplicacaoSpec::validate_politicas` gate carves out on the
30375        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
30376        // (the upper boundary the same gate carves out on the sibling
30377        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
30378        // past-the-guard sentinel that pins the accessor doesn't perform
30379        // a silent bounds-collapse at the return path).
30380        //
30381        // Sibling of the peer per-`:politicas`
30382        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
30383        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
30384        // peer per-`:politicas` `Option<u32>` shape — second
30385        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
30386        // Pins against a future silent detour that re-derived the retry
30387        // cap from a peer axis (an accidental `.circuit_breaker
30388        // .as_ref().map(|b| b.max_failures)` collapse that read the
30389        // breaker's max-failure count as a retry budget), a
30390        // `None → Some(0)` cluster-default projection (which would
30391        // silently re-introduce the `PolicyRetriesZero` refusal case at
30392        // the emit boundary), or a bounds-collapsing accessor that
30393        // clamped the return through `POLICY_RETRIES_MAX` (the
30394        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
30395        // must ship the raw slot verbatim so a validate-time gate
30396        // regression surfaces at the emit boundary rather than being
30397        // silently absorbed).
30398        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
30399            let p = MeshPolicy {
30400                retries,
30401                ..MeshPolicy::default()
30402            };
30403            assert_eq!(
30404                p.retries(),
30405                retries,
30406                "MeshPolicy::retries must return :politicas :retries \
30407                 verbatim (got {:?}, expected {retries:?})",
30408                p.retries(),
30409            );
30410            assert_eq!(
30411                p.retries(),
30412                p.retries,
30413                "MeshPolicy::retries must byte-equal the raw .retries \
30414                 field access across every value in the accept-set",
30415            );
30416        }
30417    }
30418
30419    #[test]
30420    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
30421        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
30422        // must key off [`MeshPolicy::retries`], not the raw `.retries`
30423        // field access. Structurally: toggling ONLY the `retries` slot
30424        // on an otherwise-default MeshPolicy must flip `is_empty()`
30425        // from `true` (all-`None`) to `false` (one axis carries a
30426        // value); the flip must be observed for every value in the
30427        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
30428        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
30429        // the emptiness semantic reads "any axis carries a value" —
30430        // not "any axis carries a value the validate gate accepts" —
30431        // the same non-collapsing shape the peer M2
30432        // [`crate::LimitsSpec::is_empty`] /
30433        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30434        //
30435        // Pins against a future silent detour that re-derived the
30436        // emptiness predicate off a peer axis (an accidental
30437        // `.rate_limit.is_none()`-only chain that dropped the
30438        // `retries` arm entirely), a `retries == Some(_)` collapse
30439        // that key-off a validate-gate-clamped bounds check (which
30440        // would silently classify a past-the-guard `Some(u32::MAX)`
30441        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
30442        // check), or an accessor-side detour that no longer names the
30443        // substrate-primitive typed dispatch.
30444        //
30445        // Sibling of the peer per-`:politicas`
30446        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
30447        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
30448        // same "the emptiness predicate must route through the
30449        // substrate-primitive typed dispatch" discipline extended onto
30450        // the peer per-`:politicas` `Option<u32>` axis.
30451        let empty = MeshPolicy::default();
30452        assert!(
30453            empty.is_empty(),
30454            "MeshPolicy::default() must be is_empty() — every axis \
30455             defaults to None",
30456        );
30457        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
30458            let p = MeshPolicy {
30459                retries,
30460                ..MeshPolicy::default()
30461            };
30462            assert!(
30463                !p.is_empty(),
30464                "MeshPolicy::is_empty must return false when \
30465                 :retries is {retries:?} — the emptiness \
30466                 predicate reads \"any axis carries a value\", not \
30467                 \"any axis carries a value the validate gate \
30468                 accepts\"",
30469            );
30470            assert_eq!(
30471                p.retries().is_none(),
30472                p.is_empty(),
30473                "when :retries is the only set axis, is_empty() \
30474                 must equal retries().is_none() — the accessor and \
30475                 the emptiness predicate must route through the same \
30476                 substrate-primitive typed dispatch on the :retries \
30477                 arm",
30478            );
30479        }
30480    }
30481
30482    #[test]
30483    fn mesh_policy_retries_projects_option_u32_by_copy() {
30484        // The by-copy pin: [`MeshPolicy::retries`] returns
30485        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
30486        // accessor must return by value, not by reference. Sibling of
30487        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
30488        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
30489        // extended onto the sibling `Option<u32>` copy-invariant
30490        // shape — the accessor's returned `Option<u32>` must outlive
30491        // `&self` (multiple calls must return equal values from a
30492        // dropped-`&self` copy, since the returned Option carries no
30493        // borrow), and calling the accessor twice on the same
30494        // MeshPolicy must yield the same `Option<u32>` verbatim
30495        // (idempotent, no side effects on `&self`).
30496        //
30497        // Pins against a future silent detour that returned
30498        // `Option<&u32>` (which would type-check but silently break
30499        // every downstream caller — [`crate::render::single_field_overlay`]'s
30500        // first parameter is `Option<T: Clone>`, and `&u32` would
30501        // fold to a detached copy at the call site), an accidental
30502        // `Option::as_ref()` projection (`self.retries.as_ref()` would
30503        // also type-check but return `Option<&u32>`), or a one-arm-
30504        // only accessor that reads `Some(*n)` in the Some arm but
30505        // reads a fresh `Default::default()` (`0_u32`) in the None
30506        // arm.
30507        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
30508            let p = MeshPolicy {
30509                retries,
30510                ..MeshPolicy::default()
30511            };
30512            let first = p.retries();
30513            let second = p.retries();
30514            assert_eq!(
30515                first, second,
30516                "MeshPolicy::retries must be idempotent — two \
30517                 successive calls on the same &self must return the \
30518                 same Option<u32>",
30519            );
30520            assert_eq!(
30521                first, retries,
30522                "MeshPolicy::retries must return :politicas :retries \
30523                 verbatim by copy — got {first:?}, expected {retries:?}",
30524            );
30525        }
30526    }
30527
30528    #[test]
30529    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
30530        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
30531        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
30532        // return the `:politicas :timeout` typed [`Duration`] verbatim
30533        // as an `Option<Duration>`, byte-equal to the raw field access
30534        // across every representative value in the accept-set — `None`
30535        // (cluster default applies — typically the gateway class's
30536        // implementation-side per-request wall-clock cap the caixa-mesh
30537        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
30538        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
30539        // set the surrounding `AplicacaoSpec::validate_politicas` gate
30540        // carves out on the sibling `PolicyTimeoutZero` /
30541        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
30542        // (the upper boundary the same gate carves out on the sibling
30543        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
30544        // (a past-the-guard sentinel that pins the accessor doesn't
30545        // perform a silent bounds-collapse into `None` on the zero-
30546        // Duration arm — validate rejects zero but the accessor must
30547        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
30548        // past-the-guard sentinel that pins the accessor doesn't
30549        // perform a silent bounds-collapse at the return path).
30550        //
30551        // Sibling of the peer per-`:politicas`
30552        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
30553        // `Option<u32>` optional-scalar axis and the peer per-
30554        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
30555        // pin on the sibling `Option<bool>` optional-scalar axis,
30556        // extended onto the peer per-`:politicas` `Option<Duration>`
30557        // shape — third `Option<Copy-T>`-return accessor on the M3
30558        // mesh-slot family. Pins against a future silent detour that
30559        // re-derived the per-call cap from a peer axis (an accidental
30560        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
30561        // read the breaker's rolling-window duration as a per-call
30562        // deadline), a `None → Some(Duration::MAX)` cluster-default
30563        // projection (which would silently re-introduce the
30564        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
30565        // blocking" arm at the emit boundary), or a bounds-collapsing
30566        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
30567        // (the `AplicacaoSpec::validate` gate owns the bounds; the
30568        // accessor must ship the raw slot verbatim so a validate-time
30569        // gate regression surfaces at the emit boundary rather than
30570        // being silently absorbed).
30571        for timeout in [
30572            None,
30573            Some(Duration::from_millis(1)),
30574            Some(POLICY_TIMEOUT_MAX),
30575            Some(Duration::ZERO),
30576            Some(Duration::MAX),
30577        ] {
30578            let p = MeshPolicy {
30579                timeout,
30580                ..MeshPolicy::default()
30581            };
30582            assert_eq!(
30583                p.timeout(),
30584                timeout,
30585                "MeshPolicy::timeout must return :politicas :timeout \
30586                 verbatim (got {:?}, expected {timeout:?})",
30587                p.timeout(),
30588            );
30589            assert_eq!(
30590                p.timeout(),
30591                p.timeout,
30592                "MeshPolicy::timeout must byte-equal the raw .timeout \
30593                 field access across every value in the accept-set",
30594            );
30595        }
30596    }
30597
30598    #[test]
30599    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
30600        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
30601        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
30602        // field access. Structurally: toggling ONLY the `timeout` slot
30603        // on an otherwise-default MeshPolicy must flip `is_empty()`
30604        // from `true` (all-`None`) to `false` (one axis carries a
30605        // value); the flip must be observed for every value in the
30606        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
30607        // gate accepts (`Some(Duration::from_millis(1))`,
30608        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
30609        // reads "any axis carries a value" — not "any axis carries a
30610        // value the validate gate accepts" — the same non-collapsing
30611        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
30612        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30613        //
30614        // Pins against a future silent detour that re-derived the
30615        // emptiness predicate off a peer axis (an accidental
30616        // `.rate_limit.is_none()`-only chain that dropped the
30617        // `timeout` arm entirely), a `timeout == Some(_)` collapse
30618        // that key-off a validate-gate-clamped bounds check (which
30619        // would silently classify a past-the-guard `Some(Duration::MAX)`
30620        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
30621        // check), or an accessor-side detour that no longer names the
30622        // substrate-primitive typed dispatch.
30623        //
30624        // Sibling of the peer per-`:politicas`
30625        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
30626        // the sibling `Option<u32>` optional-scalar axis and the peer
30627        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
30628        // accessor-composition pin on the sibling `Option<bool>`
30629        // optional-scalar axis — same "the emptiness predicate must
30630        // route through the substrate-primitive typed dispatch"
30631        // discipline extended onto the peer per-`:politicas`
30632        // `Option<Duration>` axis.
30633        let empty = MeshPolicy::default();
30634        assert!(
30635            empty.is_empty(),
30636            "MeshPolicy::default() must be is_empty() — every axis \
30637             defaults to None",
30638        );
30639        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
30640            let p = MeshPolicy {
30641                timeout,
30642                ..MeshPolicy::default()
30643            };
30644            assert!(
30645                !p.is_empty(),
30646                "MeshPolicy::is_empty must return false when \
30647                 :timeout is {timeout:?} — the emptiness \
30648                 predicate reads \"any axis carries a value\", not \
30649                 \"any axis carries a value the validate gate \
30650                 accepts\"",
30651            );
30652            assert_eq!(
30653                p.timeout().is_none(),
30654                p.is_empty(),
30655                "when :timeout is the only set axis, is_empty() \
30656                 must equal timeout().is_none() — the accessor and \
30657                 the emptiness predicate must route through the same \
30658                 substrate-primitive typed dispatch on the :timeout \
30659                 arm",
30660            );
30661        }
30662    }
30663
30664    #[test]
30665    fn mesh_policy_timeout_projects_option_duration_by_copy() {
30666        // The by-copy pin: [`MeshPolicy::timeout`] returns
30667        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
30668        // and the accessor must return by value, not by reference.
30669        // Sibling of the peer per-`:politicas`
30670        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
30671        // sibling `Option<u32>` optional-scalar axis and the peer
30672        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
30673        // by-copy pin on the sibling `Option<bool>` optional-scalar
30674        // axis, extended onto the peer per-`:politicas`
30675        // `Option<Duration>` copy-invariant shape — the accessor's
30676        // returned `Option<Duration>` must outlive `&self` (multiple
30677        // calls must return equal values from a dropped-`&self`
30678        // copy, since the returned Option carries no borrow), and
30679        // calling the accessor twice on the same MeshPolicy must
30680        // yield the same `Option<Duration>` verbatim (idempotent, no
30681        // side effects on `&self`).
30682        //
30683        // Pins against a future silent detour that returned
30684        // `Option<&Duration>` (which would type-check but silently
30685        // break every downstream caller — [`crate::render::single_field_overlay`]'s
30686        // first parameter is `Option<T: Clone>`, and `&Duration`
30687        // would fold to a detached copy at the call site), an
30688        // accidental `Option::as_ref()` projection
30689        // (`self.timeout.as_ref()` would also type-check but return
30690        // `Option<&Duration>`), or a one-arm-only accessor that
30691        // reads `Some(*d)` in the Some arm but reads a fresh
30692        // `Default::default()` (`Duration::ZERO`) in the None arm
30693        // (which would silently re-classify every unset `:timeout`
30694        // as the `PolicyTimeoutZero`-refused zero-Duration value at
30695        // the accessor boundary).
30696        for timeout in [
30697            None,
30698            Some(Duration::from_millis(1)),
30699            Some(POLICY_TIMEOUT_MAX),
30700            Some(Duration::ZERO),
30701            Some(Duration::MAX),
30702        ] {
30703            let p = MeshPolicy {
30704                timeout,
30705                ..MeshPolicy::default()
30706            };
30707            let first = p.timeout();
30708            let second = p.timeout();
30709            assert_eq!(
30710                first, second,
30711                "MeshPolicy::timeout must be idempotent — two \
30712                 successive calls on the same &self must return the \
30713                 same Option<Duration>",
30714            );
30715            assert_eq!(
30716                first, timeout,
30717                "MeshPolicy::timeout must return :politicas :timeout \
30718                 verbatim by copy — got {first:?}, expected {timeout:?}",
30719            );
30720        }
30721    }
30722
30723    #[test]
30724    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
30725        // The canonical per-`:politicas` `:rate-limit` Envoy-
30726        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
30727        // [`MeshPolicy::rate_limit`] must return the `:politicas
30728        // :rate-limit` typed [`RateLimit`] verbatim as an
30729        // `Option<RateLimit>`, byte-equal to the raw field access
30730        // across every representative value in the accept-set — `None`
30731        // (cluster default applies — no per-Aplicacao rate declaration,
30732        // the gateway-class per-listener default arm the future caixa-
30733        // mesh `local_rate_limit_overlay` emitter documents),
30734        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
30735        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
30736        // accept-set the surrounding
30737        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
30738        // sibling `PolicyRateLimitZero` refusal, paired with the
30739        // canonical-window "1 second" arm of the three-unit
30740        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
30741        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
30742        // (the upper boundary the same gate carves out on the sibling
30743        // `PolicyRateLimitExceedsCap` refusal, paired with the
30744        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
30745        // (a past-the-guard sentinel that pins the accessor doesn't
30746        // perform a silent bounds-collapse into `None` on the
30747        // zero-rate/zero-window arm — validate rejects zero but the
30748        // accessor must ship the raw slot verbatim so a validate-time
30749        // gate regression surfaces at the emit boundary rather than
30750        // being silently absorbed), and
30751        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
30752        // (a past-the-guard sentinel that pins the accessor doesn't
30753        // perform a silent bounds-collapse at the return path).
30754        //
30755        // First `Option<Copy-composite-T>`-return accessor pin on the
30756        // M3 mesh-slot family (peer of the sibling per-`:politicas`
30757        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
30758        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
30759        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
30760        // Copy accessor pins, extended onto the peer per-`:politicas`
30761        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
30762        // and the accessor returns by value). Pins against a future
30763        // silent detour that re-derived the rate declaration from a
30764        // peer axis (an accidental
30765        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
30766        // collapse that read the breaker's trip threshold + rolling
30767        // window as a rate declaration), a `None → Some(default())`
30768        // cluster-default projection (which would silently re-
30769        // introduce a "cluster default is 0/s" arm the emit boundary
30770        // would take as "declared but inert" — the canonical
30771        // declared-but-inert footgun the sibling
30772        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
30773        // amplification-shape axis), a bounds-collapsing accessor
30774        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
30775        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
30776        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
30777        // accessor must ship the raw slot verbatim), or a
30778        // by-reference detour (`Option<&RateLimit>`) that broke every
30779        // downstream consumer keying off `Option<RateLimit>` by-copy.
30780        for rl in [
30781            None,
30782            Some(RateLimit {
30783                rate: 1,
30784                window: Duration::from_secs(1),
30785            }),
30786            Some(RateLimit {
30787                rate: POLICY_RATE_LIMIT_MAX,
30788                window: Duration::from_secs(3600),
30789            }),
30790            Some(RateLimit {
30791                rate: 0,
30792                window: Duration::ZERO,
30793            }),
30794            Some(RateLimit {
30795                rate: u32::MAX,
30796                window: Duration::MAX,
30797            }),
30798        ] {
30799            let p = MeshPolicy {
30800                rate_limit: rl,
30801                ..MeshPolicy::default()
30802            };
30803            assert_eq!(
30804                p.rate_limit(),
30805                rl,
30806                "MeshPolicy::rate_limit must return :politicas :rate-limit \
30807                 verbatim (got {:?}, expected {rl:?})",
30808                p.rate_limit(),
30809            );
30810            assert_eq!(
30811                p.rate_limit(),
30812                p.rate_limit,
30813                "MeshPolicy::rate_limit must byte-equal the raw \
30814                 .rate_limit field access across every value in the \
30815                 accept-set",
30816            );
30817        }
30818    }
30819
30820    #[test]
30821    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
30822        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
30823        // must key off [`MeshPolicy::rate_limit`], not the raw
30824        // `.rate_limit` field access. Structurally: toggling ONLY the
30825        // `rate_limit` slot on an otherwise-default MeshPolicy must
30826        // flip `is_empty()` from `true` (all-`None`) to `false` (one
30827        // axis carries a value); the flip must be observed for every
30828        // representative value in the accept-set the surrounding
30829        // [`AplicacaoSpec::validate_politicas`] gate accepts
30830        // (`Some(RateLimit { rate: 1, window: 1s })`,
30831        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
30832        // since the emptiness semantic reads "any axis carries a
30833        // value" — not "any axis carries a value the validate gate
30834        // accepts" — the same non-collapsing shape the peer M2
30835        // [`crate::LimitsSpec::is_empty`] /
30836        // [`crate::BehaviorSpec::is_empty`] predicates carry.
30837        //
30838        // Pins against a future silent detour that re-derived the
30839        // emptiness predicate off a peer axis (an accidental
30840        // `.timeout.is_none()`-only chain that dropped the
30841        // `rate_limit` arm entirely — the last unlifted inline field
30842        // access on `is_empty` before this lift), a `rate_limit ==
30843        // Some(_)` collapse that key-off a validate-gate-clamped
30844        // bounds check (which would silently classify a past-the-
30845        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
30846        // because it fails the value-shape gate), or an accessor-
30847        // side detour that no longer names the substrate-primitive
30848        // typed dispatch.
30849        //
30850        // Fourth "the emptiness predicate must route through the
30851        // substrate-primitive typed dispatch" composition pin on the
30852        // M3 mesh-slot family — closes the last unlifted composition
30853        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
30854        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
30855        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
30856        // 7073d0f is_empty-composition pins on the sibling primitive-
30857        // Copy axes, extended onto the peer per-`:politicas`
30858        // composite-Copy `Option<RateLimit>` axis).
30859        let empty = MeshPolicy::default();
30860        assert!(
30861            empty.is_empty(),
30862            "MeshPolicy::default() must be is_empty() — every axis \
30863             defaults to None",
30864        );
30865        for rl in [
30866            RateLimit {
30867                rate: 1,
30868                window: Duration::from_secs(1),
30869            },
30870            RateLimit {
30871                rate: POLICY_RATE_LIMIT_MAX,
30872                window: Duration::from_secs(3600),
30873            },
30874        ] {
30875            let p = MeshPolicy {
30876                rate_limit: Some(rl),
30877                ..MeshPolicy::default()
30878            };
30879            assert!(
30880                !p.is_empty(),
30881                "MeshPolicy::is_empty must return false when \
30882                 :rate-limit is {rl:?} — the emptiness predicate \
30883                 reads \"any axis carries a value\", not \"any axis \
30884                 carries a value the validate gate accepts\"",
30885            );
30886            assert_eq!(
30887                p.rate_limit().is_none(),
30888                p.is_empty(),
30889                "when :rate-limit is the only set axis, is_empty() \
30890                 must equal rate_limit().is_none() — the accessor \
30891                 and the emptiness predicate must route through the \
30892                 same substrate-primitive typed dispatch on the \
30893                 :rate-limit arm",
30894            );
30895        }
30896    }
30897
30898    #[test]
30899    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
30900        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
30901        // `:rate-limit` value-shape gate must key off
30902        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
30903        // field bind. Structurally: a `MeshPolicy` whose only set
30904        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
30905        // the `PolicyRateLimitZero` refusal exactly, and the same
30906        // MeshPolicy with the rate at the canonical lower boundary
30907        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
30908        // The pair jointly pins the accessor + validate-gate
30909        // composition: any future silent detour that had the accessor
30910        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
30911        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
30912        // silently absorb the `PolicyRateLimitZero` refusal at the
30913        // accessor boundary — the composition pin catches that at
30914        // caixa-core build time.
30915        //
30916        // Sibling of the peer [`validate_politicas`]
30917        // `:mtls-required` / `:retries` / `:timeout` composition pins
30918        // on the sibling primitive-Copy optional-scalar axes — same
30919        // "the validate / shape-gate predicate must route through the
30920        // substrate-primitive typed dispatch" discipline extended
30921        // onto the peer per-`:politicas` composite-Copy
30922        // `Option<RateLimit>` axis. Second composition-with-accessor
30923        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
30924        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
30925        let mut spec = three_member_spec();
30926        spec.politicas = MeshPolicy {
30927            rate_limit: Some(RateLimit {
30928                rate: 0,
30929                window: Duration::from_secs(1),
30930            }),
30931            ..MeshPolicy::default()
30932        };
30933        assert!(
30934            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
30935            "validate_politicas must reject rate == 0 with \
30936             PolicyRateLimitZero — the accessor and the validate gate \
30937             must route through the same substrate-primitive typed \
30938             dispatch on the :rate-limit zero-floor arm",
30939        );
30940        spec.politicas = MeshPolicy {
30941            rate_limit: Some(RateLimit {
30942                rate: 1,
30943                window: Duration::from_secs(1),
30944            }),
30945            ..MeshPolicy::default()
30946        };
30947        assert!(
30948            spec.validate().is_ok(),
30949            "validate_politicas must accept rate == 1 (the canonical \
30950             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
30951             set) with a canonical 1s window",
30952        );
30953    }
30954
30955    #[test]
30956    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
30957        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
30958        // `outlier_detection`-mesh consecutive-failure-ejection scalar
30959        // pin: [`MeshPolicy::circuit_breaker`] must return the
30960        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
30961        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
30962        // raw field access across every representative value in the
30963        // accept-set — `None` (cluster default applies — no
30964        // per-Aplicacao breaker declaration, the gateway-class per-
30965        // listener default arm the future caixa-mesh
30966        // `outlier_detection_overlay` emitter documents),
30967        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
30968        // (the lower boundary of the accept-set the surrounding
30969        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
30970        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
30971        // refusals),
30972        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
30973        // (the upper boundary the same gate carves out on the sibling
30974        // `PolicyBreakerMaxFailuresExceedsCap` /
30975        // `PolicyBreakerWindowExceedsCap` refusals),
30976        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
30977        // (a past-the-guard sentinel that pins the accessor doesn't
30978        // perform a silent bounds-collapse into `None` on the
30979        // zero-failures/zero-window arm — validate rejects zero but
30980        // the accessor must ship the raw slot verbatim so a validate-
30981        // time gate regression surfaces at the emit boundary rather
30982        // than being silently absorbed), and
30983        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
30984        // (a past-the-guard sentinel that pins the accessor doesn't
30985        // perform a silent bounds-collapse at the return path).
30986        //
30987        // Second `Option<Copy-composite-T>`-return accessor pin on the
30988        // M3 mesh-slot family (peer of the sibling per-`:politicas`
30989        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
30990        // composite-Copy accessor pin, and of the sibling per-
30991        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
30992        // [`MeshPolicy::retries`] bdfb399 /
30993        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
30994        // accessor pins). Pins against a future silent detour that
30995        // re-derived the breaker declaration from a peer axis (an
30996        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
30997        // collapse that read the rate-limit's bucket capacity + refill
30998        // period as a breaker declaration), a `None → Some(default())`
30999        // cluster-default projection (which would silently re-
31000        // introduce the `PolicyBreakerZeroFailures` /
31001        // `PolicyBreakerZeroWindow` refusal cases at the emit
31002        // boundary), a bounds-collapsing accessor that clamped
31003        // `cb.max_failures` through
31004        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
31005        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
31006        // [`AplicacaoSpec::validate`] gate owns the bounds; the
31007        // accessor must ship the raw slot verbatim), or a
31008        // by-reference detour (`Option<&CircuitBreaker>`) that broke
31009        // every downstream consumer keying off `Option<CircuitBreaker>`
31010        // by-copy.
31011        for cb in [
31012            None,
31013            Some(CircuitBreaker {
31014                max_failures: 1,
31015                window: Duration::from_millis(1),
31016            }),
31017            Some(CircuitBreaker {
31018                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
31019                window: POLICY_BREAKER_WINDOW_MAX,
31020            }),
31021            Some(CircuitBreaker {
31022                max_failures: 0,
31023                window: Duration::ZERO,
31024            }),
31025            Some(CircuitBreaker {
31026                max_failures: u32::MAX,
31027                window: Duration::MAX,
31028            }),
31029        ] {
31030            let p = MeshPolicy {
31031                circuit_breaker: cb,
31032                ..MeshPolicy::default()
31033            };
31034            assert_eq!(
31035                p.circuit_breaker(),
31036                cb,
31037                "MeshPolicy::circuit_breaker must return :politicas \
31038                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
31039                p.circuit_breaker(),
31040            );
31041            assert_eq!(
31042                p.circuit_breaker(),
31043                p.circuit_breaker,
31044                "MeshPolicy::circuit_breaker must byte-equal the raw \
31045                 .circuit_breaker field access across every value in \
31046                 the accept-set",
31047            );
31048        }
31049    }
31050
31051    #[test]
31052    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
31053        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
31054        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
31055        // `.circuit_breaker` field access. Structurally: toggling ONLY
31056        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
31057        // must flip `is_empty()` from `true` (all-`None`) to `false`
31058        // (one axis carries a value); the flip must be observed for
31059        // every representative value in the accept-set the surrounding
31060        // [`AplicacaoSpec::validate_politicas`] gate accepts
31061        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
31062        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
31063        // since the emptiness semantic reads "any axis carries a
31064        // value" — not "any axis carries a value the validate gate
31065        // accepts" — the same non-collapsing shape the peer M2
31066        // [`crate::LimitsSpec::is_empty`] /
31067        // [`crate::BehaviorSpec::is_empty`] predicates carry.
31068        //
31069        // Pins against a future silent detour that re-derived the
31070        // emptiness predicate off a peer axis (an accidental
31071        // `.rate_limit.is_none()`-only chain that dropped the
31072        // `circuit_breaker` arm entirely — the last unlifted inline
31073        // field access on `is_empty` before this lift), a
31074        // `circuit_breaker == Some(_)` collapse that key-off a
31075        // validate-gate-clamped bounds check (which would silently
31076        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
31077        // 0, window: 0s })` as empty because it fails the value-shape
31078        // gate), or an accessor-side detour that no longer names the
31079        // substrate-primitive typed dispatch.
31080        //
31081        // Fifth "the emptiness predicate must route through the
31082        // substrate-primitive typed dispatch" composition pin on the
31083        // M3 mesh-slot family — closes the last unlifted composition
31084        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
31085        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
31086        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
31087        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
31088        // composition pins on the sibling primitive-Copy + composite-
31089        // Copy axes, extended onto the peer per-`:politicas`
31090        // composite-Copy `Option<CircuitBreaker>` axis).
31091        let empty = MeshPolicy::default();
31092        assert!(
31093            empty.is_empty(),
31094            "MeshPolicy::default() must be is_empty() — every axis \
31095             defaults to None",
31096        );
31097        for cb in [
31098            CircuitBreaker {
31099                max_failures: 1,
31100                window: Duration::from_millis(1),
31101            },
31102            CircuitBreaker {
31103                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
31104                window: POLICY_BREAKER_WINDOW_MAX,
31105            },
31106        ] {
31107            let p = MeshPolicy {
31108                circuit_breaker: Some(cb),
31109                ..MeshPolicy::default()
31110            };
31111            assert!(
31112                !p.is_empty(),
31113                "MeshPolicy::is_empty must return false when \
31114                 :circuit-breaker is {cb:?} — the emptiness predicate \
31115                 reads \"any axis carries a value\", not \"any axis \
31116                 carries a value the validate gate accepts\"",
31117            );
31118            assert_eq!(
31119                p.circuit_breaker().is_none(),
31120                p.is_empty(),
31121                "when :circuit-breaker is the only set axis, \
31122                 is_empty() must equal circuit_breaker().is_none() — \
31123                 the accessor and the emptiness predicate must route \
31124                 through the same substrate-primitive typed dispatch \
31125                 on the :circuit-breaker arm",
31126            );
31127        }
31128    }
31129
31130    #[test]
31131    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
31132        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31133        // `:circuit-breaker` value-shape gate must key off
31134        // [`MeshPolicy::circuit_breaker`], not the raw
31135        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
31136        // whose only set axis is a `Some(CircuitBreaker { max_failures:
31137        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
31138        // refusal exactly, and the same MeshPolicy with the breaker at
31139        // the canonical lower boundary
31140        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
31141        // pass validate. The pair jointly pins the accessor +
31142        // validate-gate composition: any future silent detour that had
31143        // the accessor omit the `Some(CircuitBreaker { max_failures:
31144        // 0, .. })` arm (a
31145        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
31146        // collapse) would silently absorb the
31147        // `PolicyBreakerZeroFailures` refusal at the accessor
31148        // boundary — the composition pin catches that at caixa-core
31149        // build time.
31150        //
31151        // Sibling of the peer [`validate_politicas`]
31152        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
31153        // composition pins on the sibling primitive-Copy + composite-
31154        // Copy optional-scalar axes — same "the validate / shape-gate
31155        // predicate must route through the substrate-primitive typed
31156        // dispatch" discipline extended onto the peer per-`:politicas`
31157        // composite-Copy `Option<CircuitBreaker>` axis. Second
31158        // composition-with-accessor pin on the M3 mesh-slot
31159        // `Option<CircuitBreaker>` arm alongside the
31160        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
31161        let mut spec = three_member_spec();
31162        spec.politicas = MeshPolicy {
31163            circuit_breaker: Some(CircuitBreaker {
31164                max_failures: 0,
31165                window: Duration::from_millis(1),
31166            }),
31167            ..MeshPolicy::default()
31168        };
31169        assert!(
31170            matches!(
31171                spec.validate(),
31172                Err(AplicacaoError::PolicyBreakerZeroFailures)
31173            ),
31174            "validate_politicas must reject max_failures == 0 with \
31175             PolicyBreakerZeroFailures — the accessor and the validate \
31176             gate must route through the same substrate-primitive \
31177             typed dispatch on the :circuit-breaker zero-floor arm",
31178        );
31179        spec.politicas = MeshPolicy {
31180            circuit_breaker: Some(CircuitBreaker {
31181                max_failures: 1,
31182                window: Duration::from_millis(1),
31183            }),
31184            ..MeshPolicy::default()
31185        };
31186        assert!(
31187            spec.validate().is_ok(),
31188            "validate_politicas must accept a CircuitBreaker at the \
31189             canonical lower boundary (max_failures = 1, window = \
31190             1ms) — the accessor and the validate gate must route \
31191             through the same substrate-primitive typed dispatch on \
31192             the :circuit-breaker arm",
31193        );
31194    }
31195
31196    #[test]
31197    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
31198        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
31199        // Envoy-outlier-detection trip-threshold scalar pin:
31200        // [`CircuitBreaker::max_failures`] must return the
31201        // `:politicas :circuit-breaker :max-failures` typed `u32`
31202        // verbatim, byte-equal to the raw field access across every
31203        // representative value in the accept-set — `1` (the lower
31204        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
31205        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
31206        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
31207        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
31208        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
31209        // refusal), `0` (a past-the-guard sentinel that pins the accessor
31210        // doesn't perform a silent bounds-collapse into `1` on the zero
31211        // arm — validate rejects zero but the accessor must ship the
31212        // raw slot verbatim so a validate-time gate regression surfaces
31213        // at the emit boundary rather than being silently absorbed),
31214        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
31215        // doesn't perform a silent bounds-collapse through
31216        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
31217        //
31218        // First sub-struct required-scalar accessor pin on the M3
31219        // mesh-slot family — sibling in shape to the peer per-`:membros`
31220        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
31221        // (a40b0e3) required-`String`-carry accessor pins and the peer
31222        // per-`:contratos` [`WitContract::source`] /
31223        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
31224        // accessor pins, extended onto the peer per-`CircuitBreaker`
31225        // required-`u32` scalar-value axis. Pins against a future silent
31226        // detour that re-derived the trip threshold from a peer axis (an
31227        // accidental `self.window.as_secs() as u32` collapse that read
31228        // the breaker's rolling-window duration as a failure count), a
31229        // `0 → 1` cluster-default projection (which would silently absorb
31230        // the `PolicyBreakerZeroFailures` refusal case at the accessor
31231        // boundary), or a bounds-collapsing accessor that clamped the
31232        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
31233        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
31234        // must ship the raw slot verbatim).
31235        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
31236            let cb = CircuitBreaker {
31237                max_failures,
31238                window: Duration::from_secs(60),
31239            };
31240            assert_eq!(
31241                cb.max_failures(),
31242                max_failures,
31243                "CircuitBreaker::max_failures must return :politicas \
31244                 :circuit-breaker :max-failures verbatim (got {}, \
31245                 expected {max_failures})",
31246                cb.max_failures(),
31247            );
31248            assert_eq!(
31249                cb.max_failures(),
31250                cb.max_failures,
31251                "CircuitBreaker::max_failures must byte-equal the raw \
31252                 .max_failures field access across every value in the \
31253                 u32 accept-set",
31254            );
31255        }
31256    }
31257
31258    #[test]
31259    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
31260        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31261        // `:circuit-breaker :max-failures` zero-floor arm must key off
31262        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
31263        // field access. Structurally: a `CircuitBreaker { max_failures:
31264        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
31265        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
31266        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
31267        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
31268        // pass validate. The pair jointly pins the accessor +
31269        // validate-gate composition: any future silent detour that had
31270        // the accessor return a fresh `1` on the zero arm (a
31271        // `.max_failures().max(1)` collapse) would silently absorb the
31272        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
31273        // and the validate gate would accept a struct-literal
31274        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
31275        // catches that at caixa-core build time.
31276        //
31277        // Peer of the sibling per-`:politicas`
31278        // [`MeshPolicy::mtls_required`] (c0110f1) /
31279        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
31280        // (7073d0f) accessor-composition pins on the sibling optional-
31281        // scalar axes — same "the validate / shape-gate predicate must
31282        // route through the substrate-primitive typed dispatch"
31283        // discipline extended onto the peer per-`CircuitBreaker`
31284        // required-scalar composition axis.
31285        let mut spec = three_member_spec();
31286        spec.politicas = MeshPolicy {
31287            circuit_breaker: Some(CircuitBreaker {
31288                max_failures: 0,
31289                window: Duration::from_secs(60),
31290            }),
31291            ..MeshPolicy::default()
31292        };
31293        assert!(
31294            matches!(
31295                spec.validate(),
31296                Err(AplicacaoError::PolicyBreakerZeroFailures)
31297            ),
31298            "validate_politicas must reject max_failures == 0 with \
31299             PolicyBreakerZeroFailures — the accessor and the validate \
31300             gate must route through the same substrate-primitive typed \
31301             dispatch on the :max-failures zero-floor arm",
31302        );
31303        spec.politicas = MeshPolicy {
31304            circuit_breaker: Some(CircuitBreaker {
31305                max_failures: 1,
31306                window: Duration::from_secs(60),
31307            }),
31308            ..MeshPolicy::default()
31309        };
31310        assert!(
31311            spec.validate().is_ok(),
31312            "validate_politicas must accept max_failures == 1 (the \
31313             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
31314             accept-set)",
31315        );
31316    }
31317
31318    #[test]
31319    fn circuit_breaker_max_failures_projects_u32_by_copy() {
31320        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
31321        // `u32` by copy — `u32` is `Copy` and the accessor must return
31322        // by value, not by reference. Peer of the sibling
31323        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
31324        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
31325        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
31326        // optional-scalar axes, extended onto the peer
31327        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
31328        // the accessor's returned `u32` must outlive `&self` (multiple
31329        // calls must return equal values from a dropped-`&self` copy,
31330        // since the returned scalar carries no borrow), and calling
31331        // the accessor twice on the same CircuitBreaker must yield the
31332        // same `u32` verbatim (idempotent, no side effects on `&self`).
31333        //
31334        // Pins against a future silent detour that returned `&u32`
31335        // (which would type-check but silently break every downstream
31336        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
31337        // first parameter is `u32`, and `&u32` would fold to a detached
31338        // copy at the call site with a `*` deref the sibling accessors
31339        // don't need), an accidental `.max_failures.wrapping_add(0)`
31340        // detour that returned a fresh copy through an arithmetic
31341        // no-op (breaking a future `const fn` regression), or a
31342        // one-arm-only accessor that returned a saturating value on
31343        // some sentinel input (breaking the pass-through invariant the
31344        // sibling required-scalar accessors carry).
31345        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
31346            let cb = CircuitBreaker {
31347                max_failures,
31348                window: Duration::from_secs(60),
31349            };
31350            let first = cb.max_failures();
31351            let second = cb.max_failures();
31352            assert_eq!(
31353                first, second,
31354                "CircuitBreaker::max_failures must be idempotent — two \
31355                 successive calls on the same &self must return the \
31356                 same u32",
31357            );
31358            assert_eq!(
31359                first, max_failures,
31360                "CircuitBreaker::max_failures must return :politicas \
31361                 :circuit-breaker :max-failures verbatim by copy — \
31362                 got {first}, expected {max_failures}",
31363            );
31364        }
31365    }
31366
31367    #[test]
31368    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
31369        // The canonical per-`:politicas :circuit-breaker` `:window`
31370        // Envoy-outlier-detection rolling-observation-interval scalar
31371        // pin: [`CircuitBreaker::window`] must return the
31372        // `:politicas :circuit-breaker :window` typed `Duration`
31373        // verbatim, byte-equal to the raw field access across every
31374        // representative value in the accept-set — `Duration::from_millis(1)`
31375        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
31376        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
31377        // gate carves out on the sibling `PolicyBreakerZeroWindow`
31378        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
31379        // same gate carves out on the sibling
31380        // `PolicyBreakerWindowExceedsCap` refusal),
31381        // `Duration::ZERO` (a past-the-guard sentinel that pins the
31382        // accessor doesn't perform a silent bounds-collapse into
31383        // `Duration::from_millis(1)` on the zero arm — validate rejects
31384        // zero but the accessor must ship the raw slot verbatim so a
31385        // validate-time gate regression surfaces at the emit boundary
31386        // rather than being silently absorbed),
31387        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
31388        // far above the 1h cap — that pins the accessor doesn't perform
31389        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
31390        // at the return path).
31391        //
31392        // Second sub-struct required-scalar accessor pin on the M3
31393        // mesh-slot family — sibling in shape to the just-landed
31394        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
31395        // (3a74062) required-`u32` accessor pin on the peer
31396        // per-`CircuitBreaker` required-axis, extended onto the
31397        // per-sub-struct required-`Duration` axis. Pins against a
31398        // future silent detour that re-derived the observation window
31399        // from a peer axis (an accidental
31400        // `Duration::from_secs(self.max_failures as u64)` collapse that
31401        // read the breaker's trip count as an observation-interval
31402        // duration), a `Duration::ZERO → Duration::from_millis(1)`
31403        // cluster-default projection (which would silently absorb the
31404        // `PolicyBreakerZeroWindow` refusal case at the accessor
31405        // boundary), or a bounds-collapsing accessor that clamped the
31406        // return through `POLICY_BREAKER_WINDOW_MAX` (the
31407        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
31408        // must ship the raw slot verbatim).
31409        for window in [
31410            Duration::from_millis(1),
31411            POLICY_BREAKER_WINDOW_MAX,
31412            Duration::ZERO,
31413            Duration::from_secs(86_400),
31414        ] {
31415            let cb = CircuitBreaker {
31416                max_failures: 5,
31417                window,
31418            };
31419            assert_eq!(
31420                cb.window(),
31421                window,
31422                "CircuitBreaker::window must return :politicas \
31423                 :circuit-breaker :window verbatim (got {:?}, \
31424                 expected {window:?})",
31425                cb.window(),
31426            );
31427            assert_eq!(
31428                cb.window(),
31429                cb.window,
31430                "CircuitBreaker::window must byte-equal the raw \
31431                 .window field access across every value in the \
31432                 Duration accept-set",
31433            );
31434        }
31435    }
31436
31437    #[test]
31438    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
31439        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
31440        // `:circuit-breaker :window` zero-floor arm must key off
31441        // [`CircuitBreaker::window`], not the raw `.window` field
31442        // access. Structurally: a `CircuitBreaker { window:
31443        // Duration::ZERO, .. }` embedded in a
31444        // `:politicas :circuit-breaker` slot must surface the
31445        // `PolicyBreakerZeroWindow` refusal exactly, and a
31446        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
31447        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
31448        // accept-set) must pass validate. The pair jointly pins the
31449        // accessor + validate-gate composition: any future silent
31450        // detour that had the accessor return a fresh
31451        // `Duration::from_millis(1)` on the zero arm (a
31452        // `.window().max(Duration::from_millis(1))` collapse) would
31453        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
31454        // accessor boundary and the validate gate would accept a
31455        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
31456        // — the composition pin catches that at caixa-core build time.
31457        //
31458        // Peer of the sibling per-`CircuitBreaker`
31459        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
31460        // pin on the peer required-scalar `:max-failures` axis — same
31461        // "the validate / shape-gate predicate must route through the
31462        // substrate-primitive typed dispatch" discipline extended onto
31463        // the peer per-`CircuitBreaker` required-`Duration` composition
31464        // axis.
31465        let mut spec = three_member_spec();
31466        spec.politicas = MeshPolicy {
31467            circuit_breaker: Some(CircuitBreaker {
31468                max_failures: 5,
31469                window: Duration::ZERO,
31470            }),
31471            ..MeshPolicy::default()
31472        };
31473        assert!(
31474            matches!(
31475                spec.validate(),
31476                Err(AplicacaoError::PolicyBreakerZeroWindow)
31477            ),
31478            "validate_politicas must reject window == Duration::ZERO \
31479             with PolicyBreakerZeroWindow — the accessor and the \
31480             validate gate must route through the same substrate-\
31481             primitive typed dispatch on the :window zero-floor arm",
31482        );
31483        spec.politicas = MeshPolicy {
31484            circuit_breaker: Some(CircuitBreaker {
31485                max_failures: 5,
31486                window: Duration::from_millis(1),
31487            }),
31488            ..MeshPolicy::default()
31489        };
31490        assert!(
31491            spec.validate().is_ok(),
31492            "validate_politicas must accept window == \
31493             Duration::from_millis(1) (the lower boundary of the \
31494             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
31495        );
31496    }
31497
31498    #[test]
31499    fn circuit_breaker_window_projects_duration_by_copy() {
31500        // The by-copy pin: [`CircuitBreaker::window`] returns
31501        // `Duration` by copy — `Duration` is `Copy` and the accessor
31502        // must return by value, not by reference. Peer of the sibling
31503        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
31504        // (3a74062) by-copy pin on the peer required-scalar
31505        // `:max-failures` axis, extended onto the peer
31506        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
31507        // — the accessor's returned `Duration` must outlive `&self`
31508        // (multiple calls must return equal values from a
31509        // dropped-`&self` copy, since the returned scalar carries no
31510        // borrow), and calling the accessor twice on the same
31511        // CircuitBreaker must yield the same `Duration` verbatim
31512        // (idempotent, no side effects on `&self`).
31513        //
31514        // Pins against a future silent detour that returned
31515        // `&Duration` (which would type-check but silently break every
31516        // downstream `Duration`-by-value consumer —
31517        // [`crate::render::require_positive_canonical_bounded_duration`]'s
31518        // first parameter is `Duration`, and `&Duration` would fold to
31519        // a detached copy at the call site with a `*` deref the sibling
31520        // accessors don't need), an accidental `.window + Duration::ZERO`
31521        // detour that returned a fresh copy through an arithmetic
31522        // no-op (breaking a future `const fn` regression), or a
31523        // one-arm-only accessor that returned a saturating value on
31524        // some sentinel input (breaking the pass-through invariant the
31525        // sibling required-scalar accessors carry).
31526        for window in [
31527            Duration::from_millis(1),
31528            POLICY_BREAKER_WINDOW_MAX,
31529            Duration::ZERO,
31530            Duration::from_secs(86_400),
31531        ] {
31532            let cb = CircuitBreaker {
31533                max_failures: 5,
31534                window,
31535            };
31536            let first = cb.window();
31537            let second = cb.window();
31538            assert_eq!(
31539                first, second,
31540                "CircuitBreaker::window must be idempotent — two \
31541                 successive calls on the same &self must return the \
31542                 same Duration",
31543            );
31544            assert_eq!(
31545                first, window,
31546                "CircuitBreaker::window must return :politicas \
31547                 :circuit-breaker :window verbatim by copy — \
31548                 got {first:?}, expected {window:?}",
31549            );
31550        }
31551    }
31552
31553    #[test]
31554    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
31555        // Apex-identity pair-invariant pin composing both substrate-
31556        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
31557        // and [`WitContract::destination`] — at the emit-side call shape
31558        // every per-`(:de, :para)` CNP L4 port reader now takes. The
31559        // invariant, evaluated per-edge:
31560        //
31561        //   spec.port_for_destination(c.destination()) == expected_port
31562        //
31563        // where `expected_port` is `entrada.port` when
31564        // `c.destination() == entrada.destination()` and
31565        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
31566        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
31567        // pin on the per-`:entrada` axis — that pin encodes the apex
31568        // ingress L4 identity via `entrada.destination()`; this pin
31569        // encodes the per-edge L4 identity via `c.destination()`, and
31570        // both compose on the same substrate-primitive resolver so a
31571        // future refactor that silently split either accessor's apex
31572        // behavior surfaces at caixa-core build time.
31573        let mut spec = three_member_spec();
31574        if let Some(e) = spec.entrada.as_mut() {
31575            e.para = "cart".into();
31576            e.port = 8443;
31577        }
31578        let apex_contract = WitContract {
31579            de: "checkout".into(),
31580            para: "cart".into(),
31581            wit: "wasi:http/proxy".into(),
31582            endpoint: Some("/hello".into()),
31583            subject: None,
31584            slot: None,
31585        };
31586        assert_eq!(
31587            spec.port_for_destination(apex_contract.destination()),
31588            8443,
31589            "`spec.port_for_destination(c.destination())` must equal \
31590             `entrada.port` when the contract callee names the ingress \
31591             apex — the CNP per-edge L4 port and the HTTPRoute apex \
31592             backendRef port share this substrate-primitive resolver.",
31593        );
31594        let non_apex_contract = WitContract {
31595            de: "cart".into(),
31596            para: "payment".into(),
31597            wit: "wasi:http/proxy".into(),
31598            endpoint: Some("/charge".into()),
31599            subject: None,
31600            slot: None,
31601        };
31602        assert_eq!(
31603            spec.port_for_destination(non_apex_contract.destination()),
31604            DEFAULT_SERVICO_PORT,
31605            "`spec.port_for_destination(c.destination())` must fall back \
31606             to the substrate-canonical port floor when the contract \
31607             callee is not the ingress apex — the resolver's non-apex \
31608             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
31609        );
31610    }
31611
31612    #[test]
31613    fn membro_key_consts_are_lower_camel_case_shape() {
31614        // Shape-pin: every `MEMBRO_KEY_*` const must be a
31615        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31616        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31617        // leading capital, no whitespace / dots) — the canonical shape
31618        // the `#[serde(rename_all = "camelCase")]` derive produces on
31619        // [`Membro`]. A future flip to a non-camelCase attribute at
31620        // the derive surfaces both here (this test fails on the
31621        // stale-constant shape) and at
31622        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
31623        // fails on the mismatch between const and derive). Peer with
31624        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
31625        // on the sibling `SupervisorSpec` top-level axis.
31626        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
31627            assert!(
31628                !key.is_empty(),
31629                "MEMBRO_KEY_* must be non-empty (got {key:?})"
31630            );
31631            let first = key.chars().next().unwrap();
31632            assert!(
31633                first.is_ascii_lowercase(),
31634                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
31635                 (got {key:?}, leads with {first:?})",
31636            );
31637            assert!(
31638                key.chars().all(|c| c.is_ascii_alphanumeric()),
31639                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
31640                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31641            );
31642        }
31643    }
31644
31645    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
31646
31647    #[test]
31648    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
31649        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
31650        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
31651        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
31652        // keys the `#[serde(rename_all = "camelCase")]` attribute on
31653        // [`WitContract`] emits for the required-triad. The three
31654        // sibling payload-arm keys already pin under
31655        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
31656        // `STORE_FIELD_NAME` — pin all six alongside so a future
31657        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31658        // verbatim-field-name flip at the derive attribute (any of which
31659        // would silently break every downstream JSON consumer that
31660        // reaches for one of the six via `Value::get(...)`) surfaces
31661        // here as a build-time test failure at `aplicacao.rs`, not as an
31662        // apply-time `.get(<stale-canonical-const>)` returning `None`
31663        // far from the derive-attr drift's commit. Peer with the sibling
31664        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31665        // pin on the M3 `:membros` per-entry axis — same discipline the
31666        // `Membro` per-entry lift established, extended here to the
31667        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
31668        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
31669        // axis on the Aplicacao surface without a lifted serde-key peer.
31670        let c = WitContract {
31671            de: "cart".into(),
31672            para: "catalog".into(),
31673            wit: "wasi:http/proxy".into(),
31674            endpoint: Some("/lookup".into()),
31675            subject: None,
31676            slot: None,
31677        };
31678        let json = serde_json::to_string(&c).unwrap();
31679        for key in [
31680            crate::CONTRATO_KEY_DE,
31681            crate::CONTRATO_KEY_PARA,
31682            crate::CONTRATO_KEY_WIT,
31683            WitTarget::HTTP_FIELD_NAME,
31684        ] {
31685            let quoted = format!("\"{key}\"");
31686            assert!(
31687                json.contains(&quoted),
31688                "serialized WitContract must carry the lifted \
31689                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
31690                 {quoted} verbatim in the JSON emission (got: {json})",
31691            );
31692        }
31693
31694        // Pin the two remaining payload-arm keys by round-tripping a
31695        // `WitContract` under each payload-shape (pub-sub, store) — the
31696        // required-triad appears on every emission but the payload arms
31697        // only surface when their `Option<String>` field is `Some`.
31698        let pubsub = WitContract {
31699            de: "cart".into(),
31700            para: "events".into(),
31701            wit: "nats:pub-sub".into(),
31702            endpoint: None,
31703            subject: Some("orders.placed".into()),
31704            slot: None,
31705        };
31706        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
31707        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
31708        assert!(
31709            pubsub_json.contains(&pubsub_quoted),
31710            "serialized pub-sub WitContract must carry the lifted \
31711             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
31712             verbatim in the JSON emission (got: {pubsub_json})",
31713        );
31714        let store = WitContract {
31715            de: "cart".into(),
31716            para: "sessions".into(),
31717            wit: "wasi:keyvalue/store".into(),
31718            endpoint: None,
31719            subject: None,
31720            slot: Some("cart/$id".into()),
31721        };
31722        let store_json = serde_json::to_string(&store).unwrap();
31723        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
31724        assert!(
31725            store_json.contains(&store_quoted),
31726            "serialized store WitContract must carry the lifted \
31727             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
31728             verbatim in the JSON emission (got: {store_json})",
31729        );
31730    }
31731
31732    #[test]
31733    fn contrato_key_consts_are_pairwise_distinct() {
31734        // Cross-axis drift-detection pin: a future collapse of the six
31735        // canonical [`WitContract`] per-entry byte-strings onto the same
31736        // value (e.g. an accidental copy-paste flip of
31737        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
31738        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
31739        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
31740        // every downstream probe on one axis onto the sibling axis's
31741        // overlay entry and pass every propagation-probe test that
31742        // expected only the stale axis's value. Peer of the sibling
31743        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
31744        // widened here to the six-way axis the `WitContract`
31745        // required-triad + `WitTarget` payload-triad jointly cover.
31746        let all = [
31747            crate::CONTRATO_KEY_DE,
31748            crate::CONTRATO_KEY_PARA,
31749            crate::CONTRATO_KEY_WIT,
31750            WitTarget::HTTP_FIELD_NAME,
31751            WitTarget::PUBSUB_FIELD_NAME,
31752            WitTarget::STORE_FIELD_NAME,
31753        ];
31754        for (i, a) in all.iter().enumerate() {
31755            for b in all.iter().skip(i + 1) {
31756                assert_ne!(
31757                    a, b,
31758                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
31759                     must be pairwise-distinct canonical byte-sequences \
31760                     — got `{a}` == `{b}`",
31761                );
31762            }
31763        }
31764    }
31765
31766    #[test]
31767    fn contrato_key_consts_are_lower_camel_case_shape() {
31768        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
31769        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
31770        // byte-sequence (no `snake_case` underscores, no `kebab-case`
31771        // hyphens, no leading colon, no `PascalCase` leading capital, no
31772        // whitespace / dots) — the canonical shape the
31773        // `#[serde(rename_all = "camelCase")]` derive produces on
31774        // [`WitContract`]. A future flip to a non-camelCase attribute at
31775        // the derive surfaces both here (this test fails on the
31776        // stale-constant shape) and at
31777        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31778        // (that test fails on the mismatch between const and derive).
31779        // Peer with `membro_key_consts_are_lower_camel_case_shape`
31780        // (ce80ca0) on the sibling `Membro` per-entry axis.
31781        for key in [
31782            crate::CONTRATO_KEY_DE,
31783            crate::CONTRATO_KEY_PARA,
31784            crate::CONTRATO_KEY_WIT,
31785            WitTarget::HTTP_FIELD_NAME,
31786            WitTarget::PUBSUB_FIELD_NAME,
31787            WitTarget::STORE_FIELD_NAME,
31788        ] {
31789            assert!(
31790                !key.is_empty(),
31791                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
31792                 non-empty (got {key:?})"
31793            );
31794            let first = key.chars().next().unwrap();
31795            assert!(
31796                first.is_ascii_lowercase(),
31797                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
31798                 with an ASCII-lowercase byte (got {key:?}, leads with \
31799                 {first:?})",
31800            );
31801            assert!(
31802                key.chars().all(|c| c.is_ascii_alphanumeric()),
31803                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
31804                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
31805                 whitespace (got {key:?})",
31806            );
31807        }
31808    }
31809
31810    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
31811
31812    #[test]
31813    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
31814        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
31815        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
31816        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
31817        // name the exact camelCase JSON keys the
31818        // `#[serde(rename_all = "camelCase")]` attribute on
31819        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
31820        // pin that each canonical byte-sequence appears verbatim in the
31821        // JSON — a future accidental `rename_all = "snake_case"` /
31822        // `"kebab-case"` / verbatim-field-name flip at the derive
31823        // attribute (any of which would silently break every downstream
31824        // JSON consumer that reaches for one of the four consts via
31825        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
31826        // emitter's per-Aplicacao hostname/paths/port projection, the
31827        // future `app-operator` reconciler's per-Aplicacao ingress
31828        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
31829        // materializer's admission-time cross-check) surfaces here as
31830        // a build-time test failure at `aplicacao.rs`, not as an
31831        // apply-time `.get(<stale-canonical-const>)` returning `None`
31832        // far from the derive-attr drift's commit. Peer with the
31833        // sibling
31834        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31835        // (ca463a4) and
31836        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
31837        // pins on the M3 collection-slot atom axes — same discipline
31838        // both collection-slot lifts established, extended here to the
31839        // singleton `:entrada` mesh-slot atom axis, the last M3
31840        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
31841        // axis on the Aplicacao surface without a lifted serde-key
31842        // peer.
31843        let e = Entrada {
31844            host: "checkout.quero.cloud".into(),
31845            para: "cart".into(),
31846            paths: vec!["/cart".into()],
31847            port: 8080,
31848        };
31849        let json = serde_json::to_string(&e).unwrap();
31850        for key in [
31851            crate::ENTRADA_KEY_HOST,
31852            crate::ENTRADA_KEY_PARA,
31853            crate::ENTRADA_KEY_PATHS,
31854            crate::ENTRADA_KEY_PORT,
31855        ] {
31856            let quoted = format!("\"{key}\"");
31857            assert!(
31858                json.contains(&quoted),
31859                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
31860                 byte-sequence {quoted} verbatim in the JSON emission \
31861                 (got: {json})",
31862            );
31863        }
31864    }
31865
31866    #[test]
31867    fn entrada_key_consts_are_pairwise_distinct() {
31868        // Cross-axis drift-detection pin: a future collapse of the four
31869        // canonical [`Entrada`] singleton byte-strings onto the same
31870        // value (e.g. an accidental copy-paste flip of
31871        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
31872        // silently reroute every downstream probe on one axis onto the
31873        // sibling axis's overlay entry and pass every propagation-probe
31874        // test that expected only the stale axis's value — the
31875        // Gateway/HTTPRoute emitter would read the hostname string
31876        // where the destination-Servico name was expected (or vice
31877        // versa), the admission-webhook cross-check would compare the
31878        // wrong pair of values, and the resulting Gateway resource
31879        // would either be admitted with garbage or rejected at the
31880        // controller far from the rebrand commit's source. Peer of the
31881        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
31882        // tetrad (40cc4e5), the two-way distinct pin on the
31883        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
31884        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
31885        // triad (ca463a4).
31886        let all = [
31887            crate::ENTRADA_KEY_HOST,
31888            crate::ENTRADA_KEY_PARA,
31889            crate::ENTRADA_KEY_PATHS,
31890            crate::ENTRADA_KEY_PORT,
31891        ];
31892        for (i, a) in all.iter().enumerate() {
31893            for b in all.iter().skip(i + 1) {
31894                assert_ne!(
31895                    a, b,
31896                    "ENTRADA_KEY_* consts must be pairwise-distinct \
31897                     canonical byte-sequences — got `{a}` == `{b}`",
31898                );
31899            }
31900        }
31901    }
31902
31903    #[test]
31904    fn entrada_key_consts_are_lower_camel_case_shape() {
31905        // Shape-pin: every `ENTRADA_KEY_*` const must be a
31906        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
31907        // `kebab-case` hyphens, no leading colon, no `PascalCase`
31908        // leading capital, no whitespace / dots) — the canonical shape
31909        // the `#[serde(rename_all = "camelCase")]` derive produces on
31910        // [`Entrada`]. A future flip to a non-camelCase attribute at
31911        // the derive surfaces both here (this test fails on the
31912        // stale-constant shape) and at
31913        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
31914        // test fails on the mismatch between const and derive). Peer
31915        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
31916        // and `contrato_key_consts_are_lower_camel_case_shape`
31917        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
31918        // entry axes.
31919        for key in [
31920            crate::ENTRADA_KEY_HOST,
31921            crate::ENTRADA_KEY_PARA,
31922            crate::ENTRADA_KEY_PATHS,
31923            crate::ENTRADA_KEY_PORT,
31924        ] {
31925            assert!(
31926                !key.is_empty(),
31927                "ENTRADA_KEY_* must be non-empty (got {key:?})"
31928            );
31929            let first = key.chars().next().unwrap();
31930            assert!(
31931                first.is_ascii_lowercase(),
31932                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
31933                 (got {key:?}, leads with {first:?})",
31934            );
31935            assert!(
31936                key.chars().all(|c| c.is_ascii_alphanumeric()),
31937                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
31938                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
31939            );
31940        }
31941    }
31942
31943    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
31944
31945    #[test]
31946    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
31947        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
31948        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
31949        // [`crate::POLITICAS_KEY_RETRIES`] /
31950        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
31951        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
31952        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
31953        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
31954        // on [`MeshPolicy`] emits. Three of the five axes
31955        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
31956        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
31957        // camelCase transforms — the derive-attribute is load-bearing
31958        // on those, unlike the sibling `Entrada` / `Membro` /
31959        // `WitContract` structs whose fields are all lowercase-single-
31960        // word and where the derive is a no-op on every axis.
31961        // Serialize a fully-populated [`MeshPolicy`] (every axis
31962        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
31963        // on none of the five slots) and pin that each canonical
31964        // byte-sequence appears verbatim in the JSON — a future
31965        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
31966        // verbatim-field-name flip at the derive attribute (any of
31967        // which would silently break every downstream JSON consumer
31968        // that reaches for one of the five consts via
31969        // `Value::get(...)` — the future M4 per-edge `:politicas`
31970        // overlay projection onto Cilium `L7Rules` and Gateway API
31971        // `HTTPRoute` backend timeouts, the future
31972        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
31973        // admission-time mesh-policy cross-check, the future
31974        // `feira lint` per-`:politicas` bound-check gate) surfaces here
31975        // as a build-time test failure at `aplicacao.rs`, not as an
31976        // apply-time `.get(<stale-canonical-const>)` returning `None`
31977        // far from the derive-attr drift's commit. Peer with the
31978        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
31979        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
31980        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
31981        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
31982        // atom axes — same discipline every M3 sibling lift
31983        // established, extended here to the singleton `:politicas`
31984        // mesh-slot atom axis, closing the last M3 typed-struct
31985        // top-level `#[serde(rename_all = "camelCase")]` axis on the
31986        // Aplicacao surface without a lifted serde-key peer.
31987        let p = MeshPolicy {
31988            timeout: Some(Duration::from_secs(30)),
31989            retries: Some(3),
31990            circuit_breaker: Some(CircuitBreaker {
31991                max_failures: 5,
31992                window: Duration::from_secs(60),
31993            }),
31994            mtls_required: Some(true),
31995            rate_limit: Some(RateLimit {
31996                rate: 100,
31997                window: Duration::from_secs(1),
31998            }),
31999        };
32000        let json = serde_json::to_string(&p).unwrap();
32001        for key in [
32002            crate::POLITICAS_KEY_TIMEOUT,
32003            crate::POLITICAS_KEY_RETRIES,
32004            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
32005            crate::POLITICAS_KEY_MTLS_REQUIRED,
32006            crate::POLITICAS_KEY_RATE_LIMIT,
32007        ] {
32008            let quoted = format!("\"{key}\"");
32009            assert!(
32010                json.contains(&quoted),
32011                "serialized MeshPolicy must carry the lifted \
32012                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
32013                 JSON emission (got: {json})",
32014            );
32015        }
32016    }
32017
32018    #[test]
32019    fn politicas_key_consts_are_pairwise_distinct() {
32020        // Cross-axis drift-detection pin: a future collapse of the five
32021        // canonical [`MeshPolicy`] singleton byte-strings onto the same
32022        // value (e.g. an accidental copy-paste flip of
32023        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
32024        // would silently reroute every downstream probe on one axis
32025        // onto the sibling axis's overlay entry and pass every
32026        // propagation-probe test that expected only the stale axis's
32027        // value — the M4 per-edge `:politicas` overlay projection would
32028        // read the retry-count string where the timeout duration was
32029        // expected (or vice versa), the CR materializer's admission
32030        // cross-check would compare the wrong pair of values, and the
32031        // resulting mesh reconciler would either bind the wrong axis
32032        // or reject the resource at reconcile far from the rebrand
32033        // commit's source. Peer of the sibling four-way distinct pin
32034        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
32035        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
32036        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
32037        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
32038        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
32039        let all = [
32040            crate::POLITICAS_KEY_TIMEOUT,
32041            crate::POLITICAS_KEY_RETRIES,
32042            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
32043            crate::POLITICAS_KEY_MTLS_REQUIRED,
32044            crate::POLITICAS_KEY_RATE_LIMIT,
32045        ];
32046        for (i, a) in all.iter().enumerate() {
32047            for b in all.iter().skip(i + 1) {
32048                assert_ne!(
32049                    a, b,
32050                    "POLITICAS_KEY_* consts must be pairwise-distinct \
32051                     canonical byte-sequences — got `{a}` == `{b}`",
32052                );
32053            }
32054        }
32055    }
32056
32057    #[test]
32058    fn politicas_key_consts_are_lower_camel_case_shape() {
32059        // Shape-pin: every `POLITICAS_KEY_*` const must be a
32060        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32061        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32062        // leading capital, no whitespace / dots) — the canonical shape
32063        // the `#[serde(rename_all = "camelCase")]` derive produces on
32064        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
32065        // at the derive surfaces both here (this test fails on the
32066        // stale-constant shape) and at
32067        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
32068        // (that test fails on the mismatch between const and derive).
32069        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
32070        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
32071        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
32072        // (ca463a4) on the sibling M3 typed-struct axes.
32073        for key in [
32074            crate::POLITICAS_KEY_TIMEOUT,
32075            crate::POLITICAS_KEY_RETRIES,
32076            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
32077            crate::POLITICAS_KEY_MTLS_REQUIRED,
32078            crate::POLITICAS_KEY_RATE_LIMIT,
32079        ] {
32080            assert!(
32081                !key.is_empty(),
32082                "POLITICAS_KEY_* must be non-empty (got {key:?})"
32083            );
32084            let first = key.chars().next().unwrap();
32085            assert!(
32086                first.is_ascii_lowercase(),
32087                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
32088                 byte (got {key:?}, leads with {first:?})",
32089            );
32090            assert!(
32091                key.chars().all(|c| c.is_ascii_alphanumeric()),
32092                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
32093                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32094            );
32095        }
32096    }
32097
32098    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
32099
32100    #[test]
32101    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
32102        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
32103        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
32104        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
32105        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
32106        // [`CircuitBreaker`] emits inside the
32107        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
32108        // two axes (`max_failures` → `maxFailures`) is a non-trivial
32109        // camelCase transform — the derive-attribute is load-bearing on
32110        // that axis, unlike the sibling `window` field where the derive
32111        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
32112        // pin that each canonical byte-sequence appears verbatim in the
32113        // JSON — a future accidental `rename_all = "snake_case"` /
32114        // `"kebab-case"` / verbatim-field-name flip at the derive
32115        // attribute (any of which would silently break every downstream
32116        // JSON consumer that reaches for one of the two consts via
32117        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
32118        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
32119        // per-edge `:politicas` overlay projection onto the mesh's
32120        // per-backend consecutive-failure-counter tripping threshold, the
32121        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
32122        // admission-time breaker cross-check, the future `feira lint`
32123        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
32124        // here as a build-time test failure at `aplicacao.rs`, not as an
32125        // apply-time `.get(<stale-canonical-const>)` returning `None`
32126        // far from the derive-attr drift's commit. Peer with the sibling
32127        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
32128        // (b55cca7) parent-axis pin — that test pins the outer
32129        // sub-block key the derive on [`MeshPolicy`] emits, this test
32130        // pins the inner keys the derive on the payload type emits, so
32131        // the two together lock the whole [`MeshPolicy`] breaker-tuning
32132        // shape end-to-end at build time.
32133        let cb = CircuitBreaker {
32134            max_failures: 5,
32135            window: Duration::from_secs(60),
32136        };
32137        let json = serde_json::to_string(&cb).unwrap();
32138        for key in [
32139            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
32140            crate::CIRCUIT_BREAKER_KEY_WINDOW,
32141        ] {
32142            let quoted = format!("\"{key}\"");
32143            assert!(
32144                json.contains(&quoted),
32145                "serialized CircuitBreaker must carry the lifted \
32146                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
32147                 in the JSON emission (got: {json})",
32148            );
32149        }
32150    }
32151
32152    #[test]
32153    fn circuit_breaker_key_consts_are_pairwise_distinct() {
32154        // Cross-axis drift-detection pin: a future collapse of the two
32155        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
32156        // same value (e.g. an accidental copy-paste flip of
32157        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
32158        // `"maxFailures"`) would silently reroute every downstream
32159        // probe on one axis onto the sibling axis's overlay entry and
32160        // pass every propagation-probe test that expected only the
32161        // stale axis's value — the M4 per-edge `:politicas` overlay
32162        // projection would read the failure-count where the window
32163        // duration was expected (or vice versa), the CR materializer's
32164        // admission cross-check would compare the wrong pair of values,
32165        // and the resulting mesh reconciler would either bind the wrong
32166        // axis or reject the resource at reconcile far from the rebrand
32167        // commit's source. Peer of the sibling five-way distinct pin on
32168        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
32169        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
32170        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
32171        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
32172        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
32173        let all = [
32174            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
32175            crate::CIRCUIT_BREAKER_KEY_WINDOW,
32176        ];
32177        for (i, a) in all.iter().enumerate() {
32178            for b in all.iter().skip(i + 1) {
32179                assert_ne!(
32180                    a, b,
32181                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
32182                     canonical byte-sequences — got `{a}` == `{b}`",
32183                );
32184            }
32185        }
32186    }
32187
32188    #[test]
32189    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
32190        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
32191        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32192        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32193        // leading capital, no whitespace / dots) — the canonical shape
32194        // the `#[serde(rename_all = "camelCase")]` derive produces on
32195        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
32196        // at the derive surfaces both here (this test fails on the
32197        // stale-constant shape) and at
32198        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
32199        // (that test fails on the mismatch between const and derive).
32200        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
32201        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
32202        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
32203        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
32204        // (ca463a4) on the sibling M3 typed-struct axes.
32205        for key in [
32206            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
32207            crate::CIRCUIT_BREAKER_KEY_WINDOW,
32208        ] {
32209            assert!(
32210                !key.is_empty(),
32211                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
32212            );
32213            let first = key.chars().next().unwrap();
32214            assert!(
32215                first.is_ascii_lowercase(),
32216                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
32217                 byte (got {key:?}, leads with {first:?})",
32218            );
32219            assert!(
32220                key.chars().all(|c| c.is_ascii_alphanumeric()),
32221                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
32222                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32223            );
32224        }
32225    }
32226
32227    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
32228
32229    #[test]
32230    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
32231        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
32232        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
32233        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
32234        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
32235        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
32236        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
32237        // [`Placement`] emits. One of the four axes (`shard_key` →
32238        // `shardKey`) is a non-trivial camelCase transform — the
32239        // derive-attribute is load-bearing on that axis, unlike the
32240        // sibling `estrategia` / `clusters` / `affinity` axes whose
32241        // source-side field names carry no `_` and where the derive is a
32242        // no-op. Serialize a fully-populated [`Placement`] (both
32243        // `Option`-carrying axes `Some(_)` so
32244        // `skip_serializing_if = "Option::is_none"` fires on neither of
32245        // the two optional slots) and pin that each canonical
32246        // byte-sequence appears verbatim in the JSON — a future
32247        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
32248        // verbatim-field-name flip at the derive attribute (any of which
32249        // would silently break every downstream consumer that reaches
32250        // for one of the four consts via
32251        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
32252        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
32253        // aggregator's per-cluster fanout filter keying off
32254        // `placement.clusters`, the M3 shard-pool dispatch materializer
32255        // keying off `placement.shardKey`, the M3 Adaptive compression
32256        // pass weighting off `placement.affinity`, every downstream
32257        // dispatcher branching on `placement.estrategia`, the future
32258        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
32259        // admission-time placement cross-check, the future `feira lint`
32260        // per-`:placement` bound-check gate) surfaces here as a
32261        // build-time test failure at `aplicacao.rs`, not as an
32262        // apply-time `.get(<stale-canonical-const>)` returning `None`
32263        // far from the derive-attr drift's commit. Peer with the sibling
32264        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
32265        // (b55cca7),
32266        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
32267        // (468e959),
32268        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
32269        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
32270        // (ca463a4), and
32271        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
32272        // pins on the M3 collection-slot / singleton-slot atom axes —
32273        // closes the last M3 typed-struct top-level
32274        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
32275        // surface without a drift-detection pin.
32276        let p = Placement {
32277            estrategia: PlacementStrategy::Sharded,
32278            clusters: vec!["rio".into(), "mar".into()],
32279            affinity: Some("data-locality".into()),
32280            shard_key: Some("$tenantId".into()),
32281        };
32282        let json = serde_json::to_string(&p).unwrap();
32283        for key in [
32284            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32285            crate::M3_PLACEMENT_KEY_CLUSTERS,
32286            crate::M3_PLACEMENT_KEY_AFFINITY,
32287            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32288        ] {
32289            let quoted = format!("\"{key}\"");
32290            assert!(
32291                json.contains(&quoted),
32292                "serialized Placement must carry the lifted \
32293                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
32294                 the JSON emission (got: {json})",
32295            );
32296        }
32297    }
32298
32299    #[test]
32300    fn m3_placement_key_consts_are_pairwise_distinct() {
32301        // Cross-axis drift-detection pin: a future collapse of the four
32302        // canonical [`Placement`] sub-block byte-strings onto the same
32303        // value (e.g. an accidental copy-paste flip of
32304        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
32305        // `"affinity"`) would silently reroute every downstream probe on
32306        // one axis onto the sibling axis's overlay entry and pass every
32307        // propagation-probe test that expected only the stale axis's
32308        // value — the M3 shard-pool dispatch materializer would read the
32309        // affinity placement-hint where the shard-selection template was
32310        // expected (or vice versa), the M3 Adaptive compression pass's
32311        // cross-check would compare the wrong pair of values, and the
32312        // resulting placement engine would either bind the wrong axis or
32313        // reject the resource at reconcile far from the rebrand commit's
32314        // source. Peer of the sibling two-way distinct pin on the
32315        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
32316        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
32317        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
32318        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
32319        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
32320        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
32321        let all = [
32322            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32323            crate::M3_PLACEMENT_KEY_CLUSTERS,
32324            crate::M3_PLACEMENT_KEY_AFFINITY,
32325            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32326        ];
32327        for (i, a) in all.iter().enumerate() {
32328            for b in all.iter().skip(i + 1) {
32329                assert_ne!(
32330                    a, b,
32331                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
32332                     canonical byte-sequences — got `{a}` == `{b}`",
32333                );
32334            }
32335        }
32336    }
32337
32338    #[test]
32339    fn m3_placement_key_consts_are_lower_camel_case_shape() {
32340        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
32341        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32342        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32343        // leading capital, no whitespace / dots) — the canonical shape
32344        // the `#[serde(rename_all = "camelCase")]` derive produces on
32345        // [`Placement`]. A future flip to a non-camelCase attribute at
32346        // the derive surfaces both here (this test fails on the stale-
32347        // constant shape) and at
32348        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
32349        // (that test fails on the mismatch between const and derive).
32350        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
32351        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
32352        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
32353        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
32354        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
32355        // (ca463a4) on the sibling M3 typed-struct axes.
32356        for key in [
32357            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
32358            crate::M3_PLACEMENT_KEY_CLUSTERS,
32359            crate::M3_PLACEMENT_KEY_AFFINITY,
32360            crate::M3_PLACEMENT_KEY_SHARD_KEY,
32361        ] {
32362            assert!(
32363                !key.is_empty(),
32364                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
32365            );
32366            let first = key.chars().next().unwrap();
32367            assert!(
32368                first.is_ascii_lowercase(),
32369                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
32370                 byte (got {key:?}, leads with {first:?})",
32371            );
32372            assert!(
32373                key.chars().all(|c| c.is_ascii_alphanumeric()),
32374                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
32375                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32376            );
32377        }
32378    }
32379
32380    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
32381    //    destination-facing L4 port resolver every per-Aplicacao renderer
32382    //    reaching for a per-destination Servico TCP port axis routes
32383    //    through. The four pin tests below fix the four-way accept-set
32384    //    the resolver must always honor: (:entrada-para-matches,
32385    //    :entrada-para-mismatches, :entrada-none-so-fallback,
32386    //    :entrada-port-non-default-honored) — drift on any arm surfaces
32387    //    at caixa-core build time rather than at cluster-apply time.
32388
32389    #[test]
32390    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
32391        // The typed `:entrada` block's `:para "cart"` matches the
32392        // queried destination, so the resolver returns the author-
32393        // declared `:port` scalar verbatim — the canonical "the
32394        // destination Servico IS the ingress apex, honor the typed
32395        // listener port" arm of the port-resolution dispatch.
32396        let mut spec = three_member_spec();
32397        if let Some(e) = spec.entrada.as_mut() {
32398            e.para = "cart".into();
32399            e.port = 9090;
32400        }
32401        assert_eq!(
32402            spec.port_for_destination("cart"),
32403            9090,
32404            "port_for_destination(entrada.para) must return entrada.port \
32405             verbatim, not the DEFAULT_SERVICO_PORT fallback"
32406        );
32407    }
32408
32409    #[test]
32410    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
32411        // The typed `:entrada` block names `:para "cart"`, but the
32412        // queried destination is `"payment"` — a Servico that
32413        // participates in the mesh graph but is not the ingress apex.
32414        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
32415        // canonical port floor, closing the "non-apex destination reads
32416        // the substrate default" arm. Same fixture the peer
32417        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
32418        // pin at caixa-mesh exercises through the CNP emit-side path;
32419        // this pin exercises the shared underlying resolver directly.
32420        let spec = three_member_spec();
32421        assert_eq!(
32422            spec.port_for_destination("payment"),
32423            DEFAULT_SERVICO_PORT,
32424            "port_for_destination(non-apex-destination) must route \
32425             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
32426        );
32427    }
32428
32429    #[test]
32430    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
32431        // Internal-only Aplicacao — no `:entrada` block declared. Every
32432        // per-destination port query falls back to the lifted
32433        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
32434        // the Aplicacao surface admits `:entrada None` (internal mesh
32435        // with no external gateway); every downstream renderer's per-
32436        // destination port axis must still resolve to a well-defined
32437        // scalar even without an ingress apex.
32438        let mut spec = three_member_spec();
32439        spec.entrada = None;
32440        assert_eq!(
32441            spec.port_for_destination("cart"),
32442            DEFAULT_SERVICO_PORT,
32443            "port_for_destination on an internal-only Aplicacao must \
32444             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
32445             every destination"
32446        );
32447        assert_eq!(
32448            spec.port_for_destination("payment"),
32449            DEFAULT_SERVICO_PORT,
32450            "port_for_destination on an internal-only Aplicacao must \
32451             fall back uniformly across every destination — the fallback \
32452             is not entrada-shape-conditional"
32453        );
32454    }
32455
32456    #[test]
32457    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
32458        // Structural pin against a hypothetical future refactor that
32459        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
32460        // the resolver (a "normalize to the default when the author's
32461        // port matches the substrate default" collapse) — that would
32462        // break renderer sites that carry meaning on the emitted port
32463        // value beyond bare equality (a future per-cluster listener-
32464        // audit that keys off the author-declared port, not the
32465        // resolved-with-fallback port). Pin that a non-default
32466        // entrada.port is returned verbatim so drift here surfaces at
32467        // caixa-core build time.
32468        let mut spec = three_member_spec();
32469        if let Some(e) = spec.entrada.as_mut() {
32470            e.para = "cart".into();
32471            e.port = 8443;
32472        }
32473        assert_ne!(
32474            8443, DEFAULT_SERVICO_PORT,
32475            "test fixture must probe a port distinct from \
32476             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
32477        );
32478        assert_eq!(
32479            spec.port_for_destination("cart"),
32480            8443,
32481            "port_for_destination(entrada.para) must return entrada.port \
32482             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
32483        );
32484    }
32485
32486    #[test]
32487    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
32488        // Apex-identity pair-invariant pin composing both substrate-
32489        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
32490        // and [`Entrada::destination`] — at the emit-side call shape
32491        // every per-Aplicacao renderer's ingress-apex L4 port reader
32492        // now takes. The invariant:
32493        //
32494        //   spec.port_for_destination(entrada.destination()) == entrada.port
32495        //
32496        // holds by construction under today's single-destination
32497        // `:entrada` slot (`destination()` returns `entrada.para`, and
32498        // the resolver's apex arm matches `para == destination` and
32499        // returns `entrada.port`), and every downstream consumer that
32500        // composes the two accessors at the ingress apex — the
32501        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
32502        // `backendRefs[0].port` emit-site path, the peer future M4 CR
32503        // materializer's admission-webhook that promotes the scalar to
32504        // a per-CR override overlay, every future per-Aplicacao snapshot
32505        // renderer's apex-facing L4 port reader — reaches through the
32506        // same composition. Pin the identity across four permutations
32507        // (`:para` × `:port` including a non-default port to exercise
32508        // the honor-verbatim arm and a non-cart `:para` to exercise
32509        // destination-agnostic identity) so a future refactor that
32510        // silently split either accessor's apex behavior surfaces at
32511        // caixa-core build time — a subtle `destination()` renaming
32512        // that returned `entrada.host.as_str()` instead of
32513        // `entrada.para.as_str()` would blow this pin loudly, closing
32514        // the last quiet failure mode the two lifts admit in composition.
32515        //
32516        // Peer discipline with the sibling caixa-mesh cross-crate pin
32517        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
32518        // on the two-renderer pair-invariant axis; this pin encodes the
32519        // same two-consumer coherence rule at the substrate-primitive
32520        // level so the invariant survives even if every renderer is
32521        // deleted.
32522        for (para, port) in [
32523            ("cart", DEFAULT_SERVICO_PORT),
32524            ("cart", 8443u16),
32525            ("payment", 9090u16),
32526            ("catalog", 443u16),
32527        ] {
32528            let mut spec = three_member_spec();
32529            if let Some(e) = spec.entrada.as_mut() {
32530                e.para = para.into();
32531                e.port = port;
32532            }
32533            let expected_port = spec
32534                .entrada()
32535                .expect("three_member_spec carries a typed `:entrada` block")
32536                .port();
32537            let composed_port = {
32538                let entrada = spec.entrada().expect("entrada present");
32539                spec.port_for_destination(entrada.destination())
32540            };
32541            assert_eq!(
32542                composed_port, expected_port,
32543                "`spec.port_for_destination(entrada.destination())` must \
32544                 equal `entrada.port` under today's single-destination \
32545                 `:entrada` slot — this is the apex-identity contract \
32546                 every downstream ingress-apex L4 port reader relies on. \
32547                 Input :entrada :para: {para:?}, :entrada :port: {port}"
32548            );
32549        }
32550    }
32551
32552    #[test]
32553    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
32554        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
32555        // per-`:entrada` apex-arm membership probe must key off
32556        // [`Entrada::destination`], not the raw `.para` field access.
32557        // Structurally: setting ONLY the `:entrada :para` field to a
32558        // fresh non-cart destination on an otherwise-well-formed
32559        // Aplicacao must (1) leave `e.destination()` byte-equal to
32560        // `e.para.as_str()` (the accessor is byte-projective by
32561        // definition), and (2) cause the resolver's apex arm to fire
32562        // and return `entrada.port` at exactly that new destination
32563        // while every other destination string falls through to
32564        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
32565        // membership check. Pins against a future silent detour that
32566        // (a) re-derived the apex-arm membership probe off
32567        // `e.para == destination` in `port_for_destination` instead of
32568        // `e.destination() == destination`, silently disagreeing with
32569        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
32570        // consumers (`entrada.destination()` at
32571        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
32572        // caixa-mesh/src/lib.rs:2739) that already reach through the
32573        // accessor, (b) accessor-side introduced a per-tenant alias
32574        // arm the caller was unaware of, silently rewriting an
32575        // author-declared `:para "cart"` value to a canary-aliased
32576        // form — the raw-field-access resolver would fall through to
32577        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
32578        // while the peer emit-site consumers landed on the aliased
32579        // destination, splitting the ingress-apex L4 port at
32580        // cluster-apply time.
32581        //
32582        // Peer of the sibling
32583        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
32584        // (d0de220) composition pin on the per-`:membros` refusal-arm
32585        // axis — same "the shape-gate predicate must route through the
32586        // substrate-primitive typed dispatch" discipline extended onto
32587        // the per-`:entrada` apex-arm membership-probe axis. Closes
32588        // the last unlifted `.para` production-code read site on
32589        // `Entrada` in `caixa-core` — after this converge every
32590        // `caixa-core` `.para` field access outside the accessor's own
32591        // body and outside the `WitContract` per-`:contratos` sibling
32592        // axis is either a test-side field-setter or a doc-comment
32593        // reference.
32594        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
32595            let mut spec = three_member_spec();
32596            if let Some(e) = spec.entrada.as_mut() {
32597                e.para = para.into();
32598                e.port = port;
32599            }
32600            let e = spec
32601                .entrada
32602                .as_ref()
32603                .expect("three_member_spec carries a typed `:entrada` block");
32604            assert_eq!(
32605                e.destination(),
32606                e.para.as_str(),
32607                "Entrada::destination must byte-equal the .para field \
32608                 access — an accessor-side detour that no longer \
32609                 projects the raw field would silently split this \
32610                 drift-detection test from the port_for_destination \
32611                 apex-arm membership probe",
32612            );
32613            assert_eq!(
32614                spec.port_for_destination(para),
32615                port,
32616                "port_for_destination must key off the accessor-projected \
32617                 destination and return `entrada.port` on the apex arm — \
32618                 input :entrada :para: {para:?}, :entrada :port: {port}",
32619            );
32620            assert_eq!(
32621                spec.port_for_destination("ghost-destination-never-a-member"),
32622                DEFAULT_SERVICO_PORT,
32623                "port_for_destination must fall through to \
32624                 DEFAULT_SERVICO_PORT on a non-matching destination \
32625                 under the accessor-projected membership check — input \
32626                 :entrada :para: {para:?}, :entrada :port: {port}",
32627            );
32628        }
32629    }
32630
32631    #[test]
32632    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
32633        // The canonical per-`:politicas :rate-limit` `:rate`
32634        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
32635        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
32636        // typed `u32` verbatim, byte-equal to the raw field access
32637        // across every representative value in the accept-set — `1` (the
32638        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
32639        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
32640        // carves out on the sibling `PolicyRateLimitZero` refusal),
32641        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
32642        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
32643        // `0` (a past-the-guard sentinel that pins the accessor doesn't
32644        // perform a silent bounds-collapse into `1` on the zero arm —
32645        // validate rejects zero but the accessor must ship the raw slot
32646        // verbatim so a validate-time gate regression surfaces at the
32647        // emit boundary rather than being silently absorbed), `u32::MAX`
32648        // (a past-the-guard sentinel that pins the accessor doesn't
32649        // perform a silent bounds-collapse through
32650        // `POLICY_RATE_LIMIT_MAX` at the return path).
32651        //
32652        // First sub-struct required-scalar accessor pin on the
32653        // `RateLimit` axis — sibling in shape to the peer
32654        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
32655        // required-`u32` accessor pin on the peer per-sub-struct
32656        // required-axis. Pins against a future silent detour that
32657        // re-derived the token capacity from a peer axis (an accidental
32658        // `self.window.as_secs() as u32` collapse that read the
32659        // rate-limit window duration as a token count), a `0 → 1`
32660        // cluster-default projection (which would silently absorb the
32661        // `PolicyRateLimitZero` refusal case at the accessor boundary),
32662        // or a bounds-collapsing accessor that clamped the return
32663        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
32664        // gate owns the bounds; the accessor must ship the raw slot
32665        // verbatim).
32666        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
32667            let rl = RateLimit {
32668                rate,
32669                window: Duration::from_secs(1),
32670            };
32671            assert_eq!(
32672                rl.rate(),
32673                rate,
32674                "RateLimit::rate must return :politicas :rate-limit :rate \
32675                 verbatim (got {}, expected {rate})",
32676                rl.rate(),
32677            );
32678            assert_eq!(
32679                rl.rate(),
32680                rl.rate,
32681                "RateLimit::rate must byte-equal the raw .rate field \
32682                 access across every value in the u32 accept-set",
32683            );
32684        }
32685    }
32686
32687    #[test]
32688    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
32689        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32690        // `:rate-limit :rate` zero-floor arm must key off
32691        // [`RateLimit::rate`], not the raw `.rate` field access.
32692        // Structurally: a `RateLimit { rate: 0, window:
32693        // Duration::from_secs(1) }` embedded in a `:politicas
32694        // :rate-limit` slot must surface the `PolicyRateLimitZero`
32695        // refusal exactly, and a `RateLimit { rate: 1, window:
32696        // Duration::from_secs(1) }` (the lower boundary of the
32697        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
32698        // The pair jointly pins the accessor + validate-gate composition:
32699        // any future silent detour that had the accessor return a fresh
32700        // `1` on the zero arm (a `.rate().max(1)` collapse) would
32701        // silently absorb the `PolicyRateLimitZero` refusal at the
32702        // accessor boundary and the validate gate would accept a
32703        // struct-literal `RateLimit { rate: 0, .. }` — the composition
32704        // pin catches that at caixa-core build time.
32705        //
32706        // Peer of the sibling per-`CircuitBreaker`
32707        // [`CircuitBreaker::max_failures`] (3a74062) /
32708        // [`CircuitBreaker::window`] (373957f) accessor-composition
32709        // pins on the peer required-scalar axes — same "the validate /
32710        // shape-gate predicate must route through the substrate-primitive
32711        // typed dispatch" discipline extended onto the peer
32712        // per-`RateLimit` required-`u32` composition axis.
32713        let mut spec = three_member_spec();
32714        spec.politicas = MeshPolicy {
32715            rate_limit: Some(RateLimit {
32716                rate: 0,
32717                window: Duration::from_secs(1),
32718            }),
32719            ..MeshPolicy::default()
32720        };
32721        assert!(
32722            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
32723            "validate_politicas must reject rate == 0 with \
32724             PolicyRateLimitZero — the accessor and the validate gate \
32725             must route through the same substrate-primitive typed \
32726             dispatch on the :rate zero-floor arm",
32727        );
32728        spec.politicas = MeshPolicy {
32729            rate_limit: Some(RateLimit {
32730                rate: 1,
32731                window: Duration::from_secs(1),
32732            }),
32733            ..MeshPolicy::default()
32734        };
32735        assert!(
32736            spec.validate().is_ok(),
32737            "validate_politicas must accept rate == 1 (the lower \
32738             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
32739        );
32740    }
32741
32742    #[test]
32743    fn rate_limit_rate_projects_u32_by_copy() {
32744        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
32745        // `u32` is `Copy` and the accessor must return by value, not by
32746        // reference. Peer of the sibling per-`CircuitBreaker`
32747        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
32748        // peer required-scalar `:max-failures` axis, extended onto the
32749        // peer per-`RateLimit` required-`u32` copy-invariant shape —
32750        // the accessor's returned `u32` must outlive `&self` (multiple
32751        // calls must return equal values from a dropped-`&self` copy,
32752        // since the returned scalar carries no borrow), and calling the
32753        // accessor twice on the same RateLimit must yield the same
32754        // `u32` verbatim (idempotent, no side effects on `&self`).
32755        //
32756        // Pins against a future silent detour that returned `&u32`
32757        // (which would type-check but silently break every downstream
32758        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
32759        // first parameter is `u32`, and `&u32` would fold to a detached
32760        // copy at the call site with a `*` deref the sibling accessors
32761        // don't need), an accidental `.rate.wrapping_add(0)` detour that
32762        // returned a fresh copy through an arithmetic no-op (breaking a
32763        // future `const fn` regression), or a one-arm-only accessor
32764        // that returned a saturating value on some sentinel input
32765        // (breaking the pass-through invariant the sibling required-
32766        // scalar accessors carry).
32767        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
32768            let rl = RateLimit {
32769                rate,
32770                window: Duration::from_secs(1),
32771            };
32772            let first = rl.rate();
32773            let second = rl.rate();
32774            assert_eq!(
32775                first, second,
32776                "RateLimit::rate must be idempotent — two successive \
32777                 calls on the same &self must return the same u32",
32778            );
32779            assert_eq!(
32780                first, rate,
32781                "RateLimit::rate must return :politicas :rate-limit :rate \
32782                 verbatim by copy — got {first}, expected {rate}",
32783            );
32784        }
32785    }
32786
32787    #[test]
32788    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
32789        // The canonical per-`:politicas :rate-limit` `:window`
32790        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
32791        // pin: [`RateLimit::window`] must return the
32792        // `:politicas :rate-limit :window` typed `Duration` verbatim,
32793        // byte-equal to the raw field access across every
32794        // representative value in the accept-set — `Duration::from_secs(1)`
32795        // (the `"s"` canonical window, the lower row of
32796        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
32797        // [`AplicacaoSpec::validate_politicas`] gate accepts via
32798        // [`is_canonical_rate_limit_window`]),
32799        // `Duration::from_secs(60)` (the `"m"` canonical window, the
32800        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
32801        // window, the upper row), `Duration::ZERO` (a past-the-guard
32802        // sentinel that pins the accessor doesn't perform a silent
32803        // bounds-collapse into `Duration::from_secs(1)` on the zero
32804        // arm — validate rejects an off-set window through
32805        // `PolicyRateLimitWindowNotCanonical` but the accessor must
32806        // ship the raw slot verbatim so a validate-time gate
32807        // regression surfaces at the emit boundary rather than being
32808        // silently absorbed), `Duration::from_millis(500)` (a
32809        // sub-canonical past-the-guard sentinel that pins the accessor
32810        // doesn't silently normalize a non-canonical fractional
32811        // magnitude onto the nearest canonical row).
32812        //
32813        // Second sub-struct required-scalar accessor pin on the
32814        // `RateLimit` axis — sibling in shape to the just-landed
32815        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
32816        // accessor pin on the peer per-sub-struct required-axis,
32817        // extended onto the per-`RateLimit` required-`Duration` axis.
32818        // Pins against a future silent detour that re-derived the
32819        // refill period from a peer axis (an accidental
32820        // `Duration::from_secs(self.rate as u64)` collapse that read
32821        // the rate-limit token capacity as a refill-interval
32822        // duration), a `Duration::ZERO → Duration::from_secs(1)`
32823        // canonical-default projection (which would silently absorb
32824        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
32825        // accessor boundary), or a canonical-set-collapsing accessor
32826        // that clamped the return through [`rate_limit_window_unit`]
32827        // (the `AplicacaoSpec::validate` gate owns the canonical-set
32828        // membership; the accessor must ship the raw slot verbatim).
32829        for window in [
32830            Duration::from_secs(1),
32831            Duration::from_secs(60),
32832            Duration::from_secs(3600),
32833            Duration::ZERO,
32834            Duration::from_millis(500),
32835        ] {
32836            let rl = RateLimit { rate: 100, window };
32837            assert_eq!(
32838                rl.window(),
32839                window,
32840                "RateLimit::window must return :politicas :rate-limit :window \
32841                 verbatim (got {:?}, expected {window:?})",
32842                rl.window(),
32843            );
32844            assert_eq!(
32845                rl.window(),
32846                rl.window,
32847                "RateLimit::window must byte-equal the raw .window field \
32848                 access across every value in the Duration accept-set",
32849            );
32850        }
32851    }
32852
32853    #[test]
32854    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
32855        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32856        // `:rate-limit :window` canonical-set arm must key off
32857        // [`RateLimit::window`], not the raw `.window` field access.
32858        // Structurally: a `RateLimit { window: Duration::from_millis(500),
32859        // .. }` embedded in a `:politicas :rate-limit` slot must
32860        // surface the `PolicyRateLimitWindowNotCanonical` refusal
32861        // exactly (with the sub-canonical `Duration::from_millis(500)`
32862        // magnitude carried through verbatim), and a `RateLimit
32863        // { window: Duration::from_secs(1), .. }` (the lower row of
32864        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
32865        // The pair jointly pins the accessor + validate-gate
32866        // composition: any future silent detour that had the accessor
32867        // normalize the off-set window to the nearest canonical row
32868        // (a `.window().max(Duration::from_secs(1))` collapse, or a
32869        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
32870        // collapse) would silently absorb the
32871        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
32872        // boundary — including a drift in the error's `window` payload
32873        // (the emit-side diagnostic reader keys off the offending
32874        // magnitude verbatim, so a normalization at the accessor
32875        // boundary would silently pin the wrong magnitude in the
32876        // refusal). The composition pin catches that at caixa-core
32877        // build time.
32878        //
32879        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
32880        // (7f81a60) accessor-composition pin on the peer required-
32881        // scalar `:rate` axis — same "the validate / shape-gate
32882        // predicate must route through the substrate-primitive typed
32883        // dispatch, and the error payload must project through the
32884        // same accessor" discipline extended onto the peer
32885        // per-`RateLimit` required-`Duration` composition axis.
32886        let mut spec = three_member_spec();
32887        spec.politicas = MeshPolicy {
32888            rate_limit: Some(RateLimit {
32889                rate: 100,
32890                window: Duration::from_millis(500),
32891            }),
32892            ..MeshPolicy::default()
32893        };
32894        match spec.validate() {
32895            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
32896                assert_eq!(
32897                    window,
32898                    Duration::from_millis(500),
32899                    "PolicyRateLimitWindowNotCanonical must carry the \
32900                     offending :window magnitude verbatim through the \
32901                     accessor — got {window:?}, expected 500ms",
32902                );
32903            }
32904            other => panic!(
32905                "validate_politicas must reject non-canonical :window \
32906                 with PolicyRateLimitWindowNotCanonical — the accessor \
32907                 and the validate gate must route through the same \
32908                 substrate-primitive typed dispatch on the :window \
32909                 canonical-set arm; got {other:?}",
32910            ),
32911        }
32912        spec.politicas = MeshPolicy {
32913            rate_limit: Some(RateLimit {
32914                rate: 100,
32915                window: Duration::from_secs(1),
32916            }),
32917            ..MeshPolicy::default()
32918        };
32919        assert!(
32920            spec.validate().is_ok(),
32921            "validate_politicas must accept window == Duration::from_secs(1) \
32922             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
32923        );
32924    }
32925
32926    #[test]
32927    fn rate_limit_window_projects_duration_by_copy() {
32928        // The by-copy pin: [`RateLimit::window`] returns `Duration`
32929        // by copy — `Duration` is `Copy` and the accessor must return
32930        // by value, not by reference. Peer of the sibling per-`RateLimit`
32931        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
32932        // required-scalar `:rate` axis, extended onto the peer
32933        // per-`RateLimit` required-`Duration` copy-invariant shape —
32934        // the accessor's returned `Duration` must outlive `&self`
32935        // (multiple calls must return equal values from a
32936        // dropped-`&self` copy, since the returned scalar carries no
32937        // borrow), and calling the accessor twice on the same
32938        // RateLimit must yield the same `Duration` verbatim
32939        // (idempotent, no side effects on `&self`).
32940        //
32941        // Pins against a future silent detour that returned
32942        // `&Duration` (which would type-check but silently break every
32943        // downstream `Duration`-by-value consumer —
32944        // [`is_canonical_rate_limit_window`]'s first parameter is
32945        // `Duration`, and `&Duration` would fold to a detached copy at
32946        // the call site with a `*` deref the sibling accessors don't
32947        // need), an accidental `.window + Duration::ZERO` detour that
32948        // returned a fresh copy through an arithmetic no-op (breaking
32949        // a future `const fn` regression), or a one-arm-only accessor
32950        // that returned a canonical fallback on some sentinel input
32951        // (breaking the pass-through invariant the sibling required-
32952        // scalar accessors carry).
32953        for window in [
32954            Duration::from_secs(1),
32955            Duration::from_secs(60),
32956            Duration::from_secs(3600),
32957            Duration::ZERO,
32958            Duration::from_millis(500),
32959        ] {
32960            let rl = RateLimit { rate: 100, window };
32961            let first = rl.window();
32962            let second = rl.window();
32963            assert_eq!(
32964                first, second,
32965                "RateLimit::window must be idempotent — two successive \
32966                 calls on the same &self must return the same Duration",
32967            );
32968            assert_eq!(
32969                first, window,
32970                "RateLimit::window must return :politicas :rate-limit :window \
32971                 verbatim by copy — got {first:?}, expected {window:?}",
32972            );
32973        }
32974    }
32975
32976    #[test]
32977    fn placement_estrategia_default_pins_m3_canonical_value() {
32978        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
32979        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
32980        // active-active-across-every-named-cluster arm, the closest
32981        // canonical M3 production reference the substrate carries and
32982        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
32983        // for every un-`:placement`-declared Aplicacao. Pinning the arm
32984        // here surfaces a future rebrand of the M3-canonical
32985        // distribution default (a widening to `Sharded` once the
32986        // substrate discovers hash-keyed distribution as the more
32987        // common production shape, a tightening to `SingleNode` for
32988        // stateful Erlang/OTP distributed-app-takeover semantics
32989        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
32990        // operator pins through a future `:placement-overrides` slot)
32991        // as a deliberate test edit, not a silent contract migration.
32992        // Peer of the sibling M2 per-supervisor value pins
32993        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
32994        // /
32995        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
32996        // extended onto the M3 mesh-primitive-defining `:placement
32997        // :estrategia` axis.
32998        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
32999    }
33000
33001    #[test]
33002    fn placement_strategy_default_routes_through_lifted_default() {
33003        // Composition pin: the [`Default for PlacementStrategy`] impl's
33004        // return arm must route through the substrate-canonical
33005        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
33006        // a raw `Self::Replicated` arm. Prior to the lift the impl
33007        // carried an inline `Self::Replicated` arm with no compile-time
33008        // link back to the shared M3-canonical `Replicated` arm the
33009        // paired [`Default for Placement`] impl's struct-literal
33010        // `estrategia` field, the serde-side `#[serde(default)]` on
33011        // [`Placement::estrategia`] that resolves an author-omitted
33012        // wire-form `:placement :estrategia` scalar through the impl,
33013        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
33014        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
33015        // routes through [`Placement::default`] which routes through the
33016        // strategy default) all key off — so a future rebrand of the
33017        // M3-canonical distribution default would have had to be threaded
33018        // through the `Default` impl and the three peer routes in
33019        // lockstep or the four consumers would silently split. Byte-
33020        // parity against the lifted constant closes the split. Peer of
33021        // the sibling
33022        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
33023        // /
33024        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
33025        // composition pins on the M2 per-supervisor axes.
33026        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
33027    }
33028
33029    #[test]
33030    fn placement_default_estrategia_routes_through_lifted_default() {
33031        // Composition pin: the [`Default for Placement`] impl's
33032        // struct-literal `estrategia` field must route through the
33033        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
33034        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
33035        // impl that the sibling
33036        // `placement_strategy_default_routes_through_lifted_default` pin
33037        // already routes onto the constant). Structurally: every
33038        // `Placement::default()` call must yield an `estrategia` field
33039        // byte-equal to the lifted constant so the two paired defaults —
33040        // the [`Default for PlacementStrategy`] impl arm and the
33041        // struct-literal default arm here — cannot silently split on any
33042        // future M3-canonical distribution-default rebrand. Peer of the
33043        // sibling M2
33044        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
33045        // byte-parity pin on the [`Default for SupervisorSpec`]
33046        // struct-literal `estrategia` field extended onto the M3
33047        // mesh-primitive-defining slot family.
33048        assert_eq!(
33049            Placement::default().estrategia,
33050            PLACEMENT_ESTRATEGIA_DEFAULT,
33051        );
33052    }
33053
33054    #[test]
33055    fn placement_serde_default_estrategia_routes_through_lifted_default() {
33056        // Composition pin: the serde-side `#[serde(default)]` on
33057        // [`Placement::estrategia`] — the wire-format author-omitted
33058        // `:placement :estrategia` arm — must resolve onto the substrate-
33059        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
33060        // (via the [`Default for PlacementStrategy`] impl the sibling
33061        // `placement_strategy_default_routes_through_lifted_default` pin
33062        // already routes onto the constant). Structurally: a `Placement`
33063        // deserialized from a payload that omits the `estrategia` key
33064        // must yield an `estrategia` field byte-equal to the lifted
33065        // constant, so the wire-format author-omitted arm and the
33066        // [`PlacementStrategy::default`] impl arm cannot silently split
33067        // on any future M3-canonical distribution-default rebrand. Peer
33068        // of the sibling M2
33069        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
33070        // byte-parity pin on the wire-format author-omitted `:children
33071        // :restart` scalar extended onto the M3 mesh-primitive-defining
33072        // slot family.
33073        let omitted: Placement = serde_json::from_str("{}")
33074            .expect("Placement must deserialize with the estrategia key omitted");
33075        assert_eq!(
33076            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
33077            "an author-omitted :placement :estrategia slot must degrade onto \
33078             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
33079             {:?}, expected {:?})",
33080            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
33081        );
33082    }
33083
33084    // ── contrato_target_ctors! fold pins ────────────────────────────────
33085    //
33086    // Fixture edge triple + payload-field-name label pair for every
33087    // `contrato_target_ctors!`-generated ctor pin below. Kept as
33088    // non-default `("cart", "catalog", "wasi:http/proxy")` +
33089    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
33090    // the fixture default doesn't silently pass. Peer of the sibling
33091    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
33092    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
33093    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
33094    // `missing_entry_ctor_matches_struct_literal_wrap` /
33095    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
33096    // four `LayoutError` constructor families each closed on their
33097    // sibling envelopes.
33098    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
33099        (
33100            "cart".to_string(),
33101            "catalog".to_string(),
33102            "wasi:http/proxy".to_string(),
33103            WitTarget::HTTP_FIELD_NAME,
33104        )
33105    }
33106
33107    #[test]
33108    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
33109        // Equivalence pin: the ctor produces byte-equal
33110        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
33111        // coded struct-literal on the same edge fixture, so the fold
33112        // cannot silently drift on any future field-addition /
33113        // reordering / string-conversion tweak on the variant. Peer of
33114        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
33115        // (17dd504) / the four `LayoutError` family equivalence pins.
33116        let (de, para, wit, expected) = contrato_target_ctor_fixture();
33117        let lifted = AplicacaoError::contrato_wrong_target(
33118            (de.clone(), para.clone(), wit.clone()),
33119            expected,
33120        );
33121        let struct_literal = AplicacaoError::ContratoWrongTarget {
33122            de,
33123            para,
33124            wit,
33125            expected,
33126        };
33127        assert_eq!(lifted, struct_literal);
33128    }
33129
33130    #[test]
33131    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
33132        // Equivalence pin peer of the sibling
33133        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
33134        // on the paired `ContratoMissingTarget` variant of the same
33135        // four-slot envelope shape the `contrato_target_ctors!` macro
33136        // closes.
33137        let (de, para, wit, expected) = contrato_target_ctor_fixture();
33138        let lifted = AplicacaoError::contrato_missing_target(
33139            (de.clone(), para.clone(), wit.clone()),
33140            expected,
33141        );
33142        let struct_literal = AplicacaoError::ContratoMissingTarget {
33143            de,
33144            para,
33145            wit,
33146            expected,
33147        };
33148        assert_eq!(lifted, struct_literal);
33149    }
33150
33151    #[test]
33152    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
33153        // Routing pin: the `(de, para, wit)` triple threads verbatim
33154        // onto same-named fields on both generated ctors, no wrapper-
33155        // side lowercase / trim / re-order. Sweeps a non-default triple
33156        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
33157        // wrapper-side transformation surfaces here rather than at a
33158        // downstream diagnostic-shape drift. Sibling of
33159        // `entrada_host_invalid_ctor_routes_host_through_to_string`
33160        // (17dd504) on the paired triple-carrying envelope.
33161        let edge = (
33162            "cart-svc".to_string(),
33163            "catalog-v2".to_string(),
33164            "nats:pub-sub".to_string(),
33165        );
33166        let wrong =
33167            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
33168        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
33169        let AplicacaoError::ContratoWrongTarget {
33170            de: wde,
33171            para: wpara,
33172            wit: wwit,
33173            ..
33174        } = wrong
33175        else {
33176            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
33177        };
33178        let AplicacaoError::ContratoMissingTarget {
33179            de: mde,
33180            para: mpara,
33181            wit: mwit,
33182            ..
33183        } = missing
33184        else {
33185            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
33186        };
33187        assert_eq!(wde, "cart-svc");
33188        assert_eq!(wpara, "catalog-v2");
33189        assert_eq!(wwit, "nats:pub-sub");
33190        assert_eq!(mde, "cart-svc");
33191        assert_eq!(mpara, "catalog-v2");
33192        assert_eq!(mwit, "nats:pub-sub");
33193    }
33194
33195    #[test]
33196    fn contrato_target_ctors_route_expected_through_verbatim() {
33197        // Routing pin: the `expected: &'static str` label threads
33198        // verbatim (identity, not copy-and-transform) onto the
33199        // `expected` field of both variants, so the four canonical
33200        // labels [`WitTarget::HTTP_FIELD_NAME`] /
33201        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
33202        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
33203        // pointer-equal (not merely value-equal) references — a wrapper-
33204        // side `.to_string()` / `Cow::Owned` promotion would break the
33205        // `&'static str` contract downstream consumers depend on.
33206        for label in [
33207            WitTarget::HTTP_FIELD_NAME,
33208            WitTarget::PUBSUB_FIELD_NAME,
33209            WitTarget::STORE_FIELD_NAME,
33210            WitTarget::CAPABILITY_EXPECTED,
33211        ] {
33212            let (de, para, wit, _) = contrato_target_ctor_fixture();
33213            let wrong = AplicacaoError::contrato_wrong_target(
33214                (de.clone(), para.clone(), wit.clone()),
33215                label,
33216            );
33217            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
33218            match wrong {
33219                AplicacaoError::ContratoWrongTarget { expected, .. } => {
33220                    assert!(
33221                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
33222                            && expected.len() == label.len(),
33223                        "contrato_wrong_target must thread the &'static str \
33224                         label pointer-equal onto the `expected` field \
33225                         (label = {label:?})",
33226                    );
33227                }
33228                other => panic!("expected ContratoWrongTarget, got {other:?}"),
33229            }
33230            match missing {
33231                AplicacaoError::ContratoMissingTarget { expected, .. } => {
33232                    assert!(
33233                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
33234                            && expected.len() == label.len(),
33235                        "contrato_missing_target must thread the &'static \
33236                         str label pointer-equal onto the `expected` field \
33237                         (label = {label:?})",
33238                    );
33239                }
33240                other => panic!("expected ContratoMissingTarget, got {other:?}"),
33241            }
33242        }
33243    }
33244
33245    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
33246    //
33247    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
33248    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
33249    // byte-equality mistake against the fixture default doesn't silently
33250    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
33251    // triple + expected-label envelope on
33252    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
33253    // struct_literal_wrap` (17dd504, host + reason envelope on
33254    // `entrada_host_invalid`) / the four `LayoutError` family
33255    // equivalence pins.
33256    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
33257        ("cart".to_string(), "catalog".to_string())
33258    }
33259
33260    #[test]
33261    fn empty_wit_ctor_matches_struct_literal_wrap() {
33262        // Equivalence pin: the ctor produces byte-equal
33263        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
33264        // struct-literal on the same edge pair, so the fold cannot
33265        // silently drift on any future field-addition / reordering /
33266        // string-conversion tweak on the variant. Peer of the sibling
33267        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
33268        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
33269        // (17dd504) / the four `LayoutError` family equivalence pins.
33270        let (de, para) = contrato_empty_pair_ctor_fixture();
33271        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
33272        let struct_literal = AplicacaoError::EmptyWit { de, para };
33273        assert_eq!(lifted, struct_literal);
33274    }
33275
33276    #[test]
33277    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
33278        // Equivalence pin peer of the sibling
33279        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
33280        // paired `ContratoEndpointEmpty` variant of the same two-slot
33281        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
33282        let (de, para) = contrato_empty_pair_ctor_fixture();
33283        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
33284        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
33285        assert_eq!(lifted, struct_literal);
33286    }
33287
33288    #[test]
33289    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
33290        // Equivalence pin peer of the sibling
33291        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33292        // above on the paired `ContratoSubjectEmpty` variant of the
33293        // same two-slot envelope shape.
33294        let (de, para) = contrato_empty_pair_ctor_fixture();
33295        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
33296        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
33297        assert_eq!(lifted, struct_literal);
33298    }
33299
33300    #[test]
33301    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
33302        // Equivalence pin peer of the sibling
33303        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
33304        // above on the paired `ContratoSlotEmpty` variant of the same
33305        // two-slot envelope shape.
33306        let (de, para) = contrato_empty_pair_ctor_fixture();
33307        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
33308        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
33309        assert_eq!(lifted, struct_literal);
33310    }
33311
33312    #[test]
33313    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
33314        // Routing pin: the `(de, para)` pair threads verbatim onto
33315        // same-named fields on all four generated ctors, no wrapper-
33316        // side lowercase / trim / re-order. Sweeps a non-default pair
33317        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33318        // transformation surfaces here rather than at a downstream
33319        // diagnostic-shape drift. Sibling of
33320        // `contrato_target_ctors_route_edge_triple_through_verbatim`
33321        // (14b81d5) on the paired triple-carrying envelope and of
33322        // `entrada_host_invalid_ctor_routes_host_through_to_string`
33323        // (17dd504) on the sibling `{ host, reason }` envelope.
33324        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33325        let variants: [(AplicacaoError, &'static str); 4] = [
33326            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
33327            (
33328                AplicacaoError::contrato_endpoint_empty(edge.clone()),
33329                "ContratoEndpointEmpty",
33330            ),
33331            (
33332                AplicacaoError::contrato_subject_empty(edge.clone()),
33333                "ContratoSubjectEmpty",
33334            ),
33335            (
33336                AplicacaoError::contrato_slot_empty(edge.clone()),
33337                "ContratoSlotEmpty",
33338            ),
33339        ];
33340        for (built, label) in variants {
33341            let (de, para) = match built {
33342                AplicacaoError::EmptyWit { de, para }
33343                | AplicacaoError::ContratoEndpointEmpty { de, para }
33344                | AplicacaoError::ContratoSubjectEmpty { de, para }
33345                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
33346                other => panic!("expected {label} pair variant, got {other:?}"),
33347            };
33348            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
33349            assert_eq!(
33350                para, "catalog-v2",
33351                "para field on {label} must thread verbatim",
33352            );
33353        }
33354    }
33355
33356    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
33357    //
33358    // Fixture edge pair + value + reason for every
33359    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
33360    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
33361    // fixed per-axis `<val>` / reason so a byte-equality mistake against
33362    // the fixture default doesn't silently pass. Peer of the sibling
33363    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
33364    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
33365    // (14b81d5, triple + expected-label envelope on
33366    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
33367    // struct_literal_wrap` (17dd504, host + reason envelope on
33368    // `entrada_host_invalid`).
33369    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
33370        ("cart".to_string(), "catalog".to_string())
33371    }
33372
33373    #[test]
33374    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
33375        // Equivalence pin: the ctor produces byte-equal
33376        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
33377        // open-coded struct-literal on the same
33378        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
33379        // silently drift on any future field-addition / reordering /
33380        // string-conversion tweak on the variant. Peer of the sibling
33381        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33382        // (8580068) on the paired two-slot envelope of the same
33383        // `{ de, para, ... }` prefix, and of
33384        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
33385        // (17dd504) on the sibling `{ <field>: String, reason: String }`
33386        // two-slot envelope.
33387        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33388        let endpoint = "/charge";
33389        let reason = "sample reason text";
33390        let lifted =
33391            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
33392        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
33393            de,
33394            para,
33395            endpoint: endpoint.to_string(),
33396            reason: reason.to_string(),
33397        };
33398        assert_eq!(lifted, struct_literal);
33399    }
33400
33401    #[test]
33402    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
33403        // Equivalence pin peer of the sibling
33404        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
33405        // above on the paired `ContratoSubjectInvalid` variant of the
33406        // same four-slot envelope shape the
33407        // `contrato_pair_value_reason_ctors!` macro closes.
33408        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33409        let subject = "checkout.events.charge.failed";
33410        let reason = "sample reason text";
33411        let lifted =
33412            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
33413        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
33414            de,
33415            para,
33416            subject: subject.to_string(),
33417            reason: reason.to_string(),
33418        };
33419        assert_eq!(lifted, struct_literal);
33420    }
33421
33422    #[test]
33423    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
33424        // Equivalence pin peer of the sibling
33425        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
33426        // above on the paired `ContratoSlotInvalid` variant of the same
33427        // four-slot envelope shape.
33428        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33429        let slot = "checkout/$orderId";
33430        let reason = "sample reason text";
33431        let lifted =
33432            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
33433        let struct_literal = AplicacaoError::ContratoSlotInvalid {
33434            de,
33435            para,
33436            slot: slot.to_string(),
33437            reason: reason.to_string(),
33438        };
33439        assert_eq!(lifted, struct_literal);
33440    }
33441
33442    #[test]
33443    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
33444        // Equivalence pin peer of the sibling
33445        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
33446        // on the paired `ContratoWitInvalid` variant of the same four-
33447        // slot envelope shape the `contrato_pair_value_reason_ctors!`
33448        // macro closes. Fold pinned this test lands with the last
33449        // `{ de, para, <field>: String, reason: String }` open-coded
33450        // struct-literal inside [`WitContract::target`] rewritten to
33451        // route through the macro-generated
33452        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
33453        // between the ctor and the pre-lift struct-literal trips this
33454        // pin ahead of any downstream diagnostic-shape drift on the
33455        // `:contratos :wit` axis.
33456        let (de, para) = contrato_pair_value_reason_ctor_fixture();
33457        let wit = "wasi-http/proxy";
33458        let reason = "sample reason text";
33459        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
33460        let struct_literal = AplicacaoError::ContratoWitInvalid {
33461            de,
33462            para,
33463            wit: wit.to_string(),
33464            reason: reason.to_string(),
33465        };
33466        assert_eq!(lifted, struct_literal);
33467    }
33468
33469    #[test]
33470    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
33471        // Routing pin: the `(de, para)` pair threads verbatim onto
33472        // same-named fields on all four generated ctors, no wrapper-
33473        // side lowercase / trim / re-order. Sweeps a non-default pair
33474        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33475        // transformation surfaces here rather than at a downstream
33476        // diagnostic-shape drift. Sibling of
33477        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
33478        // (8580068) on the paired two-slot envelope and of
33479        // `contrato_target_ctors_route_edge_triple_through_verbatim`
33480        // (14b81d5) on the paired triple-carrying envelope.
33481        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33482        let variants: [(AplicacaoError, &'static str); 4] = [
33483            (
33484                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
33485                "ContratoEndpointInvalid",
33486            ),
33487            (
33488                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
33489                "ContratoSubjectInvalid",
33490            ),
33491            (
33492                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
33493                "ContratoSlotInvalid",
33494            ),
33495            (
33496                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
33497                "ContratoWitInvalid",
33498            ),
33499        ];
33500        for (built, label) in variants {
33501            let (de, para) = match built {
33502                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
33503                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
33504                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
33505                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
33506                other => panic!("expected {label} pair variant, got {other:?}"),
33507            };
33508            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
33509            assert_eq!(
33510                para, "catalog-v2",
33511                "para field on {label} must thread verbatim",
33512            );
33513        }
33514    }
33515
33516    #[test]
33517    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
33518        // Cross-arm invariance pin — the four ctors all route
33519        // `reason: impl Into<String>` verbatim onto their respective
33520        // typed variants through the shared
33521        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
33522        // pair (`&str` literal, `format!` output) against every ctor to
33523        // pin that no per-arm wrapper transformation drifted in against
33524        // the uniform macro-generated body. Peer of
33525        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
33526        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
33527        let edge = || ("cart".to_string(), "catalog".to_string());
33528        let via_literal = "literal reason text";
33529        let via_format = format!("{} reason text", "literal");
33530        assert_eq!(
33531            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
33532            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
33533        );
33534        assert_eq!(
33535            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
33536            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
33537        );
33538        assert_eq!(
33539            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
33540            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
33541        );
33542        assert_eq!(
33543            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
33544            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
33545        );
33546    }
33547
33548    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
33549    //
33550    // Fail-before-pass-after pins for the standalone
33551    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
33552    // (see the paired doc-block above the ctor definition) — the fold of
33553    // the last open-coded three-slot `{ de, para, endpoint: <val>
33554    // .to_string() }` struct-literal inside [`WitContract::target`]'s
33555    // HTTP-arm leading-slash gate onto one substrate primitive on the
33556    // envelope. A byte-mismatched ctor body would trip the equivalence
33557    // pin first, ahead of any downstream diagnostic-shape drift.
33558    //
33559    // Peer of the sibling standalone-ctor equivalence pins on the peer
33560    // one-off variants across caixa-core:
33561    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
33562    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
33563    // on the paired two-slot and four-slot per-`:contratos :endpoint`
33564    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
33565    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
33566    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
33567    // reason }` two- and three-slot envelopes; the
33568    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
33569    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
33570    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
33571        ("cart".to_string(), "catalog".to_string())
33572    }
33573
33574    #[test]
33575    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
33576        // Equivalence pin: the ctor produces byte-equal
33577        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
33578        // open-coded struct-literal on the same `(edge_pair, endpoint)`
33579        // pair, so the fold cannot silently drift on any future
33580        // field-addition / reordering / string-conversion tweak on the
33581        // variant. Same equivalence-pin shape as the sibling
33582        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
33583        // (8580068) on the paired two-slot envelope and
33584        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
33585        // (14e13f1) on the paired four-slot envelope of the same
33586        // `{ de, para, ... }`-prefix `:endpoint` axis.
33587        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
33588        let endpoint = "charge";
33589        let lifted =
33590            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
33591        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
33592            de,
33593            para,
33594            endpoint: endpoint.to_string(),
33595        };
33596        assert_eq!(lifted, struct_literal);
33597    }
33598
33599    #[test]
33600    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
33601        // Routing pin on the `(de, para)` axis: sweep a non-default
33602        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
33603        // lowercase / trim / re-order surfaces here rather than at a
33604        // downstream diagnostic-shape drift. Peer of
33605        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
33606        // (8580068) on the paired two-slot envelope and
33607        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
33608        // (14e13f1) on the paired four-slot envelope of the same
33609        // `{ de, para, ... }`-prefix `:contratos` axis.
33610        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
33611        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
33612        match built {
33613            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
33614                assert_eq!(de, "cart-svc", "de field must thread verbatim");
33615                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
33616            }
33617            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
33618        }
33619    }
33620
33621    #[test]
33622    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
33623        // Routing pin on the `endpoint: &str` axis: sweep a non-default
33624        // value (`"charge"` — no leading `/`, the exact shape the
33625        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
33626        // through the sole payload-carrier constructor axis so any
33627        // wrapper-side transformation on the `endpoint.to_string()`
33628        // one-field construction surfaces here rather than at a
33629        // downstream diagnostic-shape mismatch. Sibling of
33630        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
33631        // (14e13f1) on the sibling four-slot envelope's payload-carrier
33632        // routing pin.
33633        let edge = || ("cart".to_string(), "catalog".to_string());
33634        let via_literal = "charge";
33635        let via_string = String::from("charge");
33636        assert_eq!(
33637            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
33638            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
33639        );
33640    }
33641
33642    // ── contrato_self_loop standalone ctor pins ─────────────────────────
33643    //
33644    // Fail-before-pass-after pins for the standalone
33645    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
33646    // doc-block above the ctor definition) — the fold of the last
33647    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
33648    // <ct>.world_ref().to_string() }` struct-literal inside
33649    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
33650    // arm onto one substrate primitive on the [`AplicacaoError`]
33651    // envelope, projecting through the paired [`WitContract::source`] /
33652    // [`WitContract::world_ref`] scalar accessors on the substrate
33653    // primitive. A byte-mismatched ctor body would trip the equivalence
33654    // pin first, ahead of any downstream diagnostic-shape drift.
33655    //
33656    // Peer of the sibling standalone-ctor equivalence pins on the peer
33657    // one-off variants across caixa-core:
33658    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
33659    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
33660    // envelope, the sibling
33661    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
33662    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
33663    // the paired two-slot and four-slot per-`:contratos :endpoint`
33664    // envelopes, and the sibling
33665    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
33666    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
33667    fn contrato_self_loop_ctor_fixture() -> WitContract {
33668        WitContract {
33669            de: "cart".to_string(),
33670            para: "cart".to_string(),
33671            wit: "wasi:http/proxy".to_string(),
33672            endpoint: Some("/self".to_string()),
33673            subject: None,
33674            slot: None,
33675        }
33676    }
33677
33678    #[test]
33679    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
33680        // Equivalence pin: the ctor produces byte-equal
33681        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
33682        // struct-literal that read the same two fields through
33683        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
33684        // any future field-addition / reordering / string-conversion
33685        // tweak on the variant. Same equivalence-pin shape as the
33686        // sibling `contrato_endpoint_not_absolute_ctor_matches_
33687        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
33688        // per-`:contratos :endpoint` envelope.
33689        let contract = contrato_self_loop_ctor_fixture();
33690        let lifted = AplicacaoError::contrato_self_loop(&contract);
33691        let struct_literal = AplicacaoError::ContratoSelfLoop {
33692            caixa: contract.source().to_string(),
33693            wit: contract.world_ref().to_string(),
33694        };
33695        assert_eq!(lifted, struct_literal);
33696    }
33697
33698    #[test]
33699    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
33700        // Routing pin sweeping non-default `caixa` and `:wit` values
33701        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
33702        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
33703        // axes so any wrapper-side lowercase / trim / re-order surfaces
33704        // here rather than at a downstream diagnostic-shape drift.
33705        // Peer of the sibling
33706        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
33707        // (cdf1a2c) routing pin on the sibling three-slot envelope.
33708        let contract = WitContract {
33709            de: "catalog-v2".to_string(),
33710            para: "catalog-v2".to_string(),
33711            wit: "nats:pub-sub".to_string(),
33712            endpoint: None,
33713            subject: Some("orders.>".to_string()),
33714            slot: None,
33715        };
33716        let built = AplicacaoError::contrato_self_loop(&contract);
33717        match built {
33718            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
33719                assert_eq!(
33720                    caixa, "catalog-v2",
33721                    "caixa slot must thread WitContract::source() verbatim"
33722                );
33723                assert_eq!(
33724                    wit, "nats:pub-sub",
33725                    "wit slot must thread WitContract::world_ref() verbatim"
33726                );
33727            }
33728            other => panic!("expected ContratoSelfLoop, got {other:?}"),
33729        }
33730    }
33731
33732    #[test]
33733    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
33734        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
33735        // [`WitContract::source`] accessor (matching the pre-lift open-
33736        // coded body's field selection), not [`WitContract::destination`].
33737        // Under today's `WitContract::is_self_loop()`-gated call site
33738        // the two are equal by that predicate's own contract, but a
33739        // future consumer that constructs the ctor against a not-yet-
33740        // gated candidate contract — an M4
33741        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
33742        // checking a per-`(:de, :para)`-patched candidate before the
33743        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
33744        // resolver rejecting a self-edge introduced by a cluster-local
33745        // `:contratos` override — needs the pre-lift field selection
33746        // pinned so a silent `.destination()` swap at the ctor body
33747        // surfaces here rather than at a downstream diagnostic mis-
33748        // attribution far from the self-loop diagnostic's owner
33749        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
33750        // direction).
33751        //
33752        // Deliberately constructs a non-self-loop pair (`"cart" →
33753        // "catalog"`) so the two accessors yield distinct bytes on the
33754        // fixture — a `.destination()` swap at the ctor body would land
33755        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
33756        // the assertion here.
33757        let contract = WitContract {
33758            de: "cart".to_string(),
33759            para: "catalog".to_string(),
33760            wit: "wasi:http/proxy".to_string(),
33761            endpoint: Some("/charge".to_string()),
33762            subject: None,
33763            slot: None,
33764        };
33765        let built = AplicacaoError::contrato_self_loop(&contract);
33766        match built {
33767            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
33768                assert_eq!(
33769                    caixa, "cart",
33770                    "caixa slot must project WitContract::source() (not destination)"
33771                );
33772            }
33773            other => panic!("expected ContratoSelfLoop, got {other:?}"),
33774        }
33775    }
33776
33777    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
33778    // macro definition (see the paired doc-block above the macro definition)
33779    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
33780    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
33781    // struct-literal onto one substrate primitive. The four per-variant
33782    // equivalence pins below (fail-before-pass-after by construction — a
33783    // byte-mismatched macro arm would trip its equivalence pin first) lock
33784    // each generated constructor to its struct-literal peer under
33785    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
33786    // [`AplicacaoSpec::validate_membros`], and
33787    // [`validate_no_self_membership`] on that variant produces a byte-equal
33788    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
33789    // cross-axis pin that follows (non-default caixa name) routes the sole
33790    // constructor input axis through `.to_string()`, so the fold does not
33791    // silently collapse onto a fixed name.
33792    //
33793    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
33794    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
33795    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
33796    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
33797    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
33798    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
33799    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
33800    // of the peer M2 `:behavior` envelope fold (67c31ec,
33801    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
33802    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
33803    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
33804
33805    #[test]
33806    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
33807        assert_eq!(
33808            AplicacaoError::contrato_member_missing("cart"),
33809            AplicacaoError::ContratoMemberMissing {
33810                caixa: "cart".to_string(),
33811            },
33812            "generated contrato_member_missing ctor must produce byte-equal \
33813             AplicacaoError to the open-coded struct-literal wrap on the \
33814             same &str fixture",
33815        );
33816    }
33817
33818    #[test]
33819    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
33820        assert_eq!(
33821            AplicacaoError::membro_versao_empty("cart"),
33822            AplicacaoError::MembroVersaoEmpty {
33823                caixa: "cart".to_string(),
33824            },
33825            "generated membro_versao_empty ctor must produce byte-equal \
33826             AplicacaoError to the open-coded struct-literal wrap on the \
33827             same &str fixture",
33828        );
33829    }
33830
33831    #[test]
33832    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
33833        assert_eq!(
33834            AplicacaoError::membro_duplicate("cart"),
33835            AplicacaoError::MembroDuplicate {
33836                caixa: "cart".to_string(),
33837            },
33838            "generated membro_duplicate ctor must produce byte-equal \
33839             AplicacaoError to the open-coded struct-literal wrap on the \
33840             same &str fixture",
33841        );
33842    }
33843
33844    #[test]
33845    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
33846        assert_eq!(
33847            AplicacaoError::membro_is_self_aplicacao("checkout"),
33848            AplicacaoError::MembroIsSelfAplicacao {
33849                caixa: "checkout".to_string(),
33850            },
33851            "generated membro_is_self_aplicacao ctor must produce byte-equal \
33852             AplicacaoError to the open-coded struct-literal wrap on the \
33853             same &str fixture",
33854        );
33855    }
33856
33857    #[test]
33858    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
33859        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
33860        // &str`) through a non-default fixture name against every generated
33861        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
33862        // wrapper-side lowercase / trim / truncate / re-order on the
33863        // `caixa.to_string()` sole-field construction surfaces here rather
33864        // than at a downstream diagnostic-shape mismatch. Peer of the
33865        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
33866        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
33867        // envelope (db09650), extended here onto the peer `AplicacaoError`
33868        // `{ caixa: String }` envelope so every substrate-primitive ctor
33869        // family in caixa-core carrying a single-slot `{ caixa: String }`
33870        // shape guarantees the sole-field construction routes the caller's
33871        // `&str` through `.to_string()` verbatim.
33872        let name = "cache-v2";
33873        assert_eq!(
33874            AplicacaoError::contrato_member_missing(name),
33875            AplicacaoError::ContratoMemberMissing {
33876                caixa: name.to_string(),
33877            },
33878        );
33879        assert_eq!(
33880            AplicacaoError::membro_versao_empty(name),
33881            AplicacaoError::MembroVersaoEmpty {
33882                caixa: name.to_string(),
33883            },
33884        );
33885        assert_eq!(
33886            AplicacaoError::membro_duplicate(name),
33887            AplicacaoError::MembroDuplicate {
33888                caixa: name.to_string(),
33889            },
33890        );
33891        assert_eq!(
33892            AplicacaoError::membro_is_self_aplicacao(name),
33893            AplicacaoError::MembroIsSelfAplicacao {
33894                caixa: name.to_string(),
33895            },
33896        );
33897    }
33898
33899    #[test]
33900    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
33901        assert_eq!(
33902            AplicacaoError::entrada_path_not_absolute("api/cart"),
33903            AplicacaoError::EntradaPathNotAbsolute {
33904                path: "api/cart".to_string(),
33905            },
33906            "generated entrada_path_not_absolute ctor must produce byte-equal \
33907             AplicacaoError to the open-coded struct-literal wrap on the \
33908             same &str fixture",
33909        );
33910    }
33911
33912    #[test]
33913    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
33914        assert_eq!(
33915            AplicacaoError::entrada_path_duplicate("/api/cart"),
33916            AplicacaoError::EntradaPathDuplicate {
33917                path: "/api/cart".to_string(),
33918            },
33919            "generated entrada_path_duplicate ctor must produce byte-equal \
33920             AplicacaoError to the open-coded struct-literal wrap on the \
33921             same &str fixture",
33922        );
33923    }
33924
33925    // ── membro_versao_invalid ctor pins ────────────────────────────────
33926    //
33927    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
33928    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
33929    // produces an `AplicacaoError` structurally identical to the pre-lift
33930    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
33931    // versao.to_string(), reason: reason.into() }` open-coded three-slot
33932    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
33933    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
33934    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33935    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
33936    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
33937    // extended here onto the paired per-`:membros :versao` axis on the
33938    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
33939    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
33940    // typed-error surface guarantee the shared three-field construction
33941    // routes through one substrate primitive per envelope.
33942
33943    #[test]
33944    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
33945        let caixa = "cart";
33946        let versao = "not-a-req";
33947        let reason = "sample reason text";
33948        assert_eq!(
33949            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
33950            AplicacaoError::MembroVersaoInvalid {
33951                caixa: caixa.to_string(),
33952                versao: versao.to_string(),
33953                reason: reason.to_string(),
33954            },
33955            "lifted membro_versao_invalid ctor must produce byte-equal \
33956             AplicacaoError to the open-coded struct-literal wrap on the \
33957             same (&str, &str, reason) fixture",
33958        );
33959    }
33960
33961    #[test]
33962    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
33963        // Cross-axis pin: sweep the two `&str`-shaped constructor input
33964        // axes (`caixa`, `versao`) through non-default fixtures so any
33965        // wrapper-side lowercase / trim / truncate / re-order on either
33966        // `.to_string()` field construction surfaces here rather than at
33967        // a downstream diagnostic-shape mismatch. Peer of the sibling
33968        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33969        // routing pin on the peer `SupervisorError` envelope.
33970        let caixa = "Cart-V2";
33971        let versao = "0.1.0-alpha+build.42";
33972        let reason = "constructed reason";
33973        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
33974        let AplicacaoError::MembroVersaoInvalid {
33975            caixa: got_caixa,
33976            versao: got_versao,
33977            reason: got_reason,
33978        } = err
33979        else {
33980            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
33981        };
33982        assert_eq!(got_caixa, caixa.to_string());
33983        assert_eq!(got_versao, versao.to_string());
33984        assert_eq!(got_reason, reason.to_string());
33985    }
33986
33987    #[test]
33988    fn membro_versao_invalid_ctor_routes_reason_through_into() {
33989        // Route pin: the `reason: impl Into<String>` bound accepts both
33990        // `&str` literals and `format!(…)` / `String` outputs verbatim,
33991        // matching the sibling
33992        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
33993        // routing pin on the peer `SupervisorError::child_versao_invalid`.
33994        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
33995        // `require_valid_versao_requirement`-delivered `reason` closure
33996        // parameter (typed `String`) picks the ctor up without a per-arm
33997        // wrapper transformation, and every future consumer that
33998        // constructs the variant from a `format!(…)` reason surfaces
33999        // byte-equal to the `&str`-literal path.
34000        let caixa = "cart";
34001        let versao = "not-a-req";
34002        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
34003        let from_format =
34004            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
34005        let from_string =
34006            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
34007        assert_eq!(from_literal, from_format);
34008        assert_eq!(from_literal, from_string);
34009    }
34010
34011    #[test]
34012    fn aplicacao_path_only_ctors_route_path_through_to_string() {
34013        // Cross-axis pin: sweep the sole constructor input axis (`path:
34014        // &str`) through a non-default fixture path against every generated
34015        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
34016        // wrapper-side lowercase / trim / truncate / re-order on the
34017        // `path.to_string()` sole-field construction surfaces here rather
34018        // than at a downstream diagnostic-shape mismatch. Peer of the
34019        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
34020        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
34021        // envelope (d9f6867), extended here onto the sibling
34022        // `AplicacaoError` `{ path: String }` envelope so every substrate-
34023        // primitive ctor family in caixa-core carrying a single-slot
34024        // `{ <slot>: String }` shape guarantees the sole-field construction
34025        // routes the caller's `&str` through `.to_string()` verbatim.
34026        let path = "/api/v2/checkout";
34027        assert_eq!(
34028            AplicacaoError::entrada_path_not_absolute(path),
34029            AplicacaoError::EntradaPathNotAbsolute {
34030                path: path.to_string(),
34031            },
34032        );
34033        assert_eq!(
34034            AplicacaoError::entrada_path_duplicate(path),
34035            AplicacaoError::EntradaPathDuplicate {
34036                path: path.to_string(),
34037            },
34038        );
34039    }
34040
34041    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
34042    //
34043    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
34044    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
34045    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
34046    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
34047    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
34048    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
34049    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
34050    // substitution on any one variant surfaces here rather than at a downstream
34051    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
34052    // pins on `aplicacao_field_reason_ctors!` (981060b),
34053    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
34054    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
34055    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
34056    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
34057    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
34058    // per-envelope ctor-macro pins.
34059
34060    #[test]
34061    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
34062        let timeout = Duration::from_micros(1_500);
34063        assert_eq!(
34064            AplicacaoError::policy_timeout_not_canonical(timeout),
34065            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
34066            "generated policy_timeout_not_canonical ctor must produce byte-equal \
34067             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
34068             struct-literal wrap on the same `Copy`-`Duration` fixture",
34069        );
34070    }
34071
34072    #[test]
34073    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
34074        let timeout = Duration::from_secs(3_601);
34075        assert_eq!(
34076            AplicacaoError::policy_timeout_exceeds_cap(timeout),
34077            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
34078            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
34079             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
34080             struct-literal wrap on the same `Copy`-`Duration` fixture",
34081        );
34082    }
34083
34084    #[test]
34085    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
34086        let retries = 47_u32;
34087        assert_eq!(
34088            AplicacaoError::policy_retries_exceeds_cap(retries),
34089            AplicacaoError::PolicyRetriesExceedsCap { retries },
34090            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
34091             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
34092             struct-literal wrap on the same `Copy`-`u32` fixture",
34093        );
34094    }
34095
34096    #[test]
34097    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
34098        let max_failures = 1_337_u32;
34099        assert_eq!(
34100            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
34101            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
34102            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
34103             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
34104             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
34105        );
34106    }
34107
34108    #[test]
34109    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
34110        let window = Duration::from_micros(500);
34111        assert_eq!(
34112            AplicacaoError::policy_breaker_window_not_canonical(window),
34113            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
34114            "generated policy_breaker_window_not_canonical ctor must produce \
34115             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
34116             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
34117        );
34118    }
34119
34120    #[test]
34121    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
34122        let window = Duration::from_secs(3_700);
34123        assert_eq!(
34124            AplicacaoError::policy_breaker_window_exceeds_cap(window),
34125            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
34126            "generated policy_breaker_window_exceeds_cap ctor must produce \
34127             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
34128             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
34129        );
34130    }
34131
34132    #[test]
34133    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
34134        let rate = 1_000_001_u32;
34135        assert_eq!(
34136            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
34137            AplicacaoError::PolicyRateLimitExceedsCap { rate },
34138            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
34139             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
34140             struct-literal wrap on the same `Copy`-`u32` fixture",
34141        );
34142    }
34143
34144    #[test]
34145    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
34146        let window = Duration::from_secs(15);
34147        assert_eq!(
34148            AplicacaoError::policy_rate_limit_window_not_canonical(window),
34149            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
34150            "generated policy_rate_limit_window_not_canonical ctor must produce \
34151             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
34152             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
34153             fixture",
34154        );
34155    }
34156
34157    #[test]
34158    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
34159        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
34160        // constructor input axis through a non-default `Copy` fixture against
34161        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
34162        // wrapper-side silent `.into()` / silent constant-substitution / silent
34163        // field re-name away from the canonical `timeout | retries |
34164        // max_failures | window | rate` axes on any one variant, or a
34165        // `Duration | u32` axis silently rerouted through some other `Copy`
34166        // coercion, surfaces here rather than at a downstream per-`:politicas`
34167        // diagnostic-shape drift. Peer of the sibling
34168        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
34169        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
34170        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
34171        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
34172        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
34173        // families, extended here onto the last M3 per-`:politicas` per-axis
34174        // `AplicacaoError` variant family folded onto a substrate primitive.
34175        //
34176        // Fixtures picked out of each variant's accept-set boundary rather
34177        // than the default value so a silent constant-substitution to `0` /
34178        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
34179        // structural-equality assertion. The two `Duration` fixtures pick the
34180        // sub-millisecond and above-cap ends respectively; the three `u32`
34181        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
34182        // `rate` respectively (each variant's cap sits well below the fixture
34183        // so the pre-lift struct-literal wrap the fixture is compared against
34184        // is the same shape the pre-lift wire-up produced).
34185        let sub_ms = Duration::from_micros(1_500);
34186        let above_hour = Duration::from_secs(3_700);
34187        let non_canonical_rl_window = Duration::from_secs(15);
34188        assert_eq!(
34189            AplicacaoError::policy_timeout_not_canonical(sub_ms),
34190            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
34191        );
34192        assert_eq!(
34193            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
34194            AplicacaoError::PolicyTimeoutExceedsCap {
34195                timeout: above_hour,
34196            },
34197        );
34198        assert_eq!(
34199            AplicacaoError::policy_retries_exceeds_cap(47),
34200            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
34201        );
34202        assert_eq!(
34203            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
34204            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
34205                max_failures: 1_337,
34206            },
34207        );
34208        assert_eq!(
34209            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
34210            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
34211        );
34212        assert_eq!(
34213            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
34214            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
34215        );
34216        assert_eq!(
34217            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
34218            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
34219        );
34220        assert_eq!(
34221            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
34222            AplicacaoError::PolicyRateLimitWindowNotCanonical {
34223                window: non_canonical_rl_window,
34224            },
34225        );
34226    }
34227
34228    #[test]
34229    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
34230        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
34231        // every generated ctor `const fn` so a caller can pin an
34232        // `AplicacaoError` at compile time — the same zero-runtime-work
34233        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
34234        // closure carried on its `Copy`-pass-through construction path (no
34235        // `.to_string()` / `.into()` allocation, no branching). If any future
34236        // edit silently drops the `const` qualifier from the macro body the
34237        // per-arm `const` bindings below fail to compile, which surfaces the
34238        // regression at the substrate-primitive definition rather than at
34239        // some downstream consumer that had come to rely on the `const`-
34240        // constructibility. Peer of the sibling per-variant
34241        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
34242        // equality axis; this pin closes the compile-time-const axis on the
34243        // same generated family.
34244        const TIMEOUT_NC: AplicacaoError =
34245            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
34246        const TIMEOUT_CAP: AplicacaoError =
34247            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
34248        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
34249        const MAX_FAIL_CAP: AplicacaoError =
34250            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
34251        const CB_WIN_NC: AplicacaoError =
34252            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
34253        const CB_WIN_CAP: AplicacaoError =
34254            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
34255        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
34256        const RL_WIN_NC: AplicacaoError =
34257            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
34258        assert!(matches!(
34259            TIMEOUT_NC,
34260            AplicacaoError::PolicyTimeoutNotCanonical { .. }
34261        ));
34262        assert!(matches!(
34263            TIMEOUT_CAP,
34264            AplicacaoError::PolicyTimeoutExceedsCap { .. }
34265        ));
34266        assert!(matches!(
34267            RETRIES_CAP,
34268            AplicacaoError::PolicyRetriesExceedsCap { .. }
34269        ));
34270        assert!(matches!(
34271            MAX_FAIL_CAP,
34272            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
34273        ));
34274        assert!(matches!(
34275            CB_WIN_NC,
34276            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
34277        ));
34278        assert!(matches!(
34279            CB_WIN_CAP,
34280            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
34281        ));
34282        assert!(matches!(
34283            RATE_CAP,
34284            AplicacaoError::PolicyRateLimitExceedsCap { .. }
34285        ));
34286        assert!(matches!(
34287            RL_WIN_NC,
34288            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
34289        ));
34290    }
34291
34292    // Per-variant equivalence + routing pins for the
34293    // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
34294    // (see the paired doc-block above the ctor definition) — the
34295    // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
34296    // Self` inherent constructor folds the uniform
34297    // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
34298    // one-field struct-literal onto one substrate primitive. Same
34299    // shape as the sibling
34300    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
34301    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
34302    // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
34303    // ctors — extended here onto the single-slot per-`:placement
34304    // :clusters` dedup-envelope.
34305
34306    #[test]
34307    fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
34308        // Equivalence pin: the ctor produces byte-equal
34309        // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
34310        // open-coded struct-literal that read the same field through
34311        // `c.clone()` at the caller site inside
34312        // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
34313        // field-addition / reordering / string-conversion tweak on the
34314        // variant.
34315        let cluster = "rio";
34316        let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
34317        let struct_literal = AplicacaoError::PlacementClusterDuplicate {
34318            cluster: cluster.to_string(),
34319        };
34320        assert_eq!(lifted, struct_literal);
34321    }
34322
34323    #[test]
34324    fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
34325        // Routing pin: sweep the sole constructor input axis
34326        // (`cluster: &str`) through a non-default fixture name so any
34327        // wrapper-side lowercase / trim / truncate / re-order on the
34328        // `cluster.to_string()` sole-field construction surfaces here
34329        // rather than at a downstream diagnostic-shape mismatch. Peer of
34330        // the sibling
34331        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
34332        // (d9f6867) cross-axis pin on the sibling one-slot
34333        // `{ caixa: String }` envelope — extended here onto the sibling
34334        // `{ cluster: String }` envelope so the sole `String`-slot
34335        // construction routes the caller's `&str` through `.to_string()`
34336        // verbatim.
34337        let cluster = "sao-paulo-2";
34338        let built = AplicacaoError::placement_cluster_duplicate(cluster);
34339        match built {
34340            AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
34341                assert_eq!(
34342                    c, cluster,
34343                    "cluster slot must thread the caller's `&str` verbatim through .to_string()"
34344                );
34345            }
34346            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
34347        }
34348    }
34349
34350    // Per-variant equivalence + routing pins for the
34351    // [`AplicacaoError::placement_without_clusters`] standalone ctor
34352    // (see the paired doc-block above the ctor definition) — the
34353    // generated `pub const fn placement_without_clusters(placement:
34354    // &Placement) -> Self` inherent constructor folds the uniform
34355    // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
34356    // }` one-field `Copy`-pass-through struct-literal onto one substrate
34357    // primitive. Same shape as the sibling
34358    // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
34359    // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
34360    // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
34361    // ctors — extended here onto the one-slot per-`:placement`
34362    // empty-clusters envelope.
34363
34364    #[test]
34365    fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
34366        // Equivalence pin: the ctor produces byte-equal
34367        // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
34368        // open-coded struct-literal that read the same field through
34369        // `p.estrategia()` at the caller site inside
34370        // [`AplicacaoSpec::validate_placement`]. Guards any future
34371        // field-addition / reordering / accessor-return tweak on the
34372        // variant.
34373        let placement = Placement {
34374            estrategia: PlacementStrategy::Replicated,
34375            clusters: vec![],
34376            affinity: None,
34377            shard_key: None,
34378        };
34379        let lifted = AplicacaoError::placement_without_clusters(&placement);
34380        let struct_literal = AplicacaoError::PlacementWithoutClusters {
34381            estrategia: placement.estrategia(),
34382        };
34383        assert_eq!(lifted, struct_literal);
34384    }
34385
34386    #[test]
34387    fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
34388        // Routing pin: sweep the sole constructor input axis
34389        // (`placement: &Placement`) through every variant in the closed
34390        // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
34391        // re-derivation / off-by-one arm-swap / stale-field read on the
34392        // `placement.estrategia()` sole-field projection surfaces here
34393        // rather than at a downstream diagnostic-shape mismatch. Peer of
34394        // the sibling
34395        // `validate_placement_reads_through_lifted_estrategia_accessor`
34396        // three-consumer coherence pin — extended here onto the ctor
34397        // itself so the accessor-projection posture is byte-witnessed at
34398        // the substrate primitive rather than only at the caller-site
34399        // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
34400        // future addition to the closed accept-set surfaces as an
34401        // exhaustiveness gap on this iteration list.
34402        for estrategia in [
34403            PlacementStrategy::SingleNode,
34404            PlacementStrategy::Replicated,
34405            PlacementStrategy::Sharded,
34406        ] {
34407            let placement = Placement {
34408                estrategia,
34409                clusters: vec![],
34410                affinity: None,
34411                shard_key: None,
34412            };
34413            let built = AplicacaoError::placement_without_clusters(&placement);
34414            match built {
34415                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
34416                    assert_eq!(
34417                        e,
34418                        placement.estrategia(),
34419                        "estrategia slot must thread the caller's `Placement` verbatim \
34420                         through Placement::estrategia() — the ctor reads through the \
34421                         lifted accessor",
34422                    );
34423                    assert_eq!(
34424                        e, estrategia,
34425                        "estrategia slot must byte-equal the fixture-declared variant",
34426                    );
34427                }
34428                other => panic!("expected PlacementWithoutClusters, got {other:?}"),
34429            }
34430        }
34431    }
34432
34433    #[test]
34434    fn placement_without_clusters_ctor_is_const_fn() {
34435        // Fail-before-pass-after pin on
34436        // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
34437        // surface posture. The ctor threads the paired
34438        // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
34439        // return through one `const fn` construction — any future
34440        // accidental downgrade to non-`const` (a `.clone()` on the
34441        // `Copy`-scalar `estrategia:` field expression, an owned-`String`
34442        // materialization on the sibling non-`estrategia:` axis) fails
34443        // `placement_without_clusters_via_const_fn` at caixa-core build
34444        // time with E0015 (`cannot call non-const method`), strictly
34445        // stronger than a runtime `assert!`. Sibling of the peer
34446        // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
34447        // posture on the sibling per-`:politicas` cap-scalar envelopes
34448        // and the peer [`Placement::estrategia`] const-fn accessor pin at
34449        // [`placement_estrategia_accessor_is_const_fn`] on the paired
34450        // substrate primitive.
34451        const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
34452            AplicacaoError::placement_without_clusters(p)
34453        }
34454        let placement = Placement {
34455            estrategia: PlacementStrategy::Sharded,
34456            clusters: vec![],
34457            affinity: None,
34458            shard_key: Some("tenantId".into()),
34459        };
34460        assert_eq!(
34461            placement_without_clusters_via_const_fn(&placement),
34462            AplicacaoError::placement_without_clusters(&placement),
34463        );
34464    }
34465
34466    #[test]
34467    fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
34468        // Equivalence pin: the ctor produces byte-equal
34469        // `AplicacaoError::EntradaMemberMissing` to the pre-lift
34470        // open-coded struct-literal that read the same `:para` value
34471        // through `e.destination().to_string()` at the caller site
34472        // inside [`AplicacaoSpec::validate_entrada`]. Guards any future
34473        // field-addition / reordering / accessor-return tweak on the
34474        // variant. Sibling of the peer
34475        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
34476        // and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
34477        // pins on the sibling per-`:placement` envelope, and sibling of
34478        // the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
34479        // pin on the sibling per-`:membros :caixa` envelope.
34480        let entrada = Entrada {
34481            host: "checkout.quero.cloud".into(),
34482            para: "phantom-shim".into(),
34483            paths: vec!["/api".into()],
34484            port: 8080,
34485        };
34486        let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
34487        let via_literal = AplicacaoError::EntradaMemberMissing {
34488            para: entrada.destination().to_string(),
34489        };
34490        assert_eq!(
34491            via_ctor, via_literal,
34492            "entrada_member_missing(&entrada) must byte-equal the open-coded \
34493             EntradaMemberMissing struct-literal on the same &Entrada fixture"
34494        );
34495        assert_eq!(
34496            via_ctor.to_string(),
34497            via_literal.to_string(),
34498            "Display byte-string must byte-equal the open-coded struct-literal"
34499        );
34500    }
34501
34502    #[test]
34503    fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
34504        // Boundary-sweep pin on the ctor's substrate-primitive
34505        // projection: the `para` slot is stored verbatim from
34506        // [`Entrada::destination`] across a representative set of
34507        // `:entrada :para` byte-strings, so any wrapper-side silent
34508        // normalization, `.into()` divergence, accidental field
34509        // rebrand, or per-arm ctor divergence on the sole-field
34510        // projection surfaces at caixa-core build time rather than at
34511        // a downstream diagnostic consumer that reads `err.para` back
34512        // and gets a different value than the one it stored. Peer of
34513        // the sibling
34514        // `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
34515        // boundary-sweep pin on the sibling per-`:placement :shard-key`
34516        // envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
34517        // sweep on the sibling per-`:placement` empty-clusters envelope
34518        // — extended here onto the [`Entrada`]-borrow-projected sole
34519        // `para` slot on the sibling per-`:entrada :para` envelope. The
34520        // sweep list carries a mixed set (well-shaped phantom, hyphen-
34521        // digit tail, single-character floor, and the digit-start form
34522        // the peer `accepts_canonical_entrada_para_forms` positive-
34523        // control test also sweeps) so a future silent per-input
34524        // normalization surfaces on the arm that diverges.
34525        for para in [
34526            "phantom-shim",
34527            "cart-v2",
34528            "a",
34529            "c0",
34530            "3rd-party-shim",
34531            "x-1-2-3-4",
34532        ] {
34533            let entrada = Entrada {
34534                host: "checkout.quero.cloud".into(),
34535                para: para.into(),
34536                paths: vec!["/api".into()],
34537                port: 8080,
34538            };
34539            let err = AplicacaoError::entrada_member_missing(&entrada);
34540            let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
34541                panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
34542            };
34543            assert_eq!(
34544                stored_para,
34545                entrada.destination(),
34546                "para slot must round-trip verbatim through Entrada::destination() \
34547                 for {para:?}"
34548            );
34549            assert_eq!(
34550                stored_para, para,
34551                "para slot must byte-equal the fixture-declared value for {para:?}"
34552            );
34553        }
34554    }
34555
34556    #[test]
34557    fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
34558        // End-to-end pin: the sole in-crate wire-up site
34559        // (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
34560        // routes through [`AplicacaoError::entrada_member_missing`] and
34561        // the observed `Err` byte-equals the ctor's output on the same
34562        // well-shaped-phantom `:para` fixture. A future silent de-lift
34563        // of the wire-up back to the open-coded struct-literal trips
34564        // this test at caixa-core build time rather than at a
34565        // downstream diagnostic consumer far from the wire-up commit.
34566        // Sibling of the peer
34567        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
34568        // end-to-end pin on the sibling per-`:placement :shard-key`
34569        // envelope, and sibling of the peer
34570        // `entrada_para_well_shaped_phantom_still_raises_member_missing`
34571        // pattern-match pin on the same wire-up — extended here from a
34572        // `matches!` shape check to a byte-identity + Display parity
34573        // route through the ctor.
34574        let mut s = three_member_spec();
34575        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
34576        let observed = s.validate().unwrap_err();
34577        let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
34578        assert_eq!(
34579            observed, expected,
34580            "validate_entrada's phantom-reference-arm Err must byte-equal \
34581             entrada_member_missing(&entrada)"
34582        );
34583        assert_eq!(
34584            observed.to_string(),
34585            expected.to_string(),
34586            "Display byte-string parity"
34587        );
34588    }
34589
34590    #[test]
34591    fn contrato_cycle_ctor_matches_struct_literal_wrap() {
34592        // Equivalence pin: the ctor produces byte-equal
34593        // `AplicacaoError::ContratoCycle` to the pre-lift open-coded
34594        // struct-literal that stored the caller-side reconstructed
34595        // cycle path verbatim at the gray-arm cycle-close return inside
34596        // [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
34597        // field-addition / reordering / re-collect divergence on the
34598        // variant. Sibling of the peer
34599        // `entrada_member_missing_ctor_matches_struct_literal_wrap`
34600        // (deeae5c) pin on the sibling per-`:entrada :para`
34601        // phantom-reference envelope, and sibling of the peer
34602        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
34603        // pin on the sibling per-`:placement` empty-clusters envelope.
34604        let cycle = vec![
34605            "cart".to_string(),
34606            "catalog".to_string(),
34607            "cart".to_string(),
34608        ];
34609        let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
34610        let via_literal = AplicacaoError::ContratoCycle {
34611            cycle: cycle.clone(),
34612        };
34613        assert_eq!(
34614            via_ctor, via_literal,
34615            "contrato_cycle(cycle) must byte-equal the open-coded \
34616             ContratoCycle struct-literal on the same Vec<String> fixture"
34617        );
34618        assert_eq!(
34619            via_ctor.to_string(),
34620            via_literal.to_string(),
34621            "Display byte-string must byte-equal the open-coded struct-literal"
34622        );
34623    }
34624
34625    #[test]
34626    fn contrato_cycle_ctor_routes_path_verbatim() {
34627        // Boundary-sweep pin on the ctor's substrate-primitive
34628        // pass-through: the `cycle` slot is stored verbatim across a
34629        // representative set of reconstructed cycle paths (two-node
34630        // closed loop; three-node loop; long chain with repeated
34631        // interior nodes; a fixture whose first/last coincide by the
34632        // gray-arm's own append-target-once-more discipline), so any
34633        // wrapper-side silent normalization, dedup, sort, `.into()`
34634        // divergence, accidental field rebrand, or re-collect on the
34635        // sole-field pass-through surfaces at caixa-core build time
34636        // rather than at a downstream diagnostic consumer that reads
34637        // `err.cycle` back and gets a different value than the one it
34638        // stored. Peer of the sibling
34639        // `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
34640        // (deeae5c) boundary-sweep pin on the sibling per-`:entrada
34641        // :para` envelope — extended here onto the owned-[`Vec<String>`]
34642        // pass-through on the sibling per-`:contratos` cycle envelope.
34643        for cycle in [
34644            vec![
34645                "cart".to_string(),
34646                "catalog".to_string(),
34647                "cart".to_string(),
34648            ],
34649            vec![
34650                "cart".to_string(),
34651                "catalog".to_string(),
34652                "payment".to_string(),
34653                "cart".to_string(),
34654            ],
34655            vec![
34656                "a".to_string(),
34657                "b".to_string(),
34658                "c".to_string(),
34659                "d".to_string(),
34660                "b".to_string(),
34661            ],
34662            vec!["only".to_string(), "only".to_string()],
34663        ] {
34664            let err = AplicacaoError::contrato_cycle(cycle.clone());
34665            let AplicacaoError::ContratoCycle { cycle: stored } = err else {
34666                panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
34667            };
34668            assert_eq!(
34669                stored, cycle,
34670                "cycle slot must round-trip the caller-side Vec<String> verbatim \
34671                 for {cycle:?}"
34672            );
34673        }
34674    }
34675
34676    #[test]
34677    fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
34678        // End-to-end pin: the sole in-crate wire-up site
34679        // (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
34680        // return) routes through [`AplicacaoError::contrato_cycle`] and
34681        // the observed `Err` byte-equals the ctor's output on the same
34682        // reconstructed cycle path. A future silent de-lift of the
34683        // wire-up back to the open-coded `AplicacaoError::ContratoCycle
34684        // { cycle }` struct-literal trips this test at caixa-core build
34685        // time rather than at a downstream diagnostic consumer far from
34686        // the wire-up commit. Sibling of the peer
34687        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
34688        // (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
34689        // envelope, and sibling of the peer
34690        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
34691        // (14bafca) end-to-end pin on the sibling per-`:placement
34692        // :shard-key` envelope — extended here from a bare
34693        // `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
34694        // check to a byte-identity route through the ctor.
34695        let mut s = three_member_spec();
34696        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
34697        s.contratos = vec![
34698            contract_http("catalog", "cart", "/x"),
34699            contract_http("cart", "payment", "/y"),
34700            contract_http("payment", "catalog", "/z"),
34701        ];
34702        let observed = s.validate().unwrap_err();
34703        let AplicacaoError::ContratoCycle { ref cycle } = observed else {
34704            panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
34705        };
34706        let expected = AplicacaoError::contrato_cycle(cycle.clone());
34707        assert_eq!(
34708            observed, expected,
34709            "detect_sync_cycles's gray-arm Err must byte-equal \
34710             contrato_cycle(cycle) on the reconstructed cycle path"
34711        );
34712        assert_eq!(
34713            observed.to_string(),
34714            expected.to_string(),
34715            "Display byte-string parity"
34716        );
34717    }
34718
34719    // ── policy_breaker_window_below_timeout standalone ctor pins ────────
34720    //
34721    // Fail-before-pass-after pins for the standalone
34722    // [`AplicacaoError::policy_breaker_window_below_timeout`] inherent
34723    // ctor (see the paired doc-block above the ctor definition) — the
34724    // fold of the last open-coded two-slot `{ window: cb.window(),
34725    // timeout: t }` struct-literal inside
34726    // [`MeshPolicy::first_cross_axis_violation`]'s window-below-timeout
34727    // arm onto one substrate primitive on the [`AplicacaoError`]
34728    // envelope, projecting through the [`CircuitBreaker::window`] scalar
34729    // accessor on the substrate primitive. A byte-mismatched ctor body
34730    // would trip the equivalence pin first, ahead of any downstream
34731    // diagnostic-shape drift.
34732    //
34733    // Peer of the sibling standalone-ctor equivalence pins on the peer
34734    // per-envelope substrate-primitive-projection ctors across
34735    // caixa-core: `contrato_self_loop_ctor_matches_struct_literal_wrap`
34736    // (b30edfe) on the sibling `{ caixa: String, wit: String }` two-slot
34737    // per-`:contratos` self-edge envelope,
34738    // `entrada_member_missing_ctor_matches_struct_literal_wrap` (deeae5c)
34739    // on the sibling `{ para: String }` one-slot per-`:entrada :para`
34740    // phantom-reference envelope, and
34741    // `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
34742    // (14bafca) on the sibling `{ estrategia, shard_key }` two-slot
34743    // per-`:placement :shard-key` envelope.
34744
34745    #[test]
34746    fn policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap() {
34747        // Equivalence pin: the ctor produces byte-equal
34748        // `AplicacaoError::PolicyBreakerWindowBelowTimeout` to the pre-
34749        // lift open-coded struct-literal that read the same two fields
34750        // through [`CircuitBreaker::window`] and the paired
34751        // `:politicas :timeout` destructure. Guards any future
34752        // field-addition / reordering / accessor-swap tweak on the
34753        // variant. Same equivalence-pin shape as the sibling
34754        // `contrato_self_loop_ctor_matches_struct_literal_wrap`
34755        // (b30edfe) on the sibling per-`:contratos` self-edge envelope.
34756        let cb = CircuitBreaker {
34757            max_failures: 5,
34758            window: Duration::from_secs(10),
34759        };
34760        let timeout = Duration::from_secs(30);
34761        let via_ctor = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
34762        let via_literal = AplicacaoError::PolicyBreakerWindowBelowTimeout {
34763            window: cb.window(),
34764            timeout,
34765        };
34766        assert_eq!(
34767            via_ctor, via_literal,
34768            "policy_breaker_window_below_timeout(&cb, t) must byte-equal \
34769             the open-coded PolicyBreakerWindowBelowTimeout struct-literal \
34770             on the same Copy-Duration fixture"
34771        );
34772        assert_eq!(
34773            via_ctor.to_string(),
34774            via_literal.to_string(),
34775            "Display byte-string must byte-equal the open-coded struct-literal"
34776        );
34777    }
34778
34779    #[test]
34780    fn policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim() {
34781        // Routing pin sweeping non-default `:circuit-breaker :window`
34782        // and `:timeout` pairs (below-boundary window / above-boundary
34783        // window; sub-second window / multi-minute timeout;
34784        // millisecond-precision fixture) through the paired
34785        // [`CircuitBreaker::window`] accessor and the direct `timeout`
34786        // parameter, so any wrapper-side silent normalization,
34787        // rounding, argument re-order, or accidental slot rebrand on
34788        // the two-slot pass-through surfaces at caixa-core build time
34789        // rather than at a downstream diagnostic consumer that reads
34790        // the two [`Duration`]s back and gets different values than
34791        // the ones it stored.
34792        //
34793        // Deliberately routes through a fixture whose `cb.window` and
34794        // `timeout` are distinct — a silent accessor swap
34795        // (`cb.max_failures` casting to `Duration` would fail to
34796        // compile; a hypothetical field-rename swap swapping the two
34797        // slots at the ctor body would land `timeout` in the `window`
34798        // slot instead of `cb.window()` and vice-versa, tripping the
34799        // per-field assertion here). Peer of the sibling
34800        // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
34801        // (b30edfe) routing pin on the sibling two-slot per-`:contratos`
34802        // envelope.
34803        for (max_failures, window, timeout) in [
34804            (5_u32, Duration::from_secs(10), Duration::from_secs(30)),
34805            (
34806                1_u32,
34807                Duration::from_millis(29_999),
34808                Duration::from_secs(30),
34809            ),
34810            (42_u32, Duration::from_millis(500), Duration::from_secs(120)),
34811            (7_u32, Duration::from_secs(1), Duration::from_secs(60)),
34812        ] {
34813            let cb = CircuitBreaker {
34814                max_failures,
34815                window,
34816            };
34817            let built = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
34818            let AplicacaoError::PolicyBreakerWindowBelowTimeout {
34819                window: stored_window,
34820                timeout: stored_timeout,
34821            } = built
34822            else {
34823                panic!(
34824                    "policy_breaker_window_below_timeout must construct \
34825                     PolicyBreakerWindowBelowTimeout for cb={cb:?}/timeout={timeout:?}"
34826                );
34827            };
34828            assert_eq!(
34829                stored_window, window,
34830                "window slot must thread CircuitBreaker::window() verbatim \
34831                 for cb={cb:?}/timeout={timeout:?}"
34832            );
34833            assert_eq!(
34834                stored_timeout, timeout,
34835                "timeout slot must thread the caller-side :timeout scalar verbatim \
34836                 for cb={cb:?}/timeout={timeout:?}"
34837            );
34838        }
34839    }
34840
34841    #[test]
34842    fn first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor() {
34843        // End-to-end pin: the sole in-crate wire-up site
34844        // ([`MeshPolicy::first_cross_axis_violation`]'s
34845        // window-below-timeout arm) routes through
34846        // [`AplicacaoError::policy_breaker_window_below_timeout`] and
34847        // the observed `Err` byte-equals the ctor's output on the same
34848        // sub-boundary `(:window, :timeout)` fixture. A future silent
34849        // de-lift of the wire-up back to the open-coded
34850        // `AplicacaoError::PolicyBreakerWindowBelowTimeout { window,
34851        // timeout }` struct-literal trips this test at caixa-core build
34852        // time rather than at a downstream diagnostic consumer far from
34853        // the wire-up commit. Sibling of the peer
34854        // `detect_sync_cycles_arm_routes_through_contrato_cycle_ctor`
34855        // (5cfcab8) end-to-end pin on the sibling per-`:contratos`
34856        // cross-edge cycle envelope,
34857        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
34858        // (deeae5c) on the sibling per-`:entrada :para` phantom-
34859        // reference envelope, and
34860        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
34861        // (14bafca) on the sibling per-`:placement :shard-key`
34862        // envelope — extended here from a bare `matches!(err,
34863        // AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })`
34864        // shape check to a byte-identity route through the ctor.
34865        let mut s = three_member_spec();
34866        s.politicas.timeout = Some(Duration::from_secs(30));
34867        s.politicas.circuit_breaker = Some(CircuitBreaker {
34868            max_failures: 5,
34869            window: Duration::from_secs(10),
34870        });
34871        let observed = s.validate().unwrap_err();
34872        let cb = s.politicas.circuit_breaker.unwrap();
34873        let timeout = s.politicas.timeout.unwrap();
34874        let expected = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
34875        assert_eq!(
34876            observed, expected,
34877            "MeshPolicy::first_cross_axis_violation's window-below-timeout \
34878             arm's Err must byte-equal policy_breaker_window_below_timeout(&cb, t)"
34879        );
34880        assert_eq!(
34881            observed.to_string(),
34882            expected.to_string(),
34883            "Display byte-string parity"
34884        );
34885    }
34886}