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, 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
2638/// Route the derived-style [`Default`] impl on [`MeshPolicy`] through
2639/// the substrate-canonical [`MeshPolicy::empty`] `pub const fn`
2640/// constructor rather than the derive-generated per-field
2641/// `<Option<_> as Default>::default` cascade — one source of truth for
2642/// the "canonical unset per-`:politicas` slot" shape across the two
2643/// paths every downstream consumer already reaches through (the
2644/// derived-until-now [`Default::default`] the `..Default::default()`
2645/// struct-update-syntax on every one-axis-under-test fixture in this
2646/// crate's test module rests on, and the `pub const fn`
2647/// [`MeshPolicy::empty`] constructor every `const`-context consumer
2648/// reaches through).
2649///
2650/// Prior to this fold the two paths were byte-equal by *coincidence*
2651/// under the pinning test
2652/// [`tests::mesh_policy_empty_byte_equals_default`] rather than
2653/// byte-equal by *construction* — the derive-generated
2654/// [`Default::default`] resolved each `Option<_>` field through its
2655/// own `<Option<_> as Default>::default` (which returns `None`) and
2656/// the lifted `pub const fn` [`MeshPolicy::empty`] named the same five
2657/// `None` arms verbatim in its struct-literal. Two hand-authored (or
2658/// derive-authored) sources of the same "canonical unset baseline"
2659/// shape on the same primitive is exactly the substrate-canonical-
2660/// source-of-truth duplication the [`crate::LimitsSpec::empty`]
2661/// (9739971) / [`MeshPolicy::empty`] (6df969b) /
2662/// [`crate::BehaviorSpec::empty`] (f9b18e3) lifts closed on the
2663/// forward `const`-context path — extending the same discipline onto
2664/// the paired [`Default`] impl means every consumer of the derived-
2665/// until-now [`Default::default`] surface (every `..Default::default()`
2666/// struct-update-syntax fixture in this crate's test module — the
2667/// five per-axis-only pins at [`tests::mesh_policy_with_only_timeout_is_not_empty`],
2668/// [`tests::mesh_policy_with_only_retries_is_not_empty`],
2669/// [`tests::mesh_policy_with_only_circuit_breaker_is_not_empty`],
2670/// [`tests::mesh_policy_with_only_mtls_required_is_not_empty`],
2671/// [`tests::mesh_policy_with_only_rate_limit_is_not_empty`] — and the
2672/// entry pin at [`tests::mesh_policy_default_is_empty`], the future
2673/// M4 per-edge `:politicas` overlay CR materializer's admission-time
2674/// default-overlay-emit gate, every future `..Default::default()`
2675/// struct-update-syntax fixture-builder arm) also routes through the
2676/// substrate primitive's single source of truth.
2677///
2678/// A future extension of the `:politicas` axis set (a per-edge
2679/// `:politicas` overlay the M4 roadmap grows once per-`:contratos`-
2680/// edge overrides land, a sixth `:politicas` sub-slot the roadmap
2681/// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2682/// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
2683/// reaches this impl's return value through exactly one edit on
2684/// [`MeshPolicy::empty`] — the derived path could silently disagree
2685/// with the constructor's shape on any new field whose
2686/// `Default::default` is not `None` (a future non-`Option<_>` field
2687/// with a non-`Default::default`-equivalent baseline, a `Vec<_>` field
2688/// defaulting to an empty vector, an enum arm-carrying field with a
2689/// non-`Default::default` canonical unset arm), while this delegated
2690/// impl reaches the constructor directly and picks up every future
2691/// extension by construction.
2692///
2693/// Direct peer of [`crate::LimitsSpec`]'s
2694/// [`Default`]-through-[`crate::LimitsSpec::empty`] fold (abd52c2) on
2695/// the M2 `:limits` typed slot — same "one source of truth for the
2696/// canonical unset baseline" discipline extended onto the M3
2697/// `:politicas` typed slot. The sibling [`crate::BehaviorSpec`] impl
2698/// on the M2 `:behavior` slot is the third and last established
2699/// candidate for the same delegation fold once the per-slot peer pin
2700/// on this axis lands in a future run. Pinned load-bearing by
2701/// [`tests::mesh_policy_default_routes_through_empty_ctor`]
2702/// (byte-parity pin against [`MeshPolicy::empty`] under `PartialEq`,
2703/// sharpening the pre-existing
2704/// [`tests::mesh_policy_empty_byte_equals_default`] pin from a "two
2705/// paths byte-equal by coincidence" invariant into a "two paths
2706/// byte-equal by construction — one delegates to the other" invariant)
2707/// and by [`tests::mesh_policy_empty_validates_ok`] (the canonical
2708/// unset baseline must pass [`MeshPolicy::validate`] — every per-axis
2709/// value-shape gate is `if let Some(_)` guarded and every cross-axis
2710/// arm on [`MeshPolicy::first_cross_axis_violation`] is a
2711/// `let (Some(_), Some(_))` pattern, so an all-`None` input
2712/// structurally short-circuits every arm; the pin makes the invariant
2713/// load-bearing so a future extension that adds a non-`Option`-guarded
2714/// gate to [`MeshPolicy::validate`] trips at caixa-core test time
2715/// rather than at a downstream consumer that composed
2716/// [`MeshPolicy::default`]/[`MeshPolicy::empty`] with
2717/// [`MeshPolicy::validate`] as its "no-op axis short-circuit").
2718impl Default for MeshPolicy {
2719    #[inline]
2720    fn default() -> Self {
2721        Self::empty()
2722    }
2723}
2724
2725impl MeshPolicy {
2726    /// Substrate-canonical `const`-context peer of the derived
2727    /// [`Default::default`] on [`MeshPolicy`] — returns the fully-empty
2728    /// per-`:politicas` slot (every one of the five `Option<_>`-carrying
2729    /// per-axis fields set to `None`), materializable at `const`-eval
2730    /// time.
2731    ///
2732    /// Named `empty()` (not `default()` / `new()`) to match the sibling
2733    /// `is_empty()` predicate on the same primitive: the pair
2734    /// (`empty()` / `is_empty()`) forms the round-trip discipline
2735    /// `MeshPolicy::empty().is_empty() == true` the pin
2736    /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
2737    /// locks load-bearing, and every `const`-context consumer that
2738    /// wants a canonical unset baseline reads through this constructor
2739    /// rather than the derived (non-`const`) [`Default::default`] or
2740    /// the five-field struct-literal `MeshPolicy { timeout: None,
2741    /// retries: None, circuit_breaker: None, mtls_required: None,
2742    /// rate_limit: None }` open-coded per-site.
2743    ///
2744    /// Direct peer of [`crate::LimitsSpec::empty`] (9739971) on the
2745    /// M2 `:limits` typed slot — same "`const`-context peer of the
2746    /// derived non-`const` [`Default::default`]" discipline extended
2747    /// onto the M3 `:politicas` typed slot. The two lifted `pub const
2748    /// fn` constructors together now cover the two per-slot
2749    /// [`Default`]-carrying M2/M3 typed slots that also carry an
2750    /// `is_empty()` emptiness predicate: every `const`-context consumer
2751    /// of a canonical unset per-slot baseline reads through the same
2752    /// paired-`(empty(), is_empty())` shape on either slot without a
2753    /// runtime dispatch on the derived [`Default::default`].
2754    ///
2755    /// Prior to this lift the "canonical unset [`MeshPolicy`]" shape
2756    /// was reached through one of two paths — the derived
2757    /// [`Default::default`] (`fn`, not `const fn` — a downstream
2758    /// `const _: MeshPolicy = MeshPolicy::default();` cannot compile
2759    /// because [`Default::default`] is not `const`-stable on stable
2760    /// Rust; the tracking issue on `const Default` still blocks the
2761    /// promotion) or an open-coded struct-literal with five `None`
2762    /// arms threaded verbatim at every call site (the five
2763    /// `MeshPolicy { timeout: Some(_), ..Default::default() }` /
2764    /// `MeshPolicy { retries: Some(_), ..Default::default() }` /
2765    /// sibling per-axis-only fixtures in this crate's own test module
2766    /// each rest on `..Default::default()` for the four peer arms; a
2767    /// future axis addition silently drifts the fixture's intent from
2768    /// "one axis under test, the other four unset" to "one axis under
2769    /// test, N axes unset, one field forgotten"). A future extension
2770    /// of the axis (a per-edge `:politicas` overlay the M4 roadmap
2771    /// grows once per-`:contratos`-edge overrides land, a sixth
2772    /// `:politicas` sub-slot the roadmap
2773    /// [`ABSORPTION-ROADMAP`](https://github.com/pleme-io/theory/blob/main/ABSORPTION-ROADMAP.md)
2774    /// grows past the five-arm Envoy/Cilium-shape §III.2 axis set)
2775    /// reaches this constructor at one edit (one added struct field
2776    /// on the type + one added `<axis>: None` line here) rather than
2777    /// a coordinated rewrite of every open-coded struct-literal at
2778    /// every downstream consumer.
2779    ///
2780    /// `pub const fn` — matches the sibling
2781    /// [`MeshPolicy::is_empty`] `pub const fn` shape verbatim, so
2782    /// every downstream consumer that folds a canonical unset
2783    /// baseline into a `const` position (a `const EMPTY: MeshPolicy =
2784    /// MeshPolicy::empty();` module-scope binding a future per-edge
2785    /// `:politicas` overlay reads through as its "no override
2786    /// declared" arm, a compile-time per-fixture-builder default the
2787    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
2788    /// admission-time default-overlay-emit gate consults, a
2789    /// compile-time lookup table the LSP hover renderer materializes
2790    /// per typed-slot fixture) reads through one `const` dispatch
2791    /// rather than being forced onto the runtime code path. Pinned
2792    /// load-bearing at the substrate-primitive level by
2793    /// [`tests::mesh_policy_empty_is_the_all_none_arm_and_is_empty`]
2794    /// (round-trip pin against [`Self::is_empty`]),
2795    /// [`tests::mesh_policy_empty_byte_equals_default`] (byte-parity
2796    /// pin against the derived [`Default::default`]), and
2797    /// [`tests::mesh_policy_empty_ctor_is_const_fn`] (const-eval-surface
2798    /// pin via `const` binding — any future accidental downgrade to
2799    /// `pub fn` fires E0015 at the binding at caixa-core build time,
2800    /// strictly stronger than a runtime `assert!`).
2801    #[must_use]
2802    pub const fn empty() -> Self {
2803        Self {
2804            timeout: None,
2805            retries: None,
2806            circuit_breaker: None,
2807            mtls_required: None,
2808            rate_limit: None,
2809        }
2810    }
2811
2812    /// True when no `:politicas` axis carries a value — every field is
2813    /// `None`. The same emptiness contract every other M2/M3 typed
2814    /// surface carries ([`crate::LimitsSpec::is_empty`],
2815    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2816    /// typed slot onto a cluster artifact key off this predicate to
2817    /// decide "emit the slot" vs "skip the slot entirely", so an
2818    /// authored-but-unset `:politicas (())` round-trips to a rendered
2819    /// artifact that's structurally identical to one that omits the
2820    /// slot. Lifted as a typed predicate (rather than per-renderer
2821    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2822    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2823    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2824    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2825    /// not a coordinated rewrite of every consumer that's reaching
2826    /// for the emptiness semantic.
2827    #[must_use]
2828    pub const fn is_empty(&self) -> bool {
2829        self.timeout().is_none()
2830            && self.retries().is_none()
2831            && self.circuit_breaker().is_none()
2832            && self.mtls_required().is_none()
2833            && self.rate_limit().is_none()
2834    }
2835
2836    /// Substrate-canonical cross-axis coherence predicate on the
2837    /// `:politicas` slot: does the `:circuit-breaker :window` rolling
2838    /// failure-observation interval span at least one full
2839    /// `:timeout`-bounded call?
2840    ///
2841    /// The first *cross-axis* invariant on the `:politicas` surface —
2842    /// every prior gate ([`AplicacaoSpec::validate_politicas`]'s four
2843    /// zero-floor + canonical-form + cap brackets) validates one axis
2844    /// in isolation, so a `MeshPolicy` whose axes are each individually
2845    /// well-formed could still name a structurally inert pair. The
2846    /// pair `{ timeout: 30s, circuit_breaker: { window: 10s, .. } }`
2847    /// passes every per-axis bracket (30s ≤ [`POLICY_TIMEOUT_MAX`],
2848    /// 10s ≤ [`POLICY_BREAKER_WINDOW_MAX`], both integer-millisecond,
2849    /// both above the zero floor) and is nonetheless a breaker that
2850    /// cannot trip on the failure mode it exists to catch: a call
2851    /// dispatched at t=0 is declared failed at t=30s, by which point
2852    /// the 10s window open at dispatch has rolled twice over, so no
2853    /// window can ever hold even one timeout-derived failure however
2854    /// high the call volume. Envoy's `outlier_detection.interval`
2855    /// carries the identical relation against the per-route request
2856    /// timeout; Hystrix ships the canonical ratio in its defaults
2857    /// (10s `metrics.rollingStats.timeInMilliseconds` against a 1s
2858    /// `execution.isolation.thread.timeoutInMilliseconds`).
2859    ///
2860    /// Vacuously `true` when either axis is absent — a `:politicas`
2861    /// that names only one of the pair declares no relation for the
2862    /// substrate to hold it to (`:timeout` alone is a per-call deadline
2863    /// with no breaker; `:circuit-breaker` alone is a breaker whose
2864    /// failures arrive from the transport's own error signal rather
2865    /// than from a substrate-imposed deadline, so no dispatch-to-report
2866    /// lag is knowable at author time). This is the same
2867    /// "unset means the cluster default applies, not zero" partition
2868    /// [`MeshPolicy::is_empty`] and every per-axis accessor's `None`
2869    /// arm already carry.
2870    ///
2871    /// Lifted as a typed predicate on the substrate primitive rather
2872    /// than open-coded at the validate gate so every downstream
2873    /// consumer of the pair reaches the invariant through one dispatch:
2874    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
2875    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
2876    /// (MESH-COMPOSITION §III.2 #3) that must emit
2877    /// `outlier_detection.interval` and the per-route `timeout` as one
2878    /// coherent Envoy block, the future M4
2879    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
2880    /// webhook, and the future per-`:contratos`-edge `:politicas`
2881    /// override that same roadmap acknowledges — which resolves an
2882    /// *effective* pair per edge (edge-level `:timeout` against the
2883    /// Aplicacao-level `:window`, or vice versa) and so must re-check
2884    /// the relation on a pair neither axis's declaration site can see
2885    /// whole. Naming the invariant once means that resolver folds this
2886    /// predicate over its resolved pair instead of re-deriving the
2887    /// comparison, exactly as the sibling cross-slot
2888    /// [`PlacementStrategy::is_shard_keyed`] predicate names the
2889    /// `:placement`/`:shard-key` relation for its own consumers.
2890    #[must_use]
2891    pub const fn breaker_window_observes_timeout(&self) -> bool {
2892        match (self.timeout(), self.circuit_breaker()) {
2893            (Some(timeout), Some(cb)) => cb.window().as_nanos() >= timeout.as_nanos(),
2894            _ => true,
2895        }
2896    }
2897
2898    /// Substrate-canonical cross-axis coherence predicate on the
2899    /// `:politicas` slot: can the token-bucket rate declared by
2900    /// `:rate-limit` dispatch enough calls inside `:circuit-breaker
2901    /// :window` to reach `:max-failures`?
2902    ///
2903    /// The second cross-axis invariant on the `:politicas` surface —
2904    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2905    /// the `(:timeout, :circuit-breaker :window)` pair, extended onto
2906    /// the `(:rate-limit, :circuit-breaker)` pair. Each axis in the
2907    /// pair is validated in isolation by the per-axis brackets in
2908    /// [`AplicacaoSpec::validate_politicas`] (rate zero-floor + cap,
2909    /// max-failures zero-floor + cap, both windows zero-floor +
2910    /// integer-millisecond + cap, rate-limit window canonical-form),
2911    /// so a `MeshPolicy` whose axes are each individually well-formed
2912    /// can still name a structurally inert pair. The pair
2913    /// `{ rate-limit: "1/h", circuit-breaker: (:max-failures 5 :window
2914    /// "10s") }` passes every per-axis bracket and is nonetheless a
2915    /// breaker that cannot trip on the failure mode it exists to
2916    /// catch: the token bucket admits `rate × (cb.window / rl.window)`
2917    /// = `1 × (10s / 3600s)` ≈ 0 calls per rolling breaker window, so
2918    /// no window can accumulate five failures however catastrophically
2919    /// the upstream is failing. Envoy's
2920    /// `outlier_detection.consecutive_5xx` paired against
2921    /// `local_rate_limit.token_bucket.max_tokens` /
2922    /// `fill_interval` carries the identical relation; every
2923    /// production playbook that pairs the two axes (Envoy, Istio, AWS
2924    /// App Mesh, Kong) recommends sizing the rate at or above the
2925    /// breaker's minimum-request-volume threshold for exactly this
2926    /// reason.
2927    ///
2928    /// The typed test is the integer inequality
2929    /// `rate × cb.window.as_nanos() >= max_failures × rl.window.as_nanos()`
2930    /// (rearranged from `rate × cb.window / rl.window >= max_failures`
2931    /// so no floating-point division mediates the comparison and so
2932    /// the sub-second `rl.window` arms — `"n/s"` = 1s — are treated
2933    /// exactly). Both multiplicands are `saturating_mul`'d into
2934    /// [`u128`] so a struct-literal `MeshPolicy` whose per-axis fields
2935    /// have not yet passed [`AplicacaoSpec::validate_politicas`]
2936    /// (e.g. `rate: u32::MAX, cb_window: Duration::MAX`) does not
2937    /// panic the predicate; a saturated pair collapses to the
2938    /// "vacuously coherent" branch the peer per-axis brackets reject
2939    /// via their own zero-floor / cap arms first.
2940    ///
2941    /// Vacuously `true` when either axis is absent — a `:politicas`
2942    /// that names only one of the pair declares no relation for the
2943    /// substrate to hold it to (`:rate-limit` alone is a per-edge
2944    /// token-bucket declaration with no failure counter to starve;
2945    /// `:circuit-breaker` alone is a rolling-window failure counter
2946    /// whose call rate is unconstrained by the substrate, so no
2947    /// bucket-derived upper bound on calls-per-window is knowable at
2948    /// author time). Same "unset means the cluster default applies,
2949    /// not zero" partition [`MeshPolicy::is_empty`] and the sibling
2950    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2951    /// carry.
2952    ///
2953    /// Lifted as a typed predicate on the substrate primitive rather
2954    /// than open-coded at the validate gate so every downstream
2955    /// consumer of the pair reaches the invariant through one
2956    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
2957    /// below, the future `CiliumClusterwideEnvoyConfig`
2958    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
2959    /// must emit `local_rate_limit.token_bucket.{max_tokens,
2960    /// fill_interval}` alongside `outlier_detection.consecutive_5xx`
2961    /// / `outlier_detection.interval` as one coherent Envoy block,
2962    /// the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
2963    /// materializer's admission webhook, and the future
2964    /// per-`:contratos`-edge `:politicas` override the same roadmap
2965    /// acknowledges — which resolves an *effective* pair per edge
2966    /// (edge-level `:rate-limit` against the Aplicacao-level
2967    /// `:circuit-breaker`, or vice versa) and so must re-check the
2968    /// relation on a pair neither axis's declaration site can see
2969    /// whole. Naming the invariant once means that resolver folds
2970    /// this predicate over its resolved pair instead of re-deriving
2971    /// the comparison, exactly as the sibling cross-axis
2972    /// [`MeshPolicy::breaker_window_observes_timeout`] predicate
2973    /// names the `(:timeout, :window)` relation for its own consumers.
2974    #[must_use]
2975    pub const fn breaker_can_trip_under_rate_limit(&self) -> bool {
2976        match (self.rate_limit(), self.circuit_breaker()) {
2977            (Some(rl), Some(cb)) => {
2978                let calls_per_cb_window =
2979                    (rl.rate() as u128).saturating_mul(cb.window().as_nanos());
2980                let trip_threshold_per_cb_window =
2981                    (cb.max_failures() as u128).saturating_mul(rl.window().as_nanos());
2982                calls_per_cb_window >= trip_threshold_per_cb_window
2983            }
2984            _ => true,
2985        }
2986    }
2987
2988    /// Substrate-canonical cross-axis coherence predicate on the
2989    /// `:politicas` slot: can one client's declared `:retries` all
2990    /// complete before `:circuit-breaker :max-failures` trips the
2991    /// breaker mid-retry?
2992    ///
2993    /// The third cross-axis invariant on the `:politicas` surface —
2994    /// sibling to [`MeshPolicy::breaker_window_observes_timeout`] on
2995    /// the `(:timeout, :circuit-breaker :window)` pair and
2996    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
2997    /// `(:rate-limit, :circuit-breaker)` pair, extended onto the
2998    /// `(:retries, :circuit-breaker :max-failures)` pair. Each axis in
2999    /// the pair is validated in isolation by the per-axis brackets in
3000    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3001    /// max-failures zero-floor + cap), so a `MeshPolicy` whose axes
3002    /// are each individually well-formed can still name a
3003    /// structurally-inert retry policy. The pair
3004    /// `{ :retries 3, :circuit-breaker (:max-failures 3 :window "1s") }`
3005    /// passes every per-axis bracket and is nonetheless a retry
3006    /// policy the substrate cannot honor: one client's initial attempt
3007    /// plus three retries is four attempts, but the breaker trips on
3008    /// the third failure — the fourth attempt (the last declared
3009    /// retry) is blocked by the open breaker, so the substrate
3010    /// declared four attempts and structurally allows three.
3011    ///
3012    /// The typed test is the integer inequality
3013    /// `cb.max_failures() > retries` — the retries count is the
3014    /// *number of retry attempts beyond the initial* (Envoy's
3015    /// `retry_policy.num_retries` semantics), so a client makes at
3016    /// most `retries + 1` attempts per client call, each of which may
3017    /// fail. For the breaker to *admit* the retry policy through
3018    /// completion, its trip threshold must not be reached by one
3019    /// client's failures alone: `retries + 1 <= max_failures`,
3020    /// equivalently `retries < max_failures`, equivalently
3021    /// `max_failures > retries`. The boundary case
3022    /// `max_failures == retries + 1` accepts (the R+1th failure — the
3023    /// last retry — trips the breaker exactly as it completes; retries
3024    /// are fully executed). The strict-below case
3025    /// `max_failures <= retries` rejects (the breaker trips before
3026    /// retries exhaust, silently truncating the declared retry policy
3027    /// mid-run — the same declared-but-structurally-inert footgun the
3028    /// sibling per-axis cap arms close on the single-axis surfaces).
3029    ///
3030    /// Vacuously `true` when either axis is absent — a `:politicas`
3031    /// that names only one of the pair declares no relation for the
3032    /// substrate to hold it to (`:retries` alone is a client-retry
3033    /// policy with no failure counter to trip; `:circuit-breaker`
3034    /// alone is a failure counter whose per-client attempt count is
3035    /// unconstrained by the substrate, so no per-client saturation
3036    /// bound on failures-per-client-call is knowable at author time).
3037    /// Same "unset means the cluster default applies, not zero"
3038    /// partition [`MeshPolicy::is_empty`] and the sibling
3039    /// [`MeshPolicy::breaker_window_observes_timeout`] /
3040    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
3041    /// carry.
3042    ///
3043    /// Lifted as a typed predicate on the substrate primitive rather
3044    /// than open-coded at the validate gate so every downstream
3045    /// consumer of the pair reaches the invariant through one
3046    /// dispatch: the [`AplicacaoSpec::validate_politicas`] gate
3047    /// below, the future `CiliumClusterwideEnvoyConfig`
3048    /// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) that
3049    /// must emit `retry_policy.num_retries` alongside
3050    /// `outlier_detection.consecutive_5xx` as one coherent Envoy
3051    /// block, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3052    /// materializer's admission webhook, and the future
3053    /// per-`:contratos`-edge `:politicas` override the same roadmap
3054    /// acknowledges — which resolves an *effective* pair per edge
3055    /// (edge-level `:retries` against the Aplicacao-level
3056    /// `:circuit-breaker`, or vice versa) and so must re-check the
3057    /// relation on a pair neither axis's declaration site can see
3058    /// whole. Naming the invariant once means that resolver folds
3059    /// this predicate over its resolved pair instead of re-deriving
3060    /// the comparison, exactly as the sibling cross-axis
3061    /// [`MeshPolicy::breaker_window_observes_timeout`] and
3062    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
3063    /// name the `(:timeout, :window)` and `(:rate-limit,
3064    /// :circuit-breaker)` relations for their own consumers.
3065    #[must_use]
3066    pub const fn retries_fit_under_breaker_trip_threshold(&self) -> bool {
3067        match (self.retries(), self.circuit_breaker()) {
3068            (Some(retries), Some(cb)) => cb.max_failures() > retries,
3069            _ => true,
3070        }
3071    }
3072
3073    /// Substrate-canonical cross-axis coherence predicate on the
3074    /// `:politicas` slot: does the `:rate-limit` token-bucket capacity
3075    /// admit one client's full `:retries + 1` attempt burst inside a
3076    /// single refill window?
3077    ///
3078    /// The fourth cross-axis invariant on the `:politicas` surface,
3079    /// completing the triangle of pairs the three sibling gates carve
3080    /// out — sibling to [`MeshPolicy::breaker_window_observes_timeout`]
3081    /// on the `(:timeout, :circuit-breaker :window)` pair,
3082    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on the
3083    /// `(:rate-limit, :circuit-breaker)` pair, and
3084    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on the
3085    /// `(:retries, :circuit-breaker :max-failures)` pair, extended onto
3086    /// the `(:retries, :rate-limit)` pair — the last cross-axis relation
3087    /// among the three scalar `:politicas` axes (`:retries`,
3088    /// `:rate-limit`, `:circuit-breaker`) whose axis-triple defines the
3089    /// coherence surface every production overlay (Envoy, Istio,
3090    /// resilience4j, AWS App Mesh) resolves as one block. Each axis in
3091    /// the pair is validated in isolation by the per-axis brackets in
3092    /// [`AplicacaoSpec::validate_politicas`] (retries zero-floor + cap,
3093    /// rate zero-floor + cap, window canonical-form), so a `MeshPolicy`
3094    /// whose axes are each individually well-formed can still name a
3095    /// structurally-truncated retry policy the rate limiter refuses to
3096    /// admit. The pair `{ :retries 5, :rate-limit "3/s" }` passes every
3097    /// per-axis bracket and is nonetheless a retry policy the substrate
3098    /// cannot honor: one client's initial attempt plus five retries is
3099    /// six attempts, but the token bucket admits at most three tokens
3100    /// per one-second refill window, so the fourth attempt onward is
3101    /// blocked by the rate limiter itself — the substrate declared six
3102    /// attempts and structurally allows three. Envoy's
3103    /// `local_rate_limit.token_bucket.max_tokens` paired against
3104    /// `retry_policy.num_retries` carries the identical relation; every
3105    /// production playbook that pairs the two axes recommends sizing
3106    /// the bucket capacity above any single client's retry budget so
3107    /// the retry policy is not silently truncated by the same rate
3108    /// limiter it feeds through.
3109    ///
3110    /// The typed test is the integer inequality
3111    /// `rl.rate() >= retries + 1` — the retries count is the *number of
3112    /// retry attempts beyond the initial* (Envoy's
3113    /// `retry_policy.num_retries` semantics), so a client makes at most
3114    /// `retries + 1` attempts per client call, each of which consumes
3115    /// one token from the local rate-limit bucket. For the bucket to
3116    /// *admit* the retry burst without dropping tokens, its capacity
3117    /// must not be reached by one client's attempts alone:
3118    /// `retries + 1 <= rate`, equivalently `rate >= retries + 1`. The
3119    /// boundary case `rate == retries + 1` accepts (the bucket admits
3120    /// exactly one client's full retry sequence per refill window —
3121    /// retries fully executed). The strict-below case `rate <= retries`
3122    /// rejects (the bucket exhausts before retries complete, silently
3123    /// truncating the declared retry policy mid-run — the same
3124    /// declared-but-structurally-inert footgun the sibling per-axis cap
3125    /// arms close on the single-axis surfaces). The equivalent
3126    /// coherent-direction form `rl.rate() > retries` sidesteps the
3127    /// `retries + 1` addition entirely (both `rate` and `retries` are
3128    /// `u32`; the `>` comparison is total on the type with no overflow
3129    /// against past-the-guard struct-literal `retries` values a caller
3130    /// might pass before `validate` runs), matching the peer
3131    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] direct-
3132    /// `>`-comparison discipline on the sibling
3133    /// `(:retries, :max-failures)` pair.
3134    ///
3135    /// Vacuously `true` when either axis is absent — a `:politicas`
3136    /// that names only one of the pair declares no relation for the
3137    /// substrate to hold it to (`:retries` alone is a client-retry
3138    /// policy with no rate limiter to saturate; `:rate-limit` alone is
3139    /// a token-bucket declaration whose per-client attempt count is
3140    /// unconstrained by the substrate, so no per-client saturation
3141    /// bound on tokens-per-client-call is knowable at author time).
3142    /// Same "unset means the cluster default applies, not zero"
3143    /// partition [`MeshPolicy::is_empty`] and the three sibling
3144    /// cross-axis predicates
3145    /// ([`MeshPolicy::breaker_window_observes_timeout`],
3146    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`],
3147    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]) carry.
3148    ///
3149    /// Lifted as a typed predicate on the substrate primitive rather
3150    /// than open-coded at the validate gate so every downstream
3151    /// consumer of the pair reaches the invariant through one dispatch:
3152    /// the [`AplicacaoSpec::validate_politicas`] gate below, the future
3153    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3154    /// (MESH-COMPOSITION §III.2 #3) that must emit
3155    /// `local_rate_limit.token_bucket.max_tokens` alongside
3156    /// `retry_policy.num_retries` as one coherent Envoy block, the
3157    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3158    /// admission webhook, and the future per-`:contratos`-edge
3159    /// `:politicas` override the same roadmap acknowledges — which
3160    /// resolves an *effective* pair per edge (edge-level `:retries`
3161    /// against the Aplicacao-level `:rate-limit`, or vice versa) and
3162    /// so must re-check the relation on a pair neither axis's
3163    /// declaration site can see whole. Naming the invariant once means
3164    /// that resolver folds this predicate over its resolved pair
3165    /// instead of re-deriving the comparison, exactly as the three
3166    /// sibling cross-axis predicates name the
3167    /// `(:timeout, :window)` / `(:rate-limit, :circuit-breaker)` /
3168    /// `(:retries, :max-failures)` relations for their own consumers,
3169    /// closing the fourth and last cross-axis relation on the scalar
3170    /// `:politicas` axis-triple.
3171    #[must_use]
3172    pub const fn rate_limit_admits_retry_burst(&self) -> bool {
3173        match (self.retries(), self.rate_limit()) {
3174            (Some(retries), Some(rl)) => rl.rate() > retries,
3175            _ => true,
3176        }
3177    }
3178
3179    /// Substrate-canonical fold over the four cross-axis coherence
3180    /// predicates on the `:politicas` slot — returns the *first*
3181    /// cross-axis violation (as its [`AplicacaoError`] variant) in the
3182    /// canonical "more-foundational-cross-axis first" ordering
3183    /// [`MeshPolicy::breaker_window_observes_timeout`] on
3184    /// `(:timeout, :circuit-breaker :window)` →
3185    /// [`MeshPolicy::breaker_can_trip_under_rate_limit`] on
3186    /// `(:rate-limit, :circuit-breaker)` →
3187    /// [`MeshPolicy::retries_fit_under_breaker_trip_threshold`] on
3188    /// `(:retries, :circuit-breaker :max-failures)` →
3189    /// [`MeshPolicy::rate_limit_admits_retry_burst`] on `(:retries,
3190    /// :rate-limit)`. Returns `None` when every cross-axis relation
3191    /// holds (the vacuous shape [`MeshPolicy::is_empty`] and the fully-
3192    /// coherent shape both land here).
3193    ///
3194    /// The ordering discipline this method encodes was open-coded four
3195    /// times at [`AplicacaoSpec::validate_politicas`] — each cross-axis
3196    /// gate was an `if !<predicate>() { let <a> = self.<axis>().expect(
3197    /// "cross-axis gate fires only when :<axis> is present"); let <b>
3198    /// = self.<axis>().expect(…); return Err(<variant>) }` block whose
3199    /// axis-fetch step depended on the predicate having just returned
3200    /// `false` (structurally guaranteed both paired axes are `Some`,
3201    /// but the compiler cannot see through the predicate body, so
3202    /// every arm re-called the accessor with `.expect(…)` to reach
3203    /// the axis it just tested). Two unsound consequences: (1) the
3204    /// validate gate carried eight `.expect(…)` panic call sites the
3205    /// predicate contract already forbids on every well-typed input
3206    /// but the type system does not enforce; (2) the
3207    /// "which-cross-axis-fires-first-when-two-apply" contract lived
3208    /// twice — once in each predicate's own doc comments and once at
3209    /// the validate call site's four-arm cascade. Lifting the four-arm
3210    /// cascade onto this substrate primitive collapses both
3211    /// duplications: the predicate contract and the axis-fetch step
3212    /// live in the same body (no `.expect(…)` — the pattern match at
3213    /// each arm rebinds the paired axes so their `Some` presence is a
3214    /// compile-time property of the local scope), and the ordering
3215    /// discipline lives once at the top of the primitive rather than
3216    /// scattered across four sibling doc-comment blocks that must
3217    /// stay in lockstep.
3218    ///
3219    /// Every downstream cross-axis consumer (the [`AplicacaoSpec::
3220    /// validate_politicas`] gate below, the future M4 `mesh.pleme.io/
3221    /// v1alpha1/Aplicacao` CR materializer's admission webhook, the
3222    /// per-`:contratos`-edge `:politicas` override MESH-COMPOSITION
3223    /// §III.2 #3 acknowledges — the last of which resolves an
3224    /// *effective* per-edge pair and must emit *the same* diagnostic
3225    /// on the same paired-axis input as `feira build`) reaches through
3226    /// one call rather than re-inlining the four pattern-matches +
3227    /// accessor-fetches + variant-constructions + ordering-cascade.
3228    ///
3229    /// Returns owned copies of every axis carried into the diagnostic:
3230    /// [`Duration`] and [`u32`] are `Copy`, so no `String` allocation
3231    /// occurs on the happy path when no violation fires.
3232    #[must_use]
3233    pub fn first_cross_axis_violation(&self) -> Option<AplicacaoError> {
3234        // Ordering discipline this fold encodes matches the four
3235        // per-arm predicate doc comments' pairwise-ordering contract:
3236        // window-below-timeout wins over every arm that names `:rate-
3237        // limit` or `:retries` (its diagnostic is more self-locating —
3238        // the pair is a per-call-deadline invariant every synchronous
3239        // edge carries whether or not `:rate-limit`/`:retries` is
3240        // declared); the starve arm wins over the two retry arms (its
3241        // diagnostic reasons across the token-bucket-vs-breaker
3242        // relation, an axis the retry arms do not touch); the
3243        // retries-saturate arm wins over the retries-burst arm (its
3244        // diagnostic reasons across the per-client-vs-breaker
3245        // relation, which carries whether or not `:rate-limit` is
3246        // declared). Each arm rebinds the paired axes through the
3247        // pattern match, so the `.expect(…)` panics the four-block
3248        // cascade at `validate_politicas` carried collapse to no-op
3249        // pattern rebindings the compiler statically proves exhaust.
3250        if let (Some(t), Some(cb)) = (self.timeout(), self.circuit_breaker())
3251            && !self.breaker_window_observes_timeout()
3252        {
3253            return Some(AplicacaoError::policy_breaker_window_below_timeout(&cb, t));
3254        }
3255        if let (Some(rl), Some(cb)) = (self.rate_limit(), self.circuit_breaker())
3256            && !self.breaker_can_trip_under_rate_limit()
3257        {
3258            return Some(AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(
3259                &rl, &cb,
3260            ));
3261        }
3262        if let (Some(retries), Some(cb)) = (self.retries(), self.circuit_breaker())
3263            && !self.retries_fit_under_breaker_trip_threshold()
3264        {
3265            return Some(
3266                AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb),
3267            );
3268        }
3269        if let (Some(retries), Some(rl)) = (self.retries(), self.rate_limit())
3270            && !self.rate_limit_admits_retry_burst()
3271        {
3272            return Some(AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(
3273                retries, &rl,
3274            ));
3275        }
3276        None
3277    }
3278
3279    /// Substrate-canonical compound entry gate over the whole
3280    /// `:politicas` typed slot — folds every per-axis bracket
3281    /// (`:timeout` / `:retries` / `:circuit-breaker :max-failures` /
3282    /// `:circuit-breaker :window` / `:rate-limit` rate / `:rate-limit`
3283    /// window-canonical-form) *and* the compound cross-axis fold
3284    /// [`MeshPolicy::first_cross_axis_violation`] into one call every
3285    /// consumer of a validated [`MeshPolicy`] reaches through.
3286    ///
3287    /// Returns the first violation as its [`AplicacaoError`] variant,
3288    /// or `Ok(())` when every per-axis value lies in its accept-set and
3289    /// every cross-axis relation holds. Per-axis brackets run strictly
3290    /// before the cross-axis fold — the sibling
3291    /// [`AplicacaoSpec::validate_politicas`] gate carried the same
3292    /// ordering discipline for the same reason: a per-axis
3293    /// structurally-invalid value (a `Duration::ZERO` `:window`, an
3294    /// above-cap `:rate-limit` rate) surfaces its own self-locating
3295    /// diagnostic first, ahead of any cross-axis arm that would send
3296    /// the author to reconcile two values one of which is not a
3297    /// meaningful window at all. Within the per-axis phase, arms fire
3298    /// in the same slot-order the peer per-axis brackets carry
3299    /// (`:timeout` → `:retries` → `:circuit-breaker` → `:rate-limit`,
3300    /// each internally ordered zero-floor before canonical-form before
3301    /// cap by [`crate::render::require_positive_bounded_u32`] /
3302    /// [`crate::render::require_positive_canonical_bounded_duration`]);
3303    /// within the cross-axis phase, arms fire in the canonical
3304    /// more-foundational-cross-axis-first ordering
3305    /// [`MeshPolicy::first_cross_axis_violation`] encodes.
3306    ///
3307    /// Lifted as a typed method on the substrate primitive so every
3308    /// downstream consumer of a validated [`MeshPolicy`] reaches the
3309    /// invariant through one dispatch: the
3310    /// [`AplicacaoSpec::validate_politicas`] gate below (whose whole
3311    /// body collapses to `self.politicas().validate()`), the future
3312    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3313    /// admission webhook, the future per-`:contratos`-edge `:politicas`
3314    /// override MESH-COMPOSITION §III.2 #3 acknowledges — the last of
3315    /// which resolves an *effective* per-edge [`MeshPolicy`] and must
3316    /// emit *the same* diagnostic on the same input as `feira build`.
3317    /// Naming the compound gate once on the substrate primitive means
3318    /// every downstream consumer inherits both the per-axis brackets
3319    /// *and* the cross-axis fold through one call, rather than
3320    /// re-inlining the four-per-axis + one-cross-axis cascade in
3321    /// lockstep with `validate_politicas`.
3322    ///
3323    /// Peer of the per-kind compound entry gates lifted at
3324    /// [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
3325    /// [`crate::render::require_supervisor_view`] (8d8a5c3), and
3326    /// [`crate::render::require_v0_servico_shape`] on the per-Caixa
3327    /// layout axis, and the sibling compound cross-axis fold
3328    /// [`MeshPolicy::first_cross_axis_violation`] on the same
3329    /// `:politicas` axis — extended here onto the per-slot per-axis +
3330    /// cross-axis compound entry gate that folds both surfaces.
3331    pub fn validate(&self) -> Result<(), AplicacaoError> {
3332        if let Some(t) = self.timeout() {
3333            crate::render::require_positive_canonical_bounded_duration(
3334                t,
3335                POLICY_TIMEOUT_MAX,
3336                || AplicacaoError::PolicyTimeoutZero,
3337                AplicacaoError::policy_timeout_not_canonical,
3338                AplicacaoError::policy_timeout_exceeds_cap,
3339            )?;
3340        }
3341        if let Some(r) = self.retries() {
3342            crate::render::require_positive_bounded_u32(
3343                r,
3344                POLICY_RETRIES_MAX,
3345                || AplicacaoError::PolicyRetriesZero,
3346                AplicacaoError::policy_retries_exceeds_cap,
3347            )?;
3348        }
3349        if let Some(cb) = self.circuit_breaker() {
3350            crate::render::require_positive_bounded_u32(
3351                cb.max_failures(),
3352                POLICY_BREAKER_MAX_FAILURES_MAX,
3353                || AplicacaoError::PolicyBreakerZeroFailures,
3354                AplicacaoError::policy_breaker_max_failures_exceeds_cap,
3355            )?;
3356            crate::render::require_positive_canonical_bounded_duration(
3357                cb.window(),
3358                POLICY_BREAKER_WINDOW_MAX,
3359                || AplicacaoError::PolicyBreakerZeroWindow,
3360                AplicacaoError::policy_breaker_window_not_canonical,
3361                AplicacaoError::policy_breaker_window_exceeds_cap,
3362            )?;
3363        }
3364        if let Some(rl) = self.rate_limit() {
3365            crate::render::require_positive_bounded_u32(
3366                rl.rate(),
3367                POLICY_RATE_LIMIT_MAX,
3368                || AplicacaoError::PolicyRateLimitZero,
3369                AplicacaoError::policy_rate_limit_exceeds_cap,
3370            )?;
3371            if rl.canonical_unit().is_none() {
3372                return Err(AplicacaoError::policy_rate_limit_window_not_canonical(
3373                    rl.window(),
3374                ));
3375            }
3376        }
3377        if let Some(err) = self.first_cross_axis_violation() {
3378            return Err(err);
3379        }
3380        Ok(())
3381    }
3382
3383    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
3384    /// per-call-deadline scalar accessor every consumer of the
3385    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
3386    /// returns the author-declared `:politicas :timeout` typed
3387    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
3388    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
3389    /// is `Copy`, so the accessor returns by value; no borrow of
3390    /// `&self` past the call). `None` when the slot is absent (the
3391    /// "cluster default applies — typically the gateway class's
3392    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
3393    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
3394    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
3395    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
3396    /// round-trips to a rendered `HTTPRoute` structurally identical to
3397    /// one that omits the slot).
3398    ///
3399    /// The `:politicas :timeout` slot carries the "no infinite blocking"
3400    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
3401    /// the typed slot's `Option<Duration>` accept-set (zero-floor
3402    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
3403    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
3404    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
3405    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
3406    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
3407    /// Every downstream consumer that reads the per-call cap keys off
3408    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3409    /// renderers key off to decide "emit :politicas overlay" vs "skip
3410    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3411    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
3412    /// fans the deadline into every rule via
3413    /// [`crate::render::single_field_overlay`], the future M4 per-
3414    /// Aplicacao Gateway API reconciler materialization pass, the
3415    /// future per-`:contratos`-edge timeout-override overlay the
3416    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
3417    ///
3418    /// Prior to this lift the `.timeout` field was accessed inline at
3419    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
3420    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
3421    /// …)` call — two open-coded field-accesses that expressed no
3422    /// compile-time link back to the typed slot. A future extension of
3423    /// the `:politicas :timeout` axis to a richer author surface — a
3424    /// per-`:contratos`-edge timeout override the operator pins through
3425    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
3426    /// roadmap acknowledges, a per-cluster timeout-default overlay the
3427    /// M4 CR materializer resolves per-CR, a split of the single
3428    /// per-call `Duration` into a richer `{request, backendRequest}`
3429    /// pair once the Gateway API's per-rule `timeouts` block grows the
3430    /// upstream-facing backendRequest arm alongside the client-facing
3431    /// request arm — would have had to be threaded through both open-
3432    /// coded copies in lockstep or the emptiness predicate and the
3433    /// caixa-mesh emit path would silently disagree on which per-call
3434    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
3435    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
3436    /// == false` while the renderer's overlay-emit path silently read
3437    /// a drifted other value, or vice versa: an author's `:timeout
3438    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
3439    /// the emptiness predicate still classified the policy as non-
3440    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
3441    /// | grep -A2 timeouts` audit would land on a route whose author's
3442    /// typed slot value silently vanished at the renderer layer).
3443    /// Lifting the resolution to a typed method on the substrate
3444    /// primitive means every downstream consumer of the Aplicacao's
3445    /// per-`:politicas` deadline surface reaches for exactly one typed
3446    /// dispatch — the resolver's accept-set migrates as a unit on any
3447    /// future axis addition.
3448    ///
3449    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
3450    /// family (sibling of the peer per-`:politicas`
3451    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
3452    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
3453    /// `Option<bool>` accessor — same "one typed dispatch on the
3454    /// substrate primitive, thin projections at each consumer"
3455    /// discipline extended onto the peer per-`:politicas` typed-
3456    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
3457    /// numeric-Copy-T scalar" projection pattern the sibling
3458    /// `Option<u32>` / `Option<bool>` lifts opened, since every
3459    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
3460    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
3461    /// than a scalar). Named `timeout()` to match the storage field's
3462    /// name; the accessor's identity maps onto the canonical MESH-
3463    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
3464    #[must_use]
3465    pub const fn timeout(&self) -> Option<Duration> {
3466        self.timeout
3467    }
3468
3469    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
3470    /// retry-budget scalar accessor every consumer of the Aplicacao's
3471    /// Gateway API v1.x per-rule retry-cap keys off — returns the
3472    /// author-declared `:politicas :retries` typed `u32` verbatim as an
3473    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
3474    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
3475    /// value; no borrow of `&self` past the call). `None` when the slot
3476    /// is absent (the "cluster default applies — typically 'no retries
3477    /// beyond a single dispatch attempt'" arm the caixa-mesh
3478    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
3479    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
3480    /// this predicate too, so an authored-but-unset `:politicas
3481    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
3482    /// identical to one that omits the slot).
3483    ///
3484    /// The `:politicas :retries` slot carries the "transient failure
3485    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
3486    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
3487    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3488    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
3489    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
3490    /// count scalar the caixa-mesh `retry_overlay` builder writes.
3491    /// Every downstream consumer that reads the retry cap keys off this
3492    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
3493    /// renderers key off to decide "emit :politicas overlay" vs "skip
3494    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
3495    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
3496    /// the value into every rule via [`crate::render::single_field_overlay`],
3497    /// the future M4 per-Aplicacao Gateway API reconciler
3498    /// materialization pass, the future per-`:contratos`-edge retry-
3499    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
3500    /// acknowledges).
3501    ///
3502    /// Prior to this lift the `.retries` field was accessed inline at
3503    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
3504    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
3505    /// …)` call — two open-coded field-accesses that expressed no
3506    /// compile-time link back to the typed slot. A future extension of
3507    /// the `:politicas :retries` axis to a richer author surface — a
3508    /// per-`:contratos`-edge retry override the operator pins through a
3509    /// future `:contratos :retries` slot, a per-cluster retry-default
3510    /// overlay the M4 CR materializer resolves per-CR, a promotion of
3511    /// the plain `u32` attempt-count to a richer `{attempts, codes,
3512    /// backoff}` sub-block once the Gateway API grows the peer
3513    /// `retry.codes` / `retry.backoff` axes — would have had to be
3514    /// threaded through both open-coded copies in lockstep or the
3515    /// emptiness predicate and the caixa-mesh emit path would silently
3516    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
3517    /// (a `:politicas` block whose only axis is a `Some :retries` would
3518    /// satisfy `is_empty() == false` while the renderer's overlay-emit
3519    /// path silently read a drifted other value, or vice versa: an
3520    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
3521    /// block while the emptiness predicate still classified the policy
3522    /// as non-empty). Lifting the resolution to a typed method on the
3523    /// substrate primitive means every downstream consumer of the
3524    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
3525    /// one typed dispatch — the resolver's accept-set migrates as a
3526    /// unit on any future axis addition.
3527    ///
3528    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
3529    /// family (sibling of the peer per-`:politicas`
3530    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
3531    /// same "one typed dispatch on the substrate primitive, thin
3532    /// projections at each consumer" discipline extended onto the
3533    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
3534    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
3535    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
3536    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
3537    /// fold on). Named `retries()` to match the storage field's name;
3538    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
3539    /// §III.2 vocabulary the slot's docstring already carries.
3540    #[must_use]
3541    pub const fn retries(&self) -> Option<u32> {
3542        self.retries
3543    }
3544
3545    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
3546    /// enforcement-toggle scalar accessor every consumer of the
3547    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
3548    /// — returns the author-declared `:politicas :mtls-required` typed
3549    /// bool verbatim as an `Option<bool>`, copied out of the typed
3550    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
3551    /// the accessor returns by value; no borrow of `&self` past the
3552    /// call). `None` when the slot is absent (the "cluster default
3553    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
3554    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
3555    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
3556    /// this predicate too, so an authored-but-unset `:politicas
3557    /// (:mtls-required ())` round-trips to a rendered
3558    /// `CiliumNetworkPolicy` structurally identical to one that omits
3559    /// the slot).
3560    ///
3561    /// The `:politicas :mtls-required` slot carries the "explicit opt-
3562    /// out only, sandboxing-by-default" mTLS-enforcement toggle
3563    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
3564    /// `{None, Some(true), Some(false)}` accept-set maps onto the
3565    /// Cilium `authentication.mode` bijection through
3566    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
3567    /// handshake enforced), `Some(false) → "disabled"` (handshake
3568    /// skipped — the debug-edge opt-out), `None` → omit the block
3569    /// (cluster default applies). Every downstream consumer that
3570    /// reads the toggle keys off this scalar (the
3571    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3572    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3573    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
3574    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
3575    /// ingress rule via [`crate::render::single_field_overlay`], the
3576    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
3577    /// materialization pass, the future per-`:contratos`-edge mTLS
3578    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3579    ///
3580    /// Prior to this lift the `.mtls_required` field was accessed
3581    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3582    /// `self.mtls_required.is_none()` arm and caixa-mesh's
3583    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
3584    /// two open-coded field-accesses that expressed no compile-time
3585    /// link back to the typed slot. A future extension of the
3586    /// `:politicas :mtls-required` axis to a richer author surface —
3587    /// a per-`:contratos`-edge mTLS override the operator pins through
3588    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
3589    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
3590    /// M4 CR materializer resolves per-CR, a three-valued
3591    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
3592    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
3593    /// would have had to be threaded through both open-coded copies in
3594    /// lockstep or the emptiness predicate and the caixa-mesh emit
3595    /// path would silently disagree on which toggle a given
3596    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
3597    /// axis is a `Some`
3598    /// `:mtls-required` would satisfy `is_empty() == false` while the
3599    /// renderer's overlay-emit path silently read a drifted other
3600    /// value, or vice versa). Lifting the resolution to a typed method
3601    /// on the substrate primitive means every downstream consumer of
3602    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
3603    /// for exactly one typed dispatch — the resolver's accept-set
3604    /// migrates as a unit on any future axis addition.
3605    ///
3606    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
3607    /// family (peer of the sibling per-`:placement`
3608    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
3609    /// same "one typed dispatch on the substrate primitive, thin
3610    /// projections at each consumer" discipline extended onto the
3611    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
3612    /// the "optional per-slot Copy-T scalar" projection pattern the
3613    /// sibling per-`:politicas` `:retries` (Option<u32>) /
3614    /// `:timeout` (Option<Duration>) future lifts fold on). Named
3615    /// `mtls_required()` to match the storage field's name; the
3616    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3617    /// §III.2 vocabulary the slot's docstring already carries.
3618    #[must_use]
3619    pub const fn mtls_required(&self) -> Option<bool> {
3620        self.mtls_required
3621    }
3622
3623    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
3624    /// `local_rate_limit`-mesh token-bucket-declaration scalar
3625    /// accessor every consumer of the Aplicacao's per-`:politicas`
3626    /// per-`(rate, window)` rate-limit surface keys off — returns the
3627    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
3628    /// verbatim as an `Option<RateLimit>`, copied out of the typed
3629    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
3630    /// `Copy`, so the accessor returns by value; no borrow of `&self`
3631    /// past the call). `None` when the slot is absent (the "cluster
3632    /// default applies — typically 'no per-Aplicacao rate declaration,
3633    /// gateway-class per-listener default applies'" arm the future
3634    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
3635    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
3636    /// `rate_limit().is_none()` arm reads this predicate too, so an
3637    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
3638    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
3639    /// identical to one that omits the slot).
3640    ///
3641    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
3642    /// token-bucket rate declaration" contract (MESH-COMPOSITION
3643    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
3644    /// (rate lower-bounded by 1 through
3645    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
3646    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
3647    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
3648    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
3649    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
3650    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
3651    /// `:politicas` overlay emits. Every downstream consumer that
3652    /// reads the rate declaration keys off this scalar (the
3653    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3654    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3655    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
3656    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
3657    /// `rl.window` against [`is_canonical_rate_limit_window`], the
3658    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
3659    /// the future per-`:contratos`-edge rate-limit override the
3660    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3661    ///
3662    /// Prior to this lift the `.rate_limit` field was accessed inline
3663    /// at two sites — [`MeshPolicy::is_empty`]'s
3664    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
3665    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
3666    /// field-accesses that expressed no compile-time link back to the
3667    /// typed slot. A future extension of the `:politicas :rate-limit`
3668    /// axis to a richer author surface — a per-`:contratos`-edge
3669    /// rate-limit override the operator pins through a future
3670    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
3671    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
3672    /// the M4 CR materializer resolves per-CR, a promotion of the
3673    /// plain `(rate, window)` scalar pair to a richer
3674    /// `{rate, window, burst, key}` sub-block once Envoy's
3675    /// `local_rate_limit` grows the peer `burst_size` /
3676    /// `descriptor_key` axes — would have had to be threaded through
3677    /// both open-coded copies in lockstep or the emptiness predicate
3678    /// and the validate gate would silently disagree on which rate
3679    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
3680    /// block whose only axis is a `Some :rate-limit` would satisfy
3681    /// `is_empty() == false` while the validate path silently read a
3682    /// drifted other value, or vice versa: an author's
3683    /// `:rate-limit "100/s"` would omit the value-shape gate while the
3684    /// emptiness predicate still classified the policy as non-empty).
3685    /// Lifting the resolution to a typed method on the substrate
3686    /// primitive means every downstream consumer of the Aplicacao's
3687    /// per-`:politicas` rate-limit surface reaches for exactly one
3688    /// typed dispatch — the resolver's accept-set migrates as a unit
3689    /// on any future axis addition.
3690    ///
3691    /// First `Option<Copy-composite-T>`-return accessor on the M3
3692    /// mesh-slot family — closes the last un-lifted per-`:politicas`
3693    /// scalar-value axis. Peer of the sibling per-`:politicas`
3694    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
3695    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
3696    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
3697    /// "one typed dispatch on the substrate primitive, thin
3698    /// projections at each consumer" discipline extended onto the
3699    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
3700    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
3701    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
3702    /// sub-accessors rather than a top-level accessor because
3703    /// consumers reach for the axes not the aggregate). Named
3704    /// `rate_limit()` to match the storage field's name; the
3705    /// accessor's identity maps onto the canonical MESH-COMPOSITION
3706    /// §III.2 vocabulary the slot's docstring already carries.
3707    #[must_use]
3708    pub const fn rate_limit(&self) -> Option<RateLimit> {
3709        self.rate_limit
3710    }
3711
3712    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
3713    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
3714    /// declaration scalar accessor every consumer of the Aplicacao's
3715    /// per-`:politicas` breaker declaration keys off — returns the
3716    /// author-declared `:politicas :circuit-breaker` typed
3717    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
3718    /// copied out of the typed slot's own `Option<CircuitBreaker>`
3719    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
3720    /// by value; no borrow of `&self` past the call). `None` when the
3721    /// slot is absent (the "cluster default applies — typically 'no
3722    /// per-Aplicacao breaker declaration, gateway-class per-listener
3723    /// default applies'" arm the future caixa-mesh
3724    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
3725    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
3726    /// arm reads this predicate too, so an authored-but-unset
3727    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
3728    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
3729    /// that omits the slot).
3730    ///
3731    /// The `:politicas :circuit-breaker` slot carries the
3732    /// "per-Aplicacao consecutive-transient-failure trip declaration"
3733    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3734    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
3735    /// zero-floor rejected through
3736    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3737    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
3738    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
3739    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
3740    /// canonical-form pinned through
3741    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
3742    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
3743    /// bijection the future `CiliumClusterwideEnvoyConfig`
3744    /// per-`:politicas` overlay emits. Every downstream consumer that
3745    /// reads the breaker declaration keys off this scalar (the
3746    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
3747    /// off to decide "emit :politicas overlay" vs "skip entirely", the
3748    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
3749    /// that brackets `cb.max_failures()` against
3750    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
3751    /// [`POLICY_BREAKER_WINDOW_MAX`] via
3752    /// [`crate::render::require_positive_canonical_bounded_duration`],
3753    /// the future M4 per-Aplicacao Envoy reconciler materialization
3754    /// pass, the future per-`:contratos`-edge breaker override the
3755    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3756    ///
3757    /// Prior to this lift the `.circuit_breaker` field was accessed
3758    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3759    /// `self.circuit_breaker.is_none()` arm and the
3760    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
3761    /// bind — two open-coded field-accesses that expressed no
3762    /// compile-time link back to the typed slot. A future extension of
3763    /// the `:politicas :circuit-breaker` axis to a richer author
3764    /// surface — a per-`:contratos`-edge breaker override the operator
3765    /// pins through a future `:contratos :circuit-breaker` slot the
3766    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
3767    /// breaker-default overlay the M4 CR materializer resolves per-CR,
3768    /// a promotion of the plain `(max_failures, window)` scalar pair to
3769    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
3770    /// sub-block once Envoy's `outlier_detection` grows the peer
3771    /// ejection-percentage / ejection-time axes — would have had to be
3772    /// threaded through both open-coded copies in lockstep or the
3773    /// emptiness predicate and the validate gate would silently
3774    /// disagree on which breaker declaration a given [`MeshPolicy`]
3775    /// resolves to (a `:politicas` block whose only axis is a
3776    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
3777    /// the validate path silently read a drifted other value, or vice
3778    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
3779    /// "60s"))` would omit the value-shape gate while the emptiness
3780    /// predicate still classified the policy as non-empty). Lifting
3781    /// the resolution to a typed method on the substrate primitive
3782    /// means every downstream consumer of the Aplicacao's
3783    /// per-`:politicas` breaker surface reaches for exactly one typed
3784    /// dispatch — the resolver's accept-set migrates as a unit on any
3785    /// future axis addition.
3786    ///
3787    /// Second `Option<Copy-composite-T>`-return accessor on the M3
3788    /// mesh-slot family (sibling of the peer per-`:politicas`
3789    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
3790    /// on the same composite-Copy shape, and of the sibling per-
3791    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
3792    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
3793    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
3794    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
3795    /// same "one typed dispatch on the substrate primitive, thin
3796    /// projections at each consumer" discipline extended onto the last
3797    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
3798    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
3799    /// match the storage field's name; the accessor's identity maps
3800    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3801    /// docstring already carries. Closes the last unlifted
3802    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
3803    /// reader now routes through a typed dispatch on the substrate
3804    /// primitive.
3805    #[must_use]
3806    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
3807        self.circuit_breaker
3808    }
3809}
3810
3811#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
3812#[serde(rename_all = "camelCase")]
3813pub struct CircuitBreaker {
3814    pub max_failures: u32,
3815    #[serde(with = "supervisor::duration_codec_required")]
3816    pub window: Duration,
3817}
3818
3819impl CircuitBreaker {
3820    /// Substrate-canonical per-`:politicas :circuit-breaker`
3821    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
3822    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3823    /// breaker trip-count keys off — returns the author-declared
3824    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
3825    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
3826    /// so the accessor returns by value; no borrow of `&self` past the
3827    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
3828    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
3829    /// axis; a `CircuitBreaker` past pattern-match is definitionally
3830    /// present, and its `:max-failures` field carries the trip count as a
3831    /// required-axis scalar).
3832    ///
3833    /// The `:politicas :circuit-breaker :max-failures` axis carries the
3834    /// "consecutive-transient-failure trip threshold" contract
3835    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
3836    /// (zero-floor rejected through
3837    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3838    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
3839    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
3840    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
3841    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
3842    /// Every downstream consumer that reads the trip threshold keys off
3843    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3844    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
3845    /// canonical `require_positive_bounded_u32` helper, the future M4
3846    /// per-Aplicacao Envoy config reconciler materialization pass, the
3847    /// future per-`:contratos`-edge breaker-override overlay the
3848    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3849    ///
3850    /// Prior to this lift the `.max_failures` field was accessed inline
3851    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
3852    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
3853    /// open-coded field-access that expressed no compile-time link back
3854    /// to the typed sub-struct axis. A future extension of the
3855    /// `:max-failures` axis to a richer author surface — a
3856    /// per-`:contratos`-edge breaker override the operator pins through a
3857    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3858    /// #3 roadmap acknowledges, a per-cluster max-failures-default
3859    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3860    /// plain `u32` trip count to a richer
3861    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3862    /// tuple once Envoy's `outlier_detection` block's peer axes come into
3863    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3864    /// count arms — would have had to be threaded through every open-
3865    /// coded copy in lockstep or the validate gate and the future M4
3866    /// emit path would silently disagree on which trip threshold a given
3867    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3868    /// would satisfy validate while the emit path silently read a drifted
3869    /// other value, or vice versa: a validated typed slot would land at
3870    /// the emit boundary as a no-op breaker whose trip threshold is
3871    /// structurally never reached). Lifting the resolution to a typed
3872    /// method on the substrate primitive means every downstream consumer
3873    /// of the Aplicacao's per-`:politicas :circuit-breaker`
3874    /// trip-threshold surface reaches for exactly one typed dispatch —
3875    /// the resolver's accept-set migrates as a unit on any future axis
3876    /// addition.
3877    ///
3878    /// First sub-struct scalar accessor on the M3 mesh-slot family
3879    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3880    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3881    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3882    /// closes the last unlifted per-`:politicas` scalar-value axis after
3883    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3884    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3885    /// Same "one typed dispatch on the substrate primitive, thin
3886    /// projections at each consumer" discipline the peer
3887    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3888    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3889    /// [`Membro::versao_requirement`] (a40b0e3),
3890    /// [`Entrada::destination`] (6db982c) accessors carry on their
3891    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3892    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3893    /// match the storage field's name; the accessor's identity maps onto
3894    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3895    /// docstring already carries.
3896    #[must_use]
3897    pub const fn max_failures(&self) -> u32 {
3898        self.max_failures
3899    }
3900
3901    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3902    /// Envoy-outlier-detection rolling-observation-interval scalar
3903    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3904    /// breaker rolling-window duration keys off — returns the
3905    /// author-declared `:politicas :circuit-breaker :window` typed
3906    /// `Duration` verbatim, copied out of the typed slot's own
3907    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3908    /// by value; no borrow of `&self` past the call). Non-optional (the
3909    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3910    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3911    /// `CircuitBreaker` past pattern-match is definitionally present,
3912    /// and its `:window` field carries the rolling-observation interval
3913    /// as a required-axis scalar).
3914    ///
3915    /// The `:politicas :circuit-breaker :window` axis carries the
3916    /// "consecutive-transient-failure rolling-observation interval"
3917    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3918    /// `Duration` accept-set (zero-floor rejected through
3919    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3920    /// residue rejected through
3921    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3922    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3923    /// Envoy `outlier_detection.interval` per-cluster
3924    /// ejection-observation-interval scalar (equivalently the future
3925    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3926    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3927    /// consumer that reads the rolling-observation interval keys off
3928    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3929    /// integer-millisecond canonical-form + cap bracket at
3930    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3931    /// [`crate::render::require_positive_canonical_bounded_duration`]
3932    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3933    /// materialization pass, the future per-`:contratos`-edge
3934    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3935    /// acknowledges).
3936    ///
3937    /// Prior to this lift the `.window` field was accessed inline at
3938    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3939    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3940    /// call — one open-coded field-access that expressed no compile-
3941    /// time link back to the typed sub-struct axis. A future extension
3942    /// of the `:window` axis to a richer author surface — a
3943    /// per-`:contratos`-edge window override the operator pins through
3944    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3945    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3946    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3947    /// `Duration` observation interval to a richer
3948    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3949    /// once Envoy's `outlier_detection` block's peer axes come into
3950    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3951    /// the window arms — would have had to be threaded through every
3952    /// open-coded copy in lockstep or the validate gate and the future
3953    /// M4 emit path would silently disagree on which observation
3954    /// interval a given [`CircuitBreaker`] resolves to (an author's
3955    /// `:window "60s"` would satisfy validate while the emit path
3956    /// silently read a drifted other value, or vice versa: a validated
3957    /// typed slot would land at the emit boundary as a breaker whose
3958    /// observation window is structurally so wide that no realistic
3959    /// failure-rate shape can trip it). Lifting the resolution to a
3960    /// typed method on the substrate primitive means every downstream
3961    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3962    /// observation-window surface reaches for exactly one typed
3963    /// dispatch — the resolver's accept-set migrates as a unit on any
3964    /// future axis addition.
3965    ///
3966    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3967    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3968    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3969    /// required-axis, extended onto the per-sub-struct required-`Duration`
3970    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3971    /// axis. Same "one typed dispatch on the substrate primitive, thin
3972    /// projections at each consumer" discipline the peer
3973    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3974    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3975    /// [`Membro::versao_requirement`] (a40b0e3),
3976    /// [`Entrada::destination`] (6db982c) accessors carry on their
3977    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3978    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3979    /// match the storage field's name; the accessor's identity maps onto
3980    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3981    /// docstring already carries.
3982    #[must_use]
3983    pub const fn window(&self) -> Duration {
3984        self.window
3985    }
3986}
3987
3988#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3989pub struct RateLimit {
3990    /// Requests per window.
3991    pub rate: u32,
3992    /// Window duration.
3993    pub window: Duration,
3994}
3995
3996impl RateLimit {
3997    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3998    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3999    /// every consumer of the Aplicacao's per-`:contratos`-edge
4000    /// rate-limit-bucket capacity keys off — returns the author-declared
4001    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
4002    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
4003    /// returns by value; no borrow of `&self` past the call). Non-optional
4004    /// (the surrounding `Option<RateLimit>` is the "slot present?"
4005    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
4006    /// `RateLimit` past pattern-match is definitionally present, and its
4007    /// `:rate` field carries the token-bucket capacity as a required-axis
4008    /// scalar).
4009    ///
4010    /// The `:politicas :rate-limit` `:rate` axis carries the
4011    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
4012    /// the typed slot's `u32` accept-set (zero-floor rejected through
4013    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
4014    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
4015    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
4016    /// token-bucket-capacity scalar (equivalently the future
4017    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4018    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4019    /// consumer that reads the token-bucket capacity keys off this
4020    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
4021    /// cap bracket that gates on the canonical
4022    /// [`crate::render::require_positive_bounded_u32`] helper, the
4023    /// [`rate_limit_codec::render`] `Duration → unit` projection that
4024    /// emits the `<n>/<s|m|h>` author surface, the future M4
4025    /// per-Aplicacao Envoy config reconciler materialization pass, the
4026    /// future per-`:contratos`-edge rate-limit-override overlay the
4027    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
4028    ///
4029    /// Prior to this lift the `.rate` field was accessed inline at three
4030    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
4031    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
4032    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
4033    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
4034    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
4035    /// field-accesses that expressed no compile-time link back to the
4036    /// typed sub-struct axis. A future extension of the `:rate` axis
4037    /// to a richer author surface — a per-`:contratos`-edge rate
4038    /// override the operator pins through a future `:contratos :rate`
4039    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
4040    /// per-cluster rate-default overlay the M4 CR materializer resolves
4041    /// per-CR, a promotion of the plain `u32` token capacity to a
4042    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
4043    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
4044    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
4045    /// before the token arms — would have had to be threaded through
4046    /// every open-coded copy in lockstep or the validate gate, the
4047    /// codec's render path, and the future M4 emit path would silently
4048    /// disagree on which token capacity a given [`RateLimit`] resolves
4049    /// to (an author's `:rate-limit "100/s"` would satisfy validate
4050    /// while the render / emit paths silently read a drifted other
4051    /// value, or vice versa: a validated typed slot would land at the
4052    /// emit boundary as a no-op limiter whose token capacity is
4053    /// structurally so high that no realistic per-edge traffic shape
4054    /// can drain it). Lifting the resolution to a typed method on the
4055    /// substrate primitive means every downstream consumer of the
4056    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
4057    /// reaches for exactly one typed dispatch — the resolver's
4058    /// accept-set migrates as a unit on any future axis addition.
4059    ///
4060    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
4061    /// in shape to the peer per-`CircuitBreaker`
4062    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
4063    /// on the peer per-sub-struct required-axis, extended onto the
4064    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
4065    /// required-axis scalar" projection pattern the sibling
4066    /// [`RateLimit::window`] future lift folds on. Same "one typed
4067    /// dispatch on the substrate primitive, thin projections at each
4068    /// consumer" discipline the peer [`WitContract::source`] /
4069    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
4070    /// (0804823), [`Membro::nome`] (4a32abf),
4071    /// [`Membro::versao_requirement`] (a40b0e3),
4072    /// [`Entrada::destination`] (6db982c),
4073    /// [`CircuitBreaker::max_failures`] (3a74062),
4074    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
4075    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
4076    /// to match the storage field's name; the accessor's identity maps
4077    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
4078    /// docstring already carries.
4079    #[must_use]
4080    pub const fn rate(&self) -> u32 {
4081        self.rate
4082    }
4083
4084    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
4085    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
4086    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
4087    /// rate-limit-bucket refill period keys off — returns the
4088    /// author-declared `:politicas :rate-limit` typed `Duration`
4089    /// verbatim, copied out of the typed slot's own `Duration` storage
4090    /// (`Duration` is `Copy`, so the accessor returns by value; no
4091    /// borrow of `&self` past the call). Non-optional (the surrounding
4092    /// `Option<RateLimit>` is the "slot present?" projection at the
4093    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
4094    /// pattern-match is definitionally present, and its `:window`
4095    /// field carries the token-bucket refill period as a required-axis
4096    /// scalar).
4097    ///
4098    /// The `:politicas :rate-limit` `:window` axis carries the
4099    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
4100    /// — the typed slot's `Duration` accept-set (constrained to the
4101    /// three canonical windows `{1s, 60s, 3600s}` the
4102    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
4103    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
4104    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
4105    /// per-cluster token-bucket-refill-period scalar (equivalently the
4106    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4107    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
4108    /// consumer that reads the token-bucket refill period keys off
4109    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
4110    /// canonical-window gate that keys off
4111    /// [`is_canonical_rate_limit_window`], the
4112    /// [`rate_limit_codec::render`] `Duration → unit` projection that
4113    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
4114    /// [`rate_limit_window_unit`] and non-canonical fallback via
4115    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
4116    /// reconciler materialization pass, the future per-`:contratos`-
4117    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
4118    /// roadmap acknowledges).
4119    ///
4120    /// Prior to this lift the `.window` field was accessed inline at
4121    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
4122    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
4123    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
4124    /// error-payload construction on refusal, and the two
4125    /// [`rate_limit_codec::render`] arms
4126    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
4127    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
4128    /// open-coded field-accesses that expressed no compile-time link
4129    /// back to the typed sub-struct axis. A future extension of the
4130    /// `:window` axis to a richer author surface — a per-`:contratos`-
4131    /// edge window override the operator pins through a future
4132    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
4133    /// acknowledges, a per-cluster window-default overlay the M4 CR
4134    /// materializer resolves per-CR, a promotion of the plain
4135    /// `Duration` refill period to a richer
4136    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
4137    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
4138    /// axis comes into scope, an addition of a `"d"` day suffix once
4139    /// Envoy's `rate_limit_action` grows daily-bucket support — would
4140    /// have had to be threaded through every open-coded copy in
4141    /// lockstep or the validate gate, the codec's render path, and
4142    /// the future M4 emit path would silently disagree on which
4143    /// refill period a given [`RateLimit`] resolves to (an author's
4144    /// `:rate-limit "100/s"` would satisfy validate while the render
4145    /// / emit paths silently read a drifted other value, or vice
4146    /// versa: a validated typed slot would land at the emit boundary
4147    /// as a limiter whose refill period is structurally so long that
4148    /// no realistic per-edge traffic shape stays inside the token
4149    /// budget). Lifting the resolution to a typed method on the
4150    /// substrate primitive means every downstream consumer of the
4151    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
4152    /// reaches for exactly one typed dispatch — the resolver's
4153    /// accept-set migrates as a unit on any future axis addition.
4154    ///
4155    /// Second sub-struct scalar accessor on the `RateLimit` axis —
4156    /// sibling in shape to the just-landed [`RateLimit::rate`]
4157    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
4158    /// required-axis, extended onto the per-sub-struct
4159    /// required-`Duration` axis; closes the last unlifted
4160    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
4161    /// per-sub-struct accessor coverage is now complete across both
4162    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
4163    /// the substrate primitive, thin projections at each consumer"
4164    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
4165    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
4166    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
4167    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
4168    /// [`Membro::nome`] (4a32abf),
4169    /// [`Membro::versao_requirement`] (a40b0e3),
4170    /// [`Entrada::destination`] (6db982c) accessors carry on their
4171    /// respective per-mesh-slot-atom scalar-value axes. Named
4172    /// `window()` to match the storage field's name; the accessor's
4173    /// identity maps onto the canonical MESH-COMPOSITION §III.2
4174    /// vocabulary the slot's docstring already carries.
4175    #[must_use]
4176    pub const fn window(&self) -> Duration {
4177        self.window
4178    }
4179
4180    /// Recognize this rate-limit's `:window` as a canonical
4181    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
4182    /// exactly matches one of the three closed-set arm-Durations
4183    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
4184    /// non-canonical magnitude the codec's round-trip would break on
4185    /// (sub-second residue, or a second-magnitude outside the set
4186    /// [`RateLimitUnit::ALL`] enumerates).
4187    ///
4188    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
4189    /// returns `Some` here — the validate gate's
4190    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
4191    /// rejects every window this accessor returns `None` on. Downstream
4192    /// consumers past validate (the codec's [`rate_limit_codec::render`]
4193    /// path, the future M4 per-Aplicacao Envoy config reconciler's
4194    /// materialization pass, the future per-`:contratos`-edge rate-limit-
4195    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
4196    /// acknowledges) that read the typed unit off a validated slot can
4197    /// pattern-match on the returned `Some` without re-checking
4198    /// canonicality at the consumer layer — the typed enum surface is
4199    /// the load-bearing carrier of the canonicality invariant.
4200    ///
4201    /// Preferred over the free [`is_canonical_rate_limit_window`]
4202    /// module-private helper at any call site that has the typed
4203    /// [`RateLimit`] in hand (the codec's `render` arm at
4204    /// [`rate_limit_codec::render`], the validate gate's canonical-form
4205    /// arm in [`AplicacaoSpec::validate_politicas`], any future
4206    /// per-`:contratos` edge-override overlay resolver): those consumers
4207    /// reach for the typed enum without going through the
4208    /// `.window()` scalar-projection layer, and get the enum value
4209    /// directly (which the codec's render arm can then format via
4210    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
4211    /// "typed sub-struct scalar accessor, one dispatch on the substrate
4212    /// primitive" discipline the sibling [`RateLimit::rate`] and
4213    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
4214    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
4215    /// projection axis (the third scalar accessor on the [`RateLimit`]
4216    /// axis, first typed-enum-return projection).
4217    ///
4218    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
4219    /// the canonical [`RateLimitUnit`] arm now carries the same
4220    /// `const`-eval-surface posture the sibling `pub const fn`
4221    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
4222    /// this typed sub-struct already carry, composing through the
4223    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
4224    /// reverse-resolver in `const` context. Any downstream substrate-
4225    /// side `const`-context consumer of the typed unit (a module-scope
4226    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
4227    /// invariant pin on a typed fixture, a future M4 admission-webhook
4228    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
4229    /// resolver over a typed [`RateLimit`], any future `const fn`
4230    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4231    /// the substrate primitive) now reaches the same typed dispatch on
4232    /// the substrate primitive at const-eval time as at runtime.
4233    ///
4234    /// Pinned load-bearing at the substrate-primitive level by
4235    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
4236    /// eval-surface pin via `const fn` wrapper).
4237    #[must_use]
4238    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
4239        RateLimitUnit::from_window(self.window)
4240    }
4241}
4242
4243/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
4244/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
4245/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
4246///
4247/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
4248/// the `:politicas :rate-limit` unit surface reads from
4249/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
4250/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
4251/// [`is_canonical_rate_limit_window`] predicate the
4252/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
4253/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
4254/// projection) now lives inside this typed enum's `match self` arms — a
4255/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
4256/// `rate_limit_action` grows daily-bucket support) is one new variant
4257/// plus the exhaustiveness arms on the four methods, so every consumer
4258/// picks it up by compile-time construction rather than a runtime
4259/// table-scan miss.
4260///
4261/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
4262/// scanned via `find_map` at every projection call — an untyped runtime
4263/// walk that carried no compile-time link between the parse arm's
4264/// accepted suffixes, the render arm's emitted suffixes, and the
4265/// validate gate's accepted windows. A future rate-limit-unit addition
4266/// that landed one row without threading through the other consumers
4267/// (or a copy-paste flip that collapsed two rows onto one suffix) would
4268/// silently split the accepted-set across the three consumers — the
4269/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
4270/// for a 24h window that parse can't round-trip, the validate gate
4271/// misses one canonical window. Lifting the pairs onto a typed
4272/// closed-set enum with exhaustive `match` arms makes any such
4273/// half-landed extension a caixa-core build error (the compiler enforces
4274/// arm coverage on every method), not a silent per-consumer drift
4275/// surfacing at apply time. Same "closed-set typed-enum discriminator"
4276/// discipline the sibling [`PlacementStrategy`] (cc8f749),
4277/// [`crate::supervisor::RestartStrategy`],
4278/// [`crate::supervisor::RestartPolicy`],
4279/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
4280/// closed-set typed enums carry on their respective closed-set axes —
4281/// extended onto the seventh closed-set typed-enum discriminator axis
4282/// on the caixa typed surface (the `:politicas :rate-limit :window`
4283/// canonical-unit axis).
4284#[derive(
4285    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4286)]
4287pub enum RateLimitUnit {
4288    /// 1-second window — canonical author-surface suffix `"s"`
4289    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4290    /// with a 1s magnitude.
4291    Second,
4292    /// 1-minute window — canonical author-surface suffix `"m"`
4293    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4294    /// with a 60s magnitude.
4295    Minute,
4296    /// 1-hour window — canonical author-surface suffix `"h"`
4297    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
4298    /// with a 3600s magnitude.
4299    Hour,
4300}
4301
4302impl RateLimitUnit {
4303    /// Exhaustive iteration surface for every consumer that reads the
4304    /// full canonical-unit set (the byte-parity witness against the
4305    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
4306    /// webhook's accepted-suffix listing in its rejection body, any
4307    /// future round-trip fuzz harness). A future variant addition to
4308    /// [`RateLimitUnit`] extends this slice as a single edit and every
4309    /// consumer picks up the new entry by construction — the compiler-
4310    /// checked exhaustiveness on the sibling method `match` arms is the
4311    /// build-time guarantee that no arm forgets to grow.
4312    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
4313
4314    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
4315    /// string every `<n>/<unit>` rate-limit shape carries after its
4316    /// `/` separator. The single source of truth the codec's parse and
4317    /// render arms both dispatch on: the parse arm matches an incoming
4318    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
4319    /// output; the render arm emits the entry's `as_suffix` verbatim
4320    /// after the rate magnitude.
4321    #[must_use]
4322    pub const fn as_suffix(self) -> &'static str {
4323        match self {
4324            Self::Second => "s",
4325            Self::Minute => "m",
4326            Self::Hour => "h",
4327        }
4328    }
4329
4330    /// Canonical `Duration` for this unit — the token-bucket refill
4331    /// period the [`RateLimit::window`] axis carries when the surrounding
4332    /// slot's `:rate-limit` author surface named this unit.
4333    #[must_use]
4334    pub const fn window(self) -> Duration {
4335        Duration::from_secs(match self {
4336            Self::Second => 1,
4337            Self::Minute => 60,
4338            Self::Hour => 3_600,
4339        })
4340    }
4341
4342    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
4343    /// `None` when `suffix` is outside the closed-set arm-string set
4344    /// [`Self::as_suffix`] emits. The single `str → Self` projection
4345    /// [`rate_limit_codec::parse`] consumes.
4346    #[must_use]
4347    pub fn from_suffix(suffix: &str) -> Option<Self> {
4348        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
4349    }
4350
4351    /// Recognize a canonical rate-limit `Duration` as one of the three
4352    /// arms, or `None` when `window` carries sub-second residue or a
4353    /// second-magnitude outside the closed-set arm-window set
4354    /// [`Self::window`] emits. The single `Duration → Self` projection
4355    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
4356    /// both consume.
4357    ///
4358    /// `pub const fn` — the reverse `Duration → Self` projection now
4359    /// carries the same `const`-eval-surface posture the sibling
4360    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
4361    /// projection accessors on this closed-set typed enum already
4362    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
4363    /// typed-`RateLimit`-projection sibling composes through in `const`
4364    /// context. Routes byte-for-byte through the peer `pub const fn`
4365    /// [`Self::window`] canonical-`Duration` projection so any future
4366    /// arm-magnitude edit on the sibling accessor reaches this reverse
4367    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
4368    /// per-arm probes each dispatch through one `pub const fn` on the
4369    /// substrate primitive rather than a hand-authored per-arm second-
4370    /// magnitude literal that would silently drift on any future
4371    /// [`Self::window`] arm-magnitude edit.
4372    ///
4373    /// Prior to the `const` lift the body dispatched through
4374    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
4375    /// iterator-driven linear scan whose iterator methods
4376    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
4377    /// `PartialEq` dispatch each carry non-`const` bounds on stable
4378    /// Rust 1.94, so any downstream substrate-side `const`-context
4379    /// consumer of the reverse resolver (a module-scope
4380    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
4381    /// invariant pin on a typed fixture, a future M4
4382    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
4383    /// webhook `const fn` per-`:politicas` canonical-window floor over a
4384    /// typed [`RateLimit`] scalar, any future `const fn`
4385    /// per-`:contratos`-edge rate-limit-override overlay resolver over
4386    /// the substrate primitive that wants to fan on the canonical unit
4387    /// at compile time) surfaced as a downstream E0015 far from the
4388    /// resolver's own declaration. The `pub const fn` posture closes
4389    /// the drift structurally at caixa-core build time.
4390    ///
4391    /// Pinned load-bearing at the substrate-primitive level by
4392    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
4393    /// eval-surface pin via `const fn` wrapper) and
4394    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
4395    /// (composition-witness pin against the peer `Self::window` scalar
4396    /// dispatch).
4397    #[must_use]
4398    pub const fn from_window(window: Duration) -> Option<Self> {
4399        if window.subsec_nanos() != 0 {
4400            return None;
4401        }
4402        // Route through the peer `pub const fn` [`Self::window`]
4403        // canonical-`Duration` projection so any future arm-magnitude
4404        // edit on the sibling accessor reaches this reverse resolver by
4405        // construction — the per-arm `secs` comparison keys off
4406        // `Duration::as_secs` (`pub const fn`), not a hand-authored
4407        // per-arm second-magnitude literal that would silently drift.
4408        let secs = window.as_secs();
4409        if secs == Self::Second.window().as_secs() {
4410            Some(Self::Second)
4411        } else if secs == Self::Minute.window().as_secs() {
4412            Some(Self::Minute)
4413        } else if secs == Self::Hour.window().as_secs() {
4414            Some(Self::Hour)
4415        } else {
4416            None
4417        }
4418    }
4419
4420    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
4421    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
4422    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
4423    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
4424    /// consumes.
4425    ///
4426    /// The peer `Duration → &'static str` axis folded onto the substrate
4427    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
4428    /// production consumers ([`rate_limit_codec::render`] and
4429    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
4430    /// migrated (61421a6): the free helper's `Duration → &str` projection
4431    /// is now the two-step composition
4432    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
4433    /// reads through the typed accessor. This lift closes the peer
4434    /// `&str → Duration` axis by folding the vestigial module-private
4435    /// `rate_limit_window_from_unit` delegate onto this associated method
4436    /// — the codec's parse arm and every future wire-side consumer of the
4437    /// `&str → Duration` projection (a future admission-webhook that
4438    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
4439    /// before it's promoted to a validated typed slot, a future
4440    /// `feira lint` shape-probe that reads the author-surface bytes
4441    /// verbatim) now reach for exactly one typed dispatch on the
4442    /// substrate primitive.
4443    ///
4444    /// Same "closed-set typed-enum discriminator with canonical
4445    /// projections per axis" discipline the sibling [`Self::as_suffix`]
4446    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
4447    /// methods carry — this associated method closes the fifth (and last
4448    /// unlifted) projection axis on the arm-table, so the closed-set enum
4449    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
4450    /// consumer of the `:politicas :rate-limit :window` axis reaches
4451    /// through. A future rate-limit-unit addition (a `"d"` day suffix
4452    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
4453    /// `"ms"` sub-second window once high-throughput per-edge policies
4454    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
4455    /// variant plus one arm per method — the compiler enforces
4456    /// exhaustiveness on every consumer's `match self` arms and picks
4457    /// the new unit up by construction across all five projections.
4458    #[must_use]
4459    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
4460        Self::from_suffix(suffix).map(Self::window)
4461    }
4462}
4463
4464/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
4465/// every consumer that formats a canonical rate-limit unit as user-
4466/// facing text (future M4 admission-webhook rejection bodies naming
4467/// the accepted-suffix set, future `feira app graph` per-`:politicas`
4468/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
4469/// codec's parse arm accepts and the render arm emits. Same
4470/// as_str-through-Display convergence discipline the sibling
4471/// [`PlacementStrategy`], [`crate::CaixaKind`],
4472/// [`crate::supervisor::RestartStrategy`], and
4473/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
4474impl std::fmt::Display for RateLimitUnit {
4475    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
4476        f.write_str(self.as_suffix())
4477    }
4478}
4479
4480/// Substrate-canonical [`AsRef<str>`] projection on the M3
4481/// `:politicas :rate-limit` closed-set typed unit-suffix enum —
4482/// routes through the same [`RateLimitUnit::as_suffix`] `pub const fn`
4483/// scalar accessor the paired [`std::fmt::Display`] impl already
4484/// delegates through, so any future consumer that binds a
4485/// [`RateLimitUnit`] through the standard-library `impl AsRef<str>`
4486/// bound (a [`std::process::Command::arg`] shell-out that composes the
4487/// canonical suffix into an Envoy sidecar config-CLI's per-`:politicas`
4488/// `--rate-limit-unit <s|m|h>` arg on the future
4489/// `CiliumClusterwideEnvoyConfig` overlay MESH-COMPOSITION §III.2 #3
4490/// names, a `tracing::field::Value::Str`-arm structured-log recorder
4491/// on the future `app-operator`'s per-`:politicas :rate-limit`
4492/// reconcile step, a [`std::collections::HashMap`] lookup keyed on
4493/// the canonical suffix through `map.get::<str>(unit.as_ref())` on a
4494/// future per-unit token-bucket-refill dispatch table the future M4
4495/// admission-webhook rejection body composes) reaches the paired
4496/// `"s"` / `"m"` / `"h"` byte-string through one substrate-primitive
4497/// dispatch rather than an open-coded `.as_suffix()` re-inlining at
4498/// every wire-up.
4499///
4500/// Deliberately routes through the canonical suffix axis, not the
4501/// second-magnitude [`RateLimitUnit::window`] axis — `AsRef<str>` and
4502/// [`fmt::Display`] land on the same author-surface-canonical byte-
4503/// string the codec's parse and render arms both dispatch on, while
4504/// the token-bucket-refill period stays reachable only through the
4505/// explicit [`RateLimitUnit::window`] / [`RateLimitUnit::from_window`]
4506/// paths.
4507///
4508/// Same "route the trait impl through the substrate-primitive
4509/// accessor" discipline the sibling [`crate::CaixaVersion`]
4510/// [`AsRef<str>`] impl (16d5c7e), the paired M2
4511/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
4512/// (63eb1a4), the paired M2 [`crate::supervisor::RestartPolicy`]
4513/// [`AsRef<str>`] impl (419ea81), the M3
4514/// [`PlacementStrategy`] [`AsRef<str>`] impl (d86edd2), and the
4515/// top-level [`crate::CaixaKind`] [`AsRef<str>`] impl (cd2091f) carry
4516/// — closes the substrate primitive's [`AsRef<str>`] projection axis
4517/// onto the last remaining closed-set typed enum with a
4518/// [`fmt::Display`] surface, so every closed-set typed enum / newtype
4519/// on the caixa surface (top-level `:kind`, both M2
4520/// `:supervisor`-slot per-child and sibling-restart typed enums, the
4521/// M3 `:placement :estrategia` typed enum, the M3
4522/// `:politicas :rate-limit` unit-suffix typed enum, and the `:versao`
4523/// typed newtype) now carries the paired [`AsRef<str>`] +
4524/// [`fmt::Display`] + `as_*` triple through one lifted-const family.
4525///
4526/// Pinned load-bearing by
4527/// [`tests::rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor`]
4528/// (byte-parity pin against [`RateLimitUnit::as_suffix`] across the
4529/// three-arm closed set) and
4530/// [`tests::rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor`]
4531/// (three-path convergence: `AsRef<str>` + `Display` + `as_suffix`
4532/// all resolve to the same byte-string per arm) — any future silent
4533/// detour that routes the impl through a divergent projection (a
4534/// per-arm inline `match self { … }` re-inlining that opens a compile-
4535/// time link to the un-lifted arm-literal, a swap onto the
4536/// second-magnitude [`RateLimitUnit::window`] axis that would collide
4537/// the canonical-suffix / token-bucket-refill two-axis split) trips at
4538/// caixa-core test time under `assert_eq!` rather than at a downstream
4539/// `impl AsRef<str>`-bound consumer's silent split.
4540impl AsRef<str> for RateLimitUnit {
4541    fn as_ref(&self) -> &str {
4542        self.as_suffix()
4543    }
4544}
4545
4546/// Upper-bound ceiling on the `:politicas :timeout` axis — every
4547/// validated [`MeshPolicy::timeout`] past
4548/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
4549/// (inclusive on both ends, integer-millisecond magnitudes by the
4550/// canonical-form gate immediately preceding).
4551///
4552/// The typed field is `Option<Duration>` (the zero-floor arm
4553/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
4554/// `Duration::ZERO`, and the canonical-form arm
4555/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
4556/// sub-millisecond residue), so a programmatic struct literal
4557/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
4558/// 24h) and the equivalent author-surface form
4559/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
4560/// integer-hour magnitude) both round-trip cleanly through serde — a
4561/// structurally unbounded `Duration` ceiling. A `:timeout` value far
4562/// above the documented production-playbook band (Envoy default `15s`,
4563/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
4564/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
4565/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
4566/// at `~3600s`) silently degenerates the mesh-policy contract: the
4567/// per-call deadline is structurally so long that no realistic
4568/// synchronous-`:contratos` traversal can reach it, so the typed slot
4569/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
4570/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
4571/// blocking" degenerates to a nominal-only contract on the
4572/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
4573/// the sibling `:politicas :retries` axis and the
4574/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
4575/// `:politicas :circuit-breaker :max-failures` axis — all three close
4576/// the "structurally unbounded ceiling on a typed `:politicas` axis"
4577/// footgun the prior zero-floor-and-canonical-form-only checks left
4578/// open.
4579///
4580/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4581/// shared duration codec emits (`"<n>h"` for any integer-hour
4582/// magnitude) — every value in the canonical authoring form's
4583/// `<integer><unit>` grammar at or below this cap renders to a clean
4584/// canonical string. The cap sits an order of magnitude above every
4585/// documented production-playbook recommendation band (Envoy default
4586/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
4587/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
4588/// configured maximum (`proxy_read_timeout` typical max `3600s`),
4589/// below the clearly-pathological "effectively no timeout" floor
4590/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
4591/// want for a long-running synchronous workflow, but a hard wall above
4592/// which the mesh-level deadline is structurally a non-deadline.
4593/// Lifted as a typed `pub const` so the bound has exactly one source
4594/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4595/// materializer's admission webhook and the caixa-mesh-side
4596/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4597/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4598/// other typed upper bound in this crate carries
4599/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4600/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4601/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4602/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4603pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
4604
4605/// Upper-bound ceiling on the `:politicas :retries` axis — every
4606/// validated [`MeshPolicy::retries`] past
4607/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
4608///
4609/// The typed slot is `Option<u32>` (`None` = no retries on transient
4610/// failure; `Some(0)` already rejected by the
4611/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
4612/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
4613/// .. }`) and the equivalent author-surface form
4614/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
4615/// serde / the codec — a structurally unbounded `u32` ceiling. The
4616/// runtime substrate that consumes the value (Envoy's
4617/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
4618/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
4619/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
4620/// admission cap is 10) translates a four-billion-retry policy into a
4621/// thundering-herd amplification vector on transient failure — the
4622/// caller's one request fans out to `retries` server-side calls per
4623/// edge per traversal, multiplying load by `(retries+1)^depth` across
4624/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
4625/// invariant "no infinite blocking" pairs with a no-runaway-amplification
4626/// invariant on the retry axis; both belong at the typed-slot layer.
4627///
4628/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
4629/// upstream mesh-policy schema that documents one) and sits above the
4630/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
4631/// every documented production playbook): a value the author can
4632/// plausibly want, but a hard wall above which the policy is
4633/// structurally a footgun. Lifted as a typed `pub const` so the bound
4634/// has exactly one source of truth — a future axis reaching for the
4635/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4636/// materializer's admission webhook, the caixa-mesh-side
4637/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
4638/// one place. Same shape every other typed upper bound in this crate
4639/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4640/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4641/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
4642/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4643pub const POLICY_RETRIES_MAX: u32 = 10;
4644
4645/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
4646/// axis — every validated [`CircuitBreaker::max_failures`] past
4647/// [`AplicacaoSpec::validate_politicas`] lies in
4648/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
4649///
4650/// The typed field is `u32` (the zero-floor arm
4651/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
4652/// `0` — a breaker that trips on the first call), so a programmatic
4653/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
4654/// and the equivalent author-surface form
4655/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
4656/// cleanly through serde — a structurally unbounded `u32` ceiling. A
4657/// `max_failures` value far above the documented production-playbook
4658/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
4659/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
4660/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
4661/// typical 5–50) silently disables the breaker's protection role:
4662/// the threshold is structurally so high that no realistic
4663/// failures-per-`:window` traffic shape can reach it, so the breaker
4664/// never trips and the typed slot becomes a no-op carried on every
4665/// emitted Envoy / Cilium L7 overlay. Pairs with the
4666/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
4667/// axis — both close the "structurally unbounded `u32` ceiling on a
4668/// typed policy axis" footgun the prior zero-floor-only checks left
4669/// open.
4670///
4671/// The `1000` ceiling sits an order of magnitude above every
4672/// documented upstream production-playbook recommendation band (the
4673/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
4674/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
4675/// the clearly-pathological "effectively no protection"
4676/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
4677/// plausibly want at hyperscale, but a hard wall above which the
4678/// policy is structurally a no-op. Lifted as a typed `pub const` so
4679/// the bound has exactly one source of truth — the future M4
4680/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4681/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4682/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4683/// one place. Same shape every other typed upper bound in this crate
4684/// carries ([`POLICY_RETRIES_MAX`],
4685/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4686/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4687/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4688pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
4689
4690/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
4691/// every validated [`CircuitBreaker::window`] past
4692/// [`AplicacaoSpec::validate_politicas`] lies in
4693/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
4694/// integer-millisecond magnitudes by the canonical-form gate
4695/// immediately preceding).
4696///
4697/// The typed field is `Duration` (the zero-floor arm
4698/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
4699/// `Duration::ZERO`, and the canonical-form arm
4700/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
4701/// sub-millisecond residue), so a programmatic struct literal
4702/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
4703/// and the equivalent author-surface form
4704/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
4705/// integer-hour magnitude) both round-trip cleanly through serde — a
4706/// structurally unbounded `Duration` ceiling. A `:window` value far
4707/// above the documented production-playbook band (Hystrix
4708/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
4709/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
4710/// Istio `outlierDetection.interval` default `10s`, Envoy
4711/// `outlier_detection.interval` default `10s`, AWS App Mesh
4712/// circuit-breaker time-window typical `30s..=300s`) degenerates the
4713/// breaker's role: a rolling-window failure counter whose window is
4714/// hours long is operationally a lifetime counter, the breaker's
4715/// "recent failures" memory is structurally so long that transient
4716/// failures are never forgotten, and the typed slot becomes a no-op
4717/// trigger that trips once and stays tripped for the lifetime of the
4718/// component carried on every emitted Envoy / Cilium L7 overlay.
4719///
4720/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
4721/// shared duration codec emits (`"<n>h"` for any integer-hour
4722/// magnitude) — every value in the canonical authoring form's
4723/// `<integer><unit>` grammar at or below this cap renders to a clean
4724/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
4725/// cap on the first typed-`Duration` `:politicas` axis: the two
4726/// duration-typed `:politicas` axes now share a single uniform top
4727/// edge so the next typed-slot wiring (the future caixa-mesh
4728/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
4729/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
4730/// admission webhook) reaches for either field knowing the value is
4731/// in `1ms..=1h` without re-validating at the renderer layer. The cap
4732/// sits two orders of magnitude above every documented upstream
4733/// production-playbook recommendation band (Hystrix / resilience4j /
4734/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
4735/// and below the clearly-pathological "rolling window degenerates to
4736/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
4737/// author can plausibly want for a very-low-traffic long-tail
4738/// failure-detection window, but a hard wall above which the breaker's
4739/// rolling-window contract is structurally a lifetime-counter contract.
4740/// Lifted as a typed `pub const` so the bound has exactly one source
4741/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4742/// materializer's admission webhook and the caixa-mesh-side
4743/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4744/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
4745/// other typed upper bound in this crate carries
4746/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4747/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
4748/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4749/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4750/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4751pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
4752
4753/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
4754/// every validated [`RateLimit::rate`] past
4755/// [`AplicacaoSpec::validate_politicas`] lies in
4756/// `1..=POLICY_RATE_LIMIT_MAX`.
4757///
4758/// The typed field is `u32` (the zero-floor arm
4759/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
4760/// zero-rate limit denies every request, the canonical "I forgot
4761/// that 0 means deny-everything" footgun), so a programmatic struct
4762/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
4763/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
4764/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
4765/// round-trip cleanly through serde — a structurally unbounded `u32`
4766/// ceiling. The runtime substrate consuming the value (Envoy's
4767/// `local_rate_limit.token_bucket.max_tokens`, the future
4768/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
4769/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
4770/// rate-limit into a no-op rate-limiter: the bucket capacity is
4771/// structurally so high no realistic per-edge traffic shape can
4772/// drain it, the limiter never trips, and the typed slot becomes a
4773/// "rate-limit declared, no enforcement" footgun — the canonical
4774/// declared-but-inert shape every other `:politicas` cap arm
4775/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
4776/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
4777///
4778/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
4779/// above every documented upstream production-playbook recommendation
4780/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
4781/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
4782/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
4783/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
4784/// `limit_req_zone` typical `1..=1_000` RPS) and below the
4785/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
4786/// `u32::MAX`): a value the author can plausibly want at hyperscale
4787/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
4788/// /h-window arm), but a hard wall above which the policy is
4789/// structurally a no-op carried verbatim on every emitted Envoy /
4790/// Cilium L7 overlay. The cap brackets all three canonical windows
4791/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
4792/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
4793/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
4794/// per-endpoint API band). Lifted as a typed `pub const` so the bound
4795/// has exactly one source of truth — the future M4
4796/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
4797/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
4798/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
4799/// one place. Same shape every other typed upper bound in this crate
4800/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
4801/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
4802/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
4803/// [`crate::LIMITS_WALL_CLOCK_MAX`],
4804/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
4805/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
4806pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
4807
4808// `:entrada :host` total-length and per-label cap axes route through
4809// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
4810// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
4811// pair of aplicacao-private aliases the previous `validate_entrada_host`
4812// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
4813// = 63`) were structurally the same K8s Gateway API v1 Hostname
4814// admission-schema bounds — the total-length cap on the OpenAPI
4815// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
4816// same regex — that the peer axes at the caixa-core::render level pin,
4817// so hoisting both readers onto the shared lifted constants closes the
4818// third-occurrence duplication threshold structurally: the M4
4819// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
4820// label validator, the future per-`Certificate` SAN emitter, and every
4821// other per-Gateway-API-Hostname landing site reach the same one place
4822// as the `:entrada :host` gate does — no per-axis alias drift surface
4823// between them, by construction.
4824
4825/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
4826/// extractor expression — the upper bound `validate_placement_shard_key`
4827/// enforces on every well-shaped shard-key past validate. The realistic
4828/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
4829/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
4830/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
4831/// `:placement :affinity` / `:placement :clusters` identifier-shaped
4832/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
4833/// in `:shard-key`" footgun at validate time rather than at the future
4834/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
4835const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
4836
4837/// Reject `:membros :caixa` values the K8s apiserver would refuse at
4838/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4839/// that maps the shared parser-shaped reason into the
4840/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
4841/// is self-locating (the offending `caixa:` is named verbatim) and
4842/// the author can grep their caixa.lisp for `:caixa "<name>"` and
4843/// fix it in one edit. Same diagnostic shape as
4844/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
4845/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
4846fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
4847    // Empty is already gated by `MembroCaixaEmpty` at the call site;
4848    // re-checking here keeps the predicate usable from any future
4849    // call site (the M4 CR materializer) without an empty-check
4850    // footgun. The shared
4851    // [`crate::render::require_valid_dns_1123_label`] helper brackets
4852    // the empty-first + shape cascade every peer name axis
4853    // (`:placement :clusters`, `:placement :affinity`, `:contratos
4854    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
4855    // `:upgrade-from :module`) routes through, so drift between the
4856    // eight axes' accepted DNS-1123-label sets is structurally
4857    // impossible.
4858    crate::render::require_valid_dns_1123_label(
4859        caixa,
4860        || AplicacaoError::MembroCaixaEmpty,
4861        |reason| AplicacaoError::membro_caixa_invalid(caixa, reason),
4862    )
4863}
4864
4865/// Reject `:placement :clusters` entries the K8s apiserver would refuse
4866/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4867/// that maps the shared parser-shaped reason into the
4868/// [`AplicacaoError::PlacementClusterInvalid`] variant.
4869///
4870/// Cluster names land in DNS-1123-label territory across every consumer:
4871/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
4872/// the `lareira-fleet-programs` aggregator applies to scope programs to
4873/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
4874/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
4875/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
4876/// cluster identity the M4 CR materializer round-trips. Each apiserver-
4877/// side schema enforces the DNS-1123 label rule on admission; a
4878/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
4879/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
4880/// mistaken-identity slug) silently passes the prior empty-/duplicate-
4881/// only gate and the failure surfaces as a no-match at filter time —
4882/// the workload doesn't land in the named cluster, with no diagnostic
4883/// naming the offending `:clusters` entry. Lifting the gate to caixa-
4884/// build time mirrors the `:membros :caixa` value-shape trajectory
4885/// (3f9d7a0) on the peer name axis.
4886///
4887/// The diagnostic carries the offending `cluster:` verbatim plus a
4888/// parser-shaped `reason:` naming the specific violation, so the
4889/// author can grep their caixa.lisp for `:clusters` and fix it in
4890/// one edit. Same diagnostic shape as
4891/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
4892fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
4893    // Empty is already gated by `PlacementClusterEmpty` at the call
4894    // site; re-checking here keeps the predicate usable from any
4895    // future call site (the M4 CR materializer's per-cluster validator)
4896    // without an empty-check footgun. Routes through the shared
4897    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4898    // name axes each land on.
4899    crate::render::require_valid_dns_1123_label(
4900        cluster,
4901        || AplicacaoError::PlacementClusterEmpty,
4902        |reason| AplicacaoError::placement_cluster_invalid(cluster, reason),
4903    )
4904}
4905
4906/// Reject `:placement :affinity` hints whose shape can never legitimately
4907/// land in any downstream selector or label-keyed routing axis. Thin
4908/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4909/// shared parser-shaped reason into the
4910/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
4911/// diagnostic is self-locating (the offending `:affinity` is named
4912/// verbatim) and the author can grep their caixa.lisp for
4913/// `:affinity "<hint>"` and fix it in one edit.
4914///
4915/// The `:affinity` slot carries a placement-engine hint — canonical
4916/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4917/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4918/// compression overlay and the future M4 placement-engine's per-hint
4919/// routing axis. Each downstream consumer (caixa-mesh's
4920/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4921/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4922/// `spec.placement.affinity` admission rule, the future M4 per-hint
4923/// node-affinity / pod-affinity rule generator keying off the same
4924/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4925/// selector) requires the value to be a DNS-1123 label — K8s label
4926/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4927/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4928/// admission rule the apiserver enforces.
4929///
4930/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4931/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4932/// Python-module-name leak), `:affinity "data.locality"` (the
4933/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4934/// `:affinity "data-locality-"` (boundary-hyphen violation),
4935/// `:affinity "data locality"` (paste-from-doc whitespace),
4936/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4937/// 64-byte over-cap slug silently passed the empty-only check and the
4938/// failure surfaced as a no-match at the M3 Adaptive compression
4939/// overlay's filter time (`placement.affinity` carried a malformed
4940/// value, no node matched, the workload landed on the default
4941/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4942/// the empty-:affinity / empty-shard-key / zero-:politicas /
4943/// empty-:contratos-target gates already close on every other
4944/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4945/// gate closes the fifth typed slot on the Aplicacao surface to land
4946/// on the canonical DNS-1123 label floor (after the four Servico-name
4947/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4948/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4949/// b0e8748).
4950///
4951/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4952/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4953/// validated values are guaranteed-accepted by the apiserver without
4954/// re-validation at any downstream renderer or admission layer.
4955fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4956    // Empty is gated separately at the call site for a self-locating
4957    // diagnostic; re-checking here keeps the predicate usable from any
4958    // future call site (the M4 CR materializer's per-affinity
4959    // validator) without an empty-check footgun. Routes through the
4960    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4961    // peer name axes each land on.
4962    crate::render::require_valid_dns_1123_label(
4963        affinity,
4964        || AplicacaoError::PlacementAffinityEmpty,
4965        |reason| AplicacaoError::placement_affinity_invalid(affinity, reason),
4966    )
4967}
4968
4969/// Reject `:placement :shard-key` extractor expressions whose shape can
4970/// never legitimately drive the future M4 Akka-style cluster-sharding
4971/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4972/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4973/// diagnostic is self-locating (the offending `:shard-key` value is
4974/// named verbatim alongside the parser-shaped reason) and the author can
4975/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4976/// edit.
4977///
4978/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4979/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4980/// expression naming the message property to hash on. The realistic
4981/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4982/// property name; `$tenantId` — Akka entity-id placeholder;
4983/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4984/// `${tenant}` — interpolation-style template) all sit in the printable
4985/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4986/// multi-line blob landing in `:shard-key`, an embedded space from a
4987/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4988/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4989/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4990/// check and the failure surfaces at the future M4 reconciler's hash
4991/// pass as a runtime extractor-evaluation error far from the source
4992/// `caixa.lisp`, with no field naming which member's `:shard-key`
4993/// carried the offending value.
4994///
4995/// The contract — the printable ASCII single-token intersection-floor
4996/// every Akka-style entity-id extractor implementation admits:
4997///
4998///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4999///     peer DNS-1123-label-shaped `:placement :affinity` /
5000///     `:placement :clusters` identifier axes; realistic shard-keys sit
5001///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
5002///     blob footguns at validate time;
5003///   - every byte in the printable ASCII range `0x21..=0x7E` —
5004///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
5005///     `"$tenantId\n"` from paste-from-aligned-doc /
5006///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
5007///     `\x7F` — the canonical "embedded null from a copy-paste-binary
5008///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
5009///     un-Punycode-encoded IDN that round-trips inconsistently across
5010///     NFC/NFD normalization).
5011///
5012/// The accepted set is broader than the DNS-1123 label floor the peer
5013/// `:placement :clusters` / `:placement :affinity` axes use because the
5014/// `:shard-key` value is not a K8s `metadata.name` / label-selector
5015/// landing site; it's an extractor expression the future Akka-style
5016/// reconciler reads as a property reference. The realistic forms
5017/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
5018/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
5019/// but every Akka-style entity-id extractor parses. The
5020/// printable-ASCII-token floor accepts every shape any such extractor
5021/// would accept while rejecting the cross-implementation footguns
5022/// (whitespace breaks token boundaries; non-ASCII round-trips
5023/// inconsistently across YAML emitters and NFC/NFD normalization;
5024/// control characters silently corrupt the next read).
5025///
5026/// Until this gate landed `validate_placement` only refused the
5027/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
5028/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
5029/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
5030/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
5031/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
5032/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
5033/// control character from paste-from-binary, the 64-byte over-cap
5034/// paste-from-doc multi-line slug) silently passed validate. The future
5035/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
5036/// would then surface the malformed value either as a runtime
5037/// extractor-evaluation error (whitespace breaks the extractor's token
5038/// boundary, no match) or as a silently-different shard assignment
5039/// across YAML emitters (non-ASCII normalizes differently between the
5040/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
5041/// parser, the same entity ID maps to two distinct shards on a
5042/// re-render). Lifting the shape gate to caixa-build time makes the
5043/// extractor-floor invariant a structural property of every validated
5044/// `Placement`: every `Sharded` placement past `validate_placement` has
5045/// a `:shard-key` the future M4 reconciler can hash without
5046/// re-validating at the runtime layer.
5047///
5048/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
5049/// [`AplicacaoError::ContratoSubjectInvalid`] /
5050/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
5051/// on the peer `:contratos` payload axes — each lifts the
5052/// runtime-side parser's intersection-floor to a caixa-build-time gate,
5053/// closing the canonical "this passed validate but the runtime parser
5054/// rejected it" surprise.
5055fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
5056    // Empty is gated separately at the call site via the more
5057    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
5058    // re-checking here keeps the predicate usable from any future call
5059    // site (the M4 CR materializer's per-shard-key validator) without
5060    // an empty-check footgun.
5061    if key.is_empty() {
5062        return Err(AplicacaoError::ShardedKeyEmpty);
5063    }
5064    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
5065        return Err(AplicacaoError::shard_key_invalid(
5066            key,
5067            format!(
5068                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
5069                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
5070                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
5071                 well under 32 bytes, this length suggests a paste-from-doc \
5072                 multi-line blob landed in `:shard-key` instead of a single-token \
5073                 extractor expression)",
5074                key.len()
5075            ),
5076        ));
5077    }
5078    for &b in key.as_bytes() {
5079        if (0x21..=0x7E).contains(&b) {
5080            continue;
5081        }
5082        let reason = if b == b' ' {
5083            "contains a space (Akka-style entity-id extractor expressions are \
5084             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
5085             whitespace breaks the extractor's token boundary at the runtime layer, \
5086             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
5087             a multi-token blob in one `:shard-key` slot)"
5088                .to_string()
5089        } else if b == b'\t' {
5090            "contains a tab character (paste-from-aligned-doc footgun; the \
5091             Akka-style entity-id extractor reads `:shard-key` as a single-token \
5092             reference, embedded whitespace breaks the token boundary at the \
5093             runtime hash-extractor pass)"
5094                .to_string()
5095        } else if b == b'\n' || b == b'\r' {
5096            format!(
5097                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
5098                 paste-from-multiline-doc footgun; the Akka-style entity-id \
5099                 extractor reads `:shard-key` as a single-token reference, embedded \
5100                 newlines either truncate the value at the YAML emitter layer or \
5101                 break the token boundary at the runtime hash-extractor pass)"
5102            )
5103        } else if b < 0x20 || b == 0x7F {
5104            format!(
5105                "contains control character 0x{b:02x} (the canonical \
5106                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
5107                 control characters silently corrupt round-trip serialization \
5108                 across YAML emitters and break the runtime hash-extractor's \
5109                 single-token parser)"
5110            )
5111        } else {
5112            format!(
5113                "contains non-ASCII byte 0x{b:02x} (the canonical \
5114                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
5115                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
5116                 across YAML emitter implementations — the same entity ID can \
5117                 silently map to two distinct shards on a re-render. Use a \
5118                 printable-ASCII extractor expression like `tenantId`, \
5119                 `$tenantId`, or `metadata.tenantId`)"
5120            )
5121        };
5122        return Err(AplicacaoError::shard_key_invalid(key, reason));
5123    }
5124    Ok(())
5125}
5126
5127/// Reject `:contratos :de` / `:contratos :para` values whose shape
5128/// can never legitimately match a validated `:membros :caixa`. Thin
5129/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
5130/// shared parser-shaped reason into the
5131/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
5132/// diagnostic is self-locating (which slot — `:de` or `:para` — and
5133/// the offending value verbatim) and the author can grep their
5134/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
5135/// one edit.
5136///
5137/// Until this gate landed an empty or DNS-1123-malformed `:de` /
5138/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
5139/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
5140/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
5141/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
5142/// un-Punycode-encoded IDN) silently passed the per-axis check and
5143/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
5144/// membership lookup — diagnostic-framed as "this caixa is not in
5145/// `:membros`" when the root cause is "this `:de` value is not a
5146/// well-shaped Servico-name identifier and could never legitimately
5147/// match any validated member". Because every `:membros :caixa` is
5148/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
5149/// `names` HashSet structurally never contains an empty / malformed
5150/// string, so the membership lookup arm misframes every empty /
5151/// malformed input. Lifting the shape arm ahead of the lookup
5152/// preserves the legitimate `ContratoMemberMissing` arm (a
5153/// well-shaped `:de` that simply isn't in `:membros` — a phantom
5154/// reference) while routing every structurally-impossible-to-match
5155/// input through the narrower self-locating shape diagnostic.
5156///
5157/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
5158/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
5159/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
5160/// to land on the canonical [`crate::render::is_dns_1123_label`]
5161/// floor. The `slot: &'static str` field carries the kebab-case
5162/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
5163/// per-callback-slot diagnostic shape and the
5164/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
5165/// (85f102c) cross-list-tag pattern.
5166fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
5167    // Routes through the shared
5168    // [`crate::render::require_valid_dns_1123_label`] gate the peer
5169    // name axes each land on. The `slot: &'static str` field flows
5170    // through both error variants so the diagnostic names which
5171    // per-edge axis (`:de` vs `:para`) the offending value came from.
5172    crate::render::require_valid_dns_1123_label(
5173        caixa,
5174        || AplicacaoError::contrato_caixa_empty(slot),
5175        |reason| AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
5176    )
5177}
5178
5179/// Reject `:entrada :para` values whose shape can never legitimately
5180/// match a validated `:membros :caixa`. Thin wrapper around
5181/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
5182/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
5183/// variant, so the diagnostic is self-locating (the offending
5184/// `:entrada :para` value is named verbatim) and the author can grep
5185/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
5186///
5187/// Until this gate landed an empty or DNS-1123-malformed `:entrada
5188/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
5189/// ADR typo, `:para "my_cart"` the Python-module-name leak,
5190/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
5191/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
5192/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
5193/// silently passed the per-axis check and surfaced as
5194/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
5195/// — diagnostic-framed as "this caixa is not in `:membros`" when the
5196/// root cause is "this `:entrada :para` value is not a well-shaped
5197/// Servico-name identifier and could never legitimately match any
5198/// validated member". Because every `:membros :caixa` is shape-
5199/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
5200/// `HashSet` structurally never contains an empty / malformed string,
5201/// so the membership lookup arm misframes every empty / malformed
5202/// input. Lifting the shape arm ahead of the lookup preserves the
5203/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
5204/// simply isn't in `:membros` — a phantom reference) while routing
5205/// every structurally-impossible-to-match input through the narrower
5206/// self-locating shape diagnostic.
5207///
5208/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
5209/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
5210/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
5211/// fourth and last Aplicacao-level Servico-name reference axis to
5212/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
5213/// No `slot: &'static str` field because there is only one axis
5214/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
5215/// the simpler shape mirrors [`validate_membro_caixa`] and
5216/// [`validate_placement_cluster`].
5217fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
5218    // Empty is gated separately at the call site for a self-locating
5219    // diagnostic; re-checking here keeps the predicate usable from any
5220    // future call site (the M4 CR materializer's per-`:entrada`
5221    // validator) without an empty-check footgun. Routes through the
5222    // shared [`crate::render::require_valid_dns_1123_label`] gate the
5223    // peer name axes each land on.
5224    crate::render::require_valid_dns_1123_label(
5225        para,
5226        || AplicacaoError::EntradaParaEmpty,
5227        |reason| AplicacaoError::entrada_para_invalid(para, reason),
5228    )
5229}
5230
5231/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
5232/// would refuse at admission time. The contract — exactly the regex
5233/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
5234/// and `HTTPRoute.spec.hostnames[]`,
5235/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
5236/// (max length 253; per-label max length 63):
5237///
5238///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
5239///     uppercase, no underscore, no Unicode/IDN — IDN must be
5240///     pre-encoded as Punycode `xn--…` by the author);
5241///   - exactly one optional leading wildcard label (`*.`); a wildcard
5242///     in any non-leading label position is rejected;
5243///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
5244///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
5245///   - total length 1..=253 bytes;
5246///   - no IPv4 literal (Gateway API forbids IP literals);
5247///   - no scheme (`https://`, `http://`), no port (`:8080`), no
5248///     whitespace, no path (`/`).
5249///
5250/// Lifted as a typed gate (rather than an inline cascade in
5251/// `validate()`) so the contract lives in one place — every future
5252/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5253/// materializer's host validator, the future per-`:entrada` SAN
5254/// emission for cert-manager Certificates, the multi-`:entrada`
5255/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
5256/// for the same predicate, not its own. Same compounding shape as
5257/// `is_canonical_rate_limit_window` (808017c) and
5258/// [`WitTarget::label`] (previously the free `contrato_target_label`
5259/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
5260/// per-variant label match is compiler-checked-exhaustive).
5261///
5262/// The diagnostic carries the offending `host:` verbatim plus a
5263/// parser-shaped `reason:` naming the specific violation, so the
5264/// author can grep their caixa.lisp for `:host "<host>"` and fix it
5265/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
5266/// (9888b13).
5267fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
5268    // Empty is already gated by `EmptyEntradaHost` at the call site;
5269    // re-checking here keeps the predicate usable from any future
5270    // call site (M4 CR materializer) without an empty-check footgun.
5271    if host.is_empty() {
5272        return Err(AplicacaoError::EmptyEntradaHost);
5273    }
5274    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
5275        return Err(AplicacaoError::entrada_host_invalid(
5276            host,
5277            format!(
5278                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
5279                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
5280                host.len(),
5281                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
5282            ),
5283        ));
5284    }
5285    if host.contains("://") {
5286        return Err(AplicacaoError::entrada_host_invalid(
5287            host,
5288            "must not carry a scheme (drop the `https://` or `http://` prefix; \
5289             Gateway API takes the bare hostname)",
5290        ));
5291    }
5292    if host.contains('/') {
5293        return Err(AplicacaoError::entrada_host_invalid(
5294            host,
5295            "must not carry a path (drop the `/…` suffix; Gateway API path \
5296             matching is in `:entrada :paths`)",
5297        ));
5298    }
5299    // After the `://` scheme-prefix and `/` path arms have ruled out the
5300    // two `:`-bearing shapes the Gateway API actively rejects with
5301    // location-shaped diagnostics, any remaining `:` in the host body is
5302    // either the canonical "I put the port in the `:host` slot"
5303    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
5304    // slot lives one axis away on the same `:entrada` block) or an
5305    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
5306    // Hostname forbids identically to the IPv4-literal arm below. Both
5307    // shapes silently fell through the `://` and `/` arms before this
5308    // lift and surfaced as a deep `label "<rest>:<port>" contains
5309    // invalid character ':'` diagnostic from the per-byte loop near the
5310    // bottom of this predicate, which named the offending byte but not
5311    // the canonical authoring fix — for the port case the author has to
5312    // know the `:entrada` block carries a separate `:port u16` slot
5313    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
5314    // move the value over; for the IPv6 case the author has to know
5315    // Gateway API v1 forbids IP literals across the board. The contract
5316    // doc-comment above already promises "no port (`:8080`)" verbatim
5317    // in the rejected-shape enumeration but the predicate's
5318    // implementation refused the `:` only as a side-effect of the
5319    // per-label `[a-z0-9-]` character-class loop; this arm brings the
5320    // implementation in line with the documented contract by surfacing
5321    // the canonical fix at the top-level shape gate, peer with how the
5322    // `://` arm names the scheme prefix and the `/` arm names the
5323    // `:entrada :paths` axis. Same compounding trajectory the recent
5324    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
5325    // — the typed slot's rejected set matches the apiserver's rejected
5326    // set, structurally, with a self-locating diagnostic at the
5327    // offending axis instead of a deep parser-shape leak.
5328    if host.contains(':') {
5329        return Err(AplicacaoError::entrada_host_invalid(
5330            host,
5331            "must not contain `:` (the port belongs in the `:entrada :port` \
5332             slot — a separate `u16` axis on the same `:entrada` block, \
5333             defaulting to 8080 — not in the host body; drop the `:<port>` \
5334             suffix and author the bare hostname. If you intended an IPv6 \
5335             literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
5336             Hostname forbids IP literals identically to the IPv4-literal \
5337             arm — use a DNS name)",
5338        ));
5339    }
5340    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
5341    // predicate — the same single source of truth every peer
5342    // ASCII-whitespace scan in caixa-core flows through: the four
5343    // typed-magnitude codec sites (`limits::parse_byte_size` backing
5344    // `:limits :memory`, `limits::parse_duration` backing `:limits
5345    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
5346    // `aplicacao::rate_limit_codec::parse` backing `:politicas
5347    // :rate-limit`) and the shared duration codec
5348    // (`supervisor::duration_codec::parse`) backing `:supervisor
5349    // :restart-window` / `:politicas :timeout` / `:politicas
5350    // :circuit-breaker :window`. This landing closes the last string-typed
5351    // slot in caixa-core still calling `.bytes().any(|b|
5352    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
5353    // across every typed slot now shares one predicate, so a future
5354    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
5355    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
5356    // deliberately excluded from the peer non-ASCII predicate) can
5357    // extend at this shared site in one edit rather than seven
5358    // independent scans diverging over time. Naming the offending byte
5359    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
5360    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
5361    // the offending byte verbatim" discipline every peer codec site
5362    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
5363    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
5364    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
5365        return Err(AplicacaoError::entrada_host_invalid(
5366            host,
5367            format!(
5368                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
5369                 Hostname is a single-token DNS name — leading, trailing, \
5370                 or embedded whitespace breaks the K8s apiserver's Hostname \
5371                 regex at admission time; the paste-from-aligned-doc / \
5372                 paste-from-shell-history / paste-from-CSV footgun silently \
5373                 lands a multi-token blob in `:entrada :host`. Strip every \
5374                 whitespace byte and author the bare hostname — space \
5375                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
5376                 refuse identically)"
5377            ),
5378        ));
5379    }
5380    // Peer of the ASCII-whitespace scan above: route the non-ASCII
5381    // subset of Unicode `White_Space` through the shared
5382    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
5383    // single source of truth every peer non-ASCII-whitespace scan in
5384    // caixa-core flows through: `limits::parse_byte_size` (`:limits
5385    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
5386    // `limits::parse_millicores` (`:limits :cpu`),
5387    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
5388    // and `supervisor::duration_codec::parse` (`:supervisor
5389    // :restart-window` / `:politicas :timeout` / `:politicas
5390    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
5391    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
5392    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
5393    // paste-from-web-doc), or an EM-SPACE-split host
5394    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
5395    // survived this predicate's ASCII byte-scan (none of the UTF-8
5396    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
5397    // `u8::is_ascii_whitespace`), then landed on the per-label
5398    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
5399    // predicate with the generic `label "…" must start and end with an
5400    // alphanumeric` diagnostic — a "far from source at build-time"
5401    // leak that names the label-shape violation but not the
5402    // paste-from-typography origin the author actually needs to fix.
5403    // Peer with the four codec sites the 1b75b38 landing pinned: the
5404    // typed slot's diagnostic axis names the offending codepoint
5405    // (`U+XXXX`) verbatim rather than laundering the value through a
5406    // downstream label-shape arm, so the author can grep their
5407    // caixa.lisp for the invisible codepoint at the surfaced position
5408    // rather than eyeball a multi-byte host for embedded NBSP / LINE
5409    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
5410    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
5411    // drift between any two typed-slot sites' non-ASCII-whitespace
5412    // rejection set becomes a single-edit fix at the shared predicate
5413    // rather than N independent inline scans diverging over time, and
5414    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
5415    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
5416    // `char::is_whitespace`" class the peer non-ASCII predicate's
5417    // doc-comment names as the follow-up trajectory) extends at the
5418    // shared predicate in one edit rather than seven.
5419    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
5420        return Err(AplicacaoError::entrada_host_invalid(
5421            host,
5422            format!(
5423                "contains non-ASCII Unicode whitespace character {ch:?} \
5424                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
5425                 single-token DNS name limited to `[a-z0-9-]` labels; \
5426                 the paste-from-typography footgun silently lands an \
5427                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
5428                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
5429                 `U+3000`, and every other member of the Unicode \
5430                 `White_Space` property outside the ASCII byte range) \
5431                 in `:entrada :host`, which the K8s apiserver's \
5432                 Hostname regex refuses at admission time far from the \
5433                 caixa.lisp source line. Strip every non-ASCII \
5434                 whitespace character and author the bare hostname \
5435                 with only ASCII bytes (write \"checkout.quero.cloud\" \
5436                 verbatim)",
5437                codepoint = ch as u32,
5438            ),
5439        ));
5440    }
5441
5442    // Strip the optional single leading wildcard label *before* the
5443    // trailing-dot check so the bare `"*."` form surfaces the more
5444    // self-locating "wildcard without domain" diagnostic instead of
5445    // the generic "trailing dot" one.
5446    let (had_wildcard, rest) = match host.strip_prefix("*.") {
5447        Some(r) => (true, r),
5448        None => (false, host),
5449    };
5450    if had_wildcard && rest.is_empty() {
5451        return Err(AplicacaoError::entrada_host_invalid(
5452            host,
5453            "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)",
5454        ));
5455    }
5456    if rest.contains('*') {
5457        return Err(AplicacaoError::entrada_host_invalid(
5458            host,
5459            "wildcard `*` is allowed only as the first label (`*.example.com`); \
5460             no inner or trailing `*` labels",
5461        ));
5462    }
5463    if rest.ends_with('.') {
5464        return Err(AplicacaoError::entrada_host_invalid(
5465            host,
5466            "must not have a trailing `.` (Gateway API hostnames are not \
5467             fully-qualified with a root dot; the apiserver regex rejects \
5468             trailing dots)",
5469        ));
5470    }
5471
5472    // Reject pure IPv4 literals: four dot-separated labels, every
5473    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
5474    // literals as Hostnames.
5475    let labels: Vec<&str> = rest.split('.').collect();
5476    if labels.len() == 4
5477        && labels
5478            .iter()
5479            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
5480    {
5481        return Err(AplicacaoError::entrada_host_invalid(
5482            host,
5483            "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
5484             literals; use a DNS name)",
5485        ));
5486    }
5487
5488    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
5489    // hyphen, with non-hyphen at both boundaries.
5490    for label in &labels {
5491        if label.is_empty() {
5492            return Err(AplicacaoError::entrada_host_invalid(
5493                host,
5494                "has an empty label (consecutive `..` or a leading `.`)",
5495            ));
5496        }
5497        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
5498            return Err(AplicacaoError::entrada_host_invalid(
5499                host,
5500                format!(
5501                    "label {label:?} exceeds DNS-1123 label max length of \
5502                     {cap} bytes (got {} bytes)",
5503                    label.len(),
5504                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
5505                ),
5506            ));
5507        }
5508        let bytes = label.as_bytes();
5509        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
5510            return Err(AplicacaoError::entrada_host_invalid(
5511                host,
5512                format!(
5513                    "label {label:?} must start and end with an alphanumeric \
5514                     (no leading or trailing `-`)"
5515                ),
5516            ));
5517        }
5518        for &b in bytes {
5519            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
5520            if !valid {
5521                let msg = if b.is_ascii_uppercase() {
5522                    format!(
5523                        "label {label:?} contains uppercase character {ch:?} \
5524                         (Gateway API hostnames are lowercase-only; use {lower:?})",
5525                        ch = b as char,
5526                        lower = label.to_ascii_lowercase()
5527                    )
5528                } else if b == b'_' {
5529                    format!(
5530                        "label {label:?} contains `_` (Gateway API hostnames \
5531                         allow only `[a-z0-9-]`; use `-` instead)"
5532                    )
5533                } else {
5534                    format!(
5535                        "label {label:?} contains invalid character {ch:?} \
5536                         (Gateway API hostnames allow only `[a-z0-9-]`)",
5537                        ch = b as char
5538                    )
5539                };
5540                return Err(AplicacaoError::entrada_host_invalid(host, msg));
5541            }
5542        }
5543    }
5544    Ok(())
5545}
5546
5547/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
5548/// would refuse at admission time. Thin wrapper around
5549/// [`crate::render::is_gateway_api_http_path`] that maps the shared
5550/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
5551/// variant, preserving the more self-locating
5552/// [`AplicacaoError::EntradaPathEmpty`] /
5553/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
5554/// path fails those narrower invariants first.
5555///
5556/// The contract is the canonical HTTP-path grammar — `1..=
5557/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
5558/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
5559/// whitespace/control/non-ASCII bytes — shared with the
5560/// `:contratos :endpoint` axis through the lifted predicate so drift
5561/// between either landing site and the K8s apiserver-side
5562/// HTTPPathMatch.value OpenAPI schema is a build error visible at
5563/// the predicate, not a per-renderer "this passed validate but failed
5564/// admission" surprise. The diagnostic carries the offending `path:`
5565/// verbatim plus a parser-shaped `reason:` naming the specific
5566/// violation, so the author can grep their caixa.lisp for `:paths`
5567/// and fix it in one edit. Same diagnostic shape as
5568/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
5569/// axis.
5570fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
5571    // Empty and missing-leading-`/` are already gated at the call
5572    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
5573    // checking here keeps the per-axis narrower diagnostics in force
5574    // when the predicate is reached directly (and `is_gateway_api_http_path`
5575    // itself defends against `bytes[0]`-style indexing on empty
5576    // input).
5577    if path.is_empty() {
5578        return Err(AplicacaoError::EntradaPathEmpty);
5579    }
5580    if !path.starts_with('/') {
5581        return Err(AplicacaoError::entrada_path_not_absolute(path));
5582    }
5583    crate::render::is_gateway_api_http_path(path)
5584        .map_err(|reason| AplicacaoError::entrada_path_invalid(path, reason))
5585}
5586
5587mod rate_limit_codec {
5588    // `Duration` is no longer named here — the codec routes through
5589    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5590    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
5591    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
5592    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
5593    // closed-set enum's arm-table rather than through vestigial free-helper
5594    // delegates.
5595    use super::{RateLimit, RateLimitUnit};
5596    use serde::{Deserializer, Serializer};
5597
5598    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
5599        // Route through the canonical [`crate::render::serialize_option_via_str`]
5600        // — the substrate-side single-owner primitive for the forward
5601        // arm of the typed-magnitude codec family. See its docstring
5602        // for the full sibling roster.
5603        crate::render::serialize_option_via_str(v, s, render)
5604    }
5605
5606    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
5607        // Route through the canonical [`crate::render::deserialize_option_via_str`]
5608        // — the substrate-side single-owner primitive for the reverse
5609        // arm of the typed-magnitude codec family. See its docstring
5610        // for the full sibling roster.
5611        crate::render::deserialize_option_via_str(d, parse)
5612    }
5613
5614    fn parse(s: &str) -> Result<RateLimit, String> {
5615        // Paired whitespace-rejection arm — same canonical-form
5616        // render-determinism discipline as the peer
5617        // `limits::parse_byte_size` / `limits::parse_duration` /
5618        // `limits::parse_millicores` /
5619        // `supervisor::duration_codec::parse` sites: the ASCII
5620        // byte-scan closes the WhatWG-conformant whitespace bytes
5621        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
5622        // `char::is_whitespace` scan closes the strictly-complementary
5623        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
5624        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
5625        // codepoints) that `str::trim` at parse entry silently strips.
5626        // Either drift class would round-trip through `render` to a
5627        // *different* canonical form on next emit — breaking the
5628        // THEORY.md Part V render-determinism contract on
5629        // `:politicas :rate-limit`.
5630        //
5631        // Routed through the lifted [`crate::render::reject_whitespace`]
5632        // primitive — the substrate-side single-owner paired-arm gate
5633        // every typed-magnitude codec in caixa-core shares.
5634        crate::render::reject_whitespace::<String, _, _>(
5635            s,
5636            |b| {
5637                format!(
5638                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
5639                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
5640                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
5641                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
5642                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
5643                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
5644                 on first serialize — breaking the THEORY.md Part V render-determinism \
5645                 contract every typed slot carries. Strip every whitespace byte (write \
5646                 `\"100/s\"` verbatim)"
5647                )
5648            },
5649            |ch| {
5650                format!(
5651                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
5652                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
5653                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
5654                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
5655                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
5656                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
5657                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
5658                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
5659                 silently strips it at parse entry, and the value round-trips through \
5660                 `render` to a *different* canonical form (`\"100/s\"`) on first \
5661                 serialize — breaking the THEORY.md Part V render-determinism contract \
5662                 every typed slot carries. Strip every non-ASCII whitespace character \
5663                 (write `\"100/s\"` verbatim with only ASCII bytes)",
5664                    cp = ch as u32
5665                )
5666            },
5667        )?;
5668        let s = s.trim();
5669        let (rate_str, unit) = s
5670            .split_once('/')
5671            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
5672        let rate_trim = rate_str.trim();
5673        // The canonical authoring form for `:politicas :rate-limit` is
5674        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
5675        // non-negative integer with no decimal point and no leading
5676        // sign, so the parser's accepted set must match for
5677        // serialize/deserialize to round-trip without canonical-form
5678        // drift. Until this gate landed the parser accepted any
5679        // `u32::from_str`-shaped magnitude — and current Rust
5680        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
5681        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
5682        // serde silently round-tripped to `"100/s"` on the next emit
5683        // (a *different* canonical string) — breaking the THEORY.md
5684        // Part V render-determinism contract on the fifth typed-codec
5685        // surface in caixa-core (peer with the four duration codecs the
5686        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
5687        // already covered: `supervisor::duration_codec` backing three
5688        // typed-duration slots, `limits::parse_duration` backing
5689        // `:limits :wall-clock`, `limits::parse_byte_size` backing
5690        // `:limits :memory`). The fractional / decimal-shaped sibling
5691        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
5692        // existing rejection arm, but the diagnostic is value-laundered
5693        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
5694        // doesn't name the canonical-form remediation or the round-trip
5695        // drift the next emit would produce); this gate lifts the
5696        // fractional arm onto the same canonical-form diagnostic the
5697        // peer codecs carry.
5698        //
5699        // Strict canonical form: every byte of the magnitude is an
5700        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
5701        // inputs the gate distinguishes "non-canonical-but-numeric"
5702        // (parses as f64 or i64 — surfaced with a self-locating
5703        // diagnostic naming the canonical authoring form and the
5704        // round-trip drift the rejected shape would produce on first
5705        // serialize) from "garbage" (parses as neither — surfaced with
5706        // the existing narrower `"not a u32"` wording so its
5707        // diagnostic shape remains stable for the parser-shape footgun
5708        // case).
5709        //
5710        // Routed through the lifted
5711        // [`crate::render::is_digit_only_magnitude`] predicate — the
5712        // same source of truth the four peer typed-magnitude codec
5713        // sites share.
5714        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
5715        if !digit_only {
5716            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
5717            if numeric {
5718                return Err(format!(
5719                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
5720                     canonical authoring form for `:politicas :rate-limit` is \
5721                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5722                     with no decimal point and no leading `+` / `-` sign. A fractional / \
5723                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
5724                     through `render` to a *different* canonical form (`\"1/s\"`, \
5725                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
5726                     THEORY.md Part V render-determinism contract every typed slot \
5727                     carries. Pick an integer rate that fits the desired window \
5728                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
5729                ));
5730            }
5731            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
5732        }
5733        // Leading-zero arm — peer with the prior `"+100/s"` arm above
5734        // (4eeae98's predecessor) on the same canonical-form
5735        // render-determinism axis. The digit-only gate accepts
5736        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
5737        // them losslessly (= 100, 0, 7), but `render` emits the
5738        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
5739        // a *different* canonical string on the next emit, breaking
5740        // the THEORY.md Part V render-determinism contract the same
5741        // way `"+100/s"` did before the leading-`+` arm landed. The
5742        // single-byte magnitude `"0"` itself round-trips losslessly
5743        // through `render` (`render(0)` emits `"0/s"`) — the
5744        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
5745        // what refuses rate-zero authoring, so `"0/s"` stays in the
5746        // accepted set at this codec layer and the diagnostic
5747        // partitioning between canonical-form drift (this arm) and
5748        // semantic-zero (the downstream gate) remains stable.
5749        // Peer with the future leading-zero arms on the three peer
5750        // typed-magnitude codecs the trajectory acknowledges:
5751        // `supervisor::duration_codec`, `limits::parse_duration`,
5752        // `limits::parse_byte_size` — each carries the same
5753        // canonical-form-drift class today; this gate lands the
5754        // discipline on the fourth typed-magnitude codec in
5755        // caixa-core first because the peer `"+100/s"` arm above is
5756        // the closest predecessor on the trajectory.
5757        //
5758        // Routed through the lifted
5759        // [`crate::render::is_leading_zero_padded_magnitude`]
5760        // predicate — the same source of truth the four peer
5761        // typed-magnitude codec sites share.
5762        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
5763            return Err(format!(
5764                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
5765                 canonical authoring form for `:politicas :rate-limit` is \
5766                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
5767                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
5768                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
5769                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
5770                 first serialize — breaking the THEORY.md Part V render-determinism \
5771                 contract every typed slot carries. Strip the leading zeros (write \
5772                 `\"100/s\"` instead of `\"0100/s\"`)"
5773            ));
5774        }
5775        // The digit-only gate guarantees every byte is `[0-9]`, and
5776        // the leading-zero arm above guarantees the magnitude is
5777        // either the single byte `"0"` or starts with `[1-9]`, so
5778        // the only way `u32::from_str` can fail here is overflow
5779        // (the magnitude exceeds `u32::MAX`). Surface that with an
5780        // overflow-shaped wording so the diagnostic names the
5781        // offending magnitude verbatim rather than collapsing onto
5782        // the non-canonical arm. Same shape
5783        // `supervisor::duration_codec` (1c55a2a) carries on the peer
5784        // duration-codec axis.
5785        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
5786            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
5787        })?;
5788        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
5789        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
5790        // arm reads the `&str → Duration` projection through the
5791        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5792        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
5793        // with [`super::RateLimitUnit::window`]) rather than the vestigial
5794        // module-private `rate_limit_window_from_unit` free helper the
5795        // predecessor 61421a6 left as the last unlifted delegate on this
5796        // axis. One typed dispatch on the substrate primitive instead of
5797        // one runtime call through the free-helper delegate; the sole
5798        // production consumer of the `&str → Duration` axis (this parse
5799        // arm) now reaches for exactly one typed method on the closed-set
5800        // enum, sibling to the codec's render arm's
5801        // [`super::RateLimit::canonical_unit`] dispatch on the paired
5802        // `Duration → RateLimitUnit` axis and to the validate gate's
5803        // [`super::RateLimit::canonical_unit`] shape-probe on the
5804        // canonical-window axis. A future rate-limit-unit addition (a
5805        // `"d"` day suffix once Envoy's `rate_limit_action` grows
5806        // daily-bucket support, a `"ms"` sub-second window once
5807        // high-throughput per-edge policies come into scope per
5808        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
5809        // on the closed-set enum, and the compiler enforces exhaustiveness
5810        // on every consumer's `match self` arms — this parse arm's
5811        // accepted-suffix set, the render arm's emitted-suffix set, the
5812        // validate gate's canonical-window set, and every future
5813        // per-`:contratos`-edge rate-limit-override overlay all pick it up
5814        // by construction.
5815        let unit = unit.trim();
5816        let window = RateLimitUnit::window_from_suffix(unit)
5817            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
5818        Ok(RateLimit { rate, window })
5819    }
5820
5821    fn render(rl: RateLimit) -> String {
5822        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
5823        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
5824        // this render arm reads the `Duration → RateLimitUnit` projection
5825        // through the substrate primitive [`super::RateLimit::canonical_unit`]
5826        // (returns `None` on every non-canonical window — the sub-second /
5827        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
5828        // formats the returned typed enum through its
5829        // [`std::fmt::Display`] impl (which routes through
5830        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
5831        // the substrate primitive instead of one runtime `find_map`
5832        // walk through the free-helper delegate chain
5833        // [`super::rate_limit_window_unit`] (the vestigial free helper's
5834        // sole production consumer was this arm; every other consumer of
5835        // the `Duration → unit` axis — the validate gate below and the
5836        // future M4 per-Aplicacao Envoy config reconciler — now reads
5837        // the same typed method).
5838        //
5839        // A future rate-limit-unit addition (a `"d"` day suffix once
5840        // Envoy's `rate_limit_action` grows daily-bucket support) is
5841        // one variant + one arm per method on the closed-set enum, and
5842        // the compiler enforces exhaustiveness on every consumer's
5843        // `match self` arms — the codec's `parse` accepted-suffix set,
5844        // this render arm's emitted-suffix set, the validate gate's
5845        // canonical-window set, and every future per-`:contratos`-edge
5846        // rate-limit-override overlay all pick it up by construction.
5847        if let Some(unit) = rl.canonical_unit() {
5848            format!("{}/{unit}", rl.rate())
5849        } else {
5850            // Defensive fallback for non-canonical windows. Note:
5851            // [`AplicacaoSpec::validate_politicas`] rejects any
5852            // non-canonical `:rate-limit :window` via
5853            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5854            // a validated `RateLimit` never reaches this branch. The
5855            // emitted `<n>/<k>s` form is *not* round-trippable through
5856            // [`parse`] (which accepts only the closed-set
5857            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5858            // explicit count) — the validate gate is what makes the
5859            // round-trip a structural property; this branch exists only
5860            // so a programmatic non-validated serialize doesn't panic.
5861            format!("{}/{}s", rl.rate(), rl.window().as_secs())
5862        }
5863    }
5864}
5865
5866// ── placement strategy ───────────────────────────────────────────────
5867
5868/// How the Aplicacao distributes across clusters. Three options:
5869///
5870/// - `SingleNode` — one cluster runs the app at a time; takeover on
5871///   death (Erlang/OTP distributed-app semantics).
5872/// - `Replicated` — every named cluster runs an instance (active-active).
5873/// - `Sharded` — entities distribute by hash key across clusters
5874///   (Akka cluster sharding).
5875#[derive(
5876    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5877)]
5878pub enum PlacementStrategy {
5879    SingleNode,
5880    Replicated,
5881    Sharded,
5882}
5883
5884/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5885/// distribution-strategy default for the `:placement :estrategia` axis —
5886/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5887/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5888/// so every substrate-side consumer that resolves "what
5889/// [`PlacementStrategy`] variant does an author-omitted `:placement
5890/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5891/// primitive [`PlacementStrategy`].
5892///
5893/// The `:placement :estrategia` default axis has three production
5894/// consumers on the substrate side today: the [`Default for
5895/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5896/// impl's struct-literal `estrategia` field, and the serde-side
5897/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5898/// author-omitted `:placement :estrategia` scalar through the [`Default
5899/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5900/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5901/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5902/// consumers, with no compile-time link back to the paired
5903/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5904/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5905/// production consumer that resolves an author-omitted `:placement` slot
5906/// (entirely omitted, not just the `:estrategia` scalar within a declared
5907/// `:placement` block) through [`Placement::default`] which then routes
5908/// through this same discriminator. A future coherent rebrand of the
5909/// `:placement :estrategia` default (a widening to `Sharded` once the
5910/// substrate discovers hash-keyed distribution as the more common
5911/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5912/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5913/// names, a per-cluster overlay the operator pins through a future
5914/// `:placement-overrides` slot) would have had to migrate a lifted
5915/// discriminator on one path and open-coded discriminators on the peers
5916/// in lockstep or the four consumers would silently drift out of
5917/// pairing. Lifting the resolution rule to a typed `pub const` on the
5918/// substrate primitive means the M3-mesh-canonical `:placement
5919/// :estrategia` default migrates as one unit on any future axis change.
5920///
5921/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5922/// §II.2's active-active-across-every-named-cluster arm — the closest
5923/// canonical M3 production reference the substrate carries, matching the
5924/// caixa-mesh default axis every M3 renderer already keys off (a
5925/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5926/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5927/// under the substrate's fleet-programs aggregator without an explicit
5928/// `:placement :estrategia` override). The two alternatives the closed
5929/// [`PlacementStrategy::ALL`] accept-set carries
5930/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5931/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5932/// Akka-style hash-keyed distribution across clusters,
5933/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5934/// postures an author declares explicitly, never a posture an omitted
5935/// slot should silently assume.
5936///
5937/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5938/// exactly one source of truth on the `:placement :estrategia` axis, on
5939/// the same substrate-primitive lift discipline the sibling M2
5940/// per-supervisor default set carries
5941/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5942/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5943/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5944/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5945/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5946/// ([`crate::render::DEFAULT_NAMESPACE`],
5947/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5948/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5949/// the M3 mesh-primitive-defining slot family to converge onto the
5950/// substrate-primitive-lift discipline the M2 supervisor-slot family
5951/// already carries end-to-end.
5952pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5953
5954impl Default for PlacementStrategy {
5955    fn default() -> Self {
5956        // Route the [`Default for PlacementStrategy`] impl through the
5957        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5958        // `pub const` rather than a raw `Self::Replicated` arm — one
5959        // source of truth for the M3-mesh-canonical active-active-
5960        // across-every-named-cluster `:placement :estrategia` default
5961        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5962        // lift discipline the sibling M2 per-supervisor default set
5963        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5964        // paired halves) carries end-to-end. Pinned by
5965        // `placement_strategy_default_routes_through_lifted_default`.
5966        PLACEMENT_ESTRATEGIA_DEFAULT
5967    }
5968}
5969
5970impl PlacementStrategy {
5971    /// Exhaustive iteration surface for every consumer that reads the
5972    /// full closed-set (the future M4 admission-webhook's accepted-
5973    /// strategy listing in its rejection body, a future `feira app
5974    /// placement --list` CLI-side surfacing of the accepted arm-set,
5975    /// any future round-trip fuzz harness). A future variant addition
5976    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5977    /// names as a trajectory item) extends this slice as a single edit
5978    /// and every consumer picks up the new entry by construction — the
5979    /// compiler-checked exhaustiveness on the sibling method `match`
5980    /// arms is the build-time guarantee that no arm forgets to grow.
5981    /// Same shape as the sibling closed-set typed enums'
5982    /// [`RateLimitUnit::ALL`] (6bce03d) and
5983    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5984    /// surfaces — the third closed-set typed enum on the caixa surface
5985    /// to converge onto the same discipline.
5986    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5987
5988    /// Canonical camelCase-schema discriminator scalar this variant
5989    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5990    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5991    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5992    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5993    /// every substrate consumer that dispatches on the strategy (the
5994    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5995    /// reconciler, the M3 Adaptive compression pass) reads the same
5996    /// byte-string the `Serialize` derive emits — the pin test in
5997    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5998    /// asserts the two paths agree.
5999    #[must_use]
6000    pub const fn as_str(self) -> &'static str {
6001        match self {
6002            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
6003            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
6004            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
6005        }
6006    }
6007
6008    /// Substrate-canonical reverse projection on the `:placement
6009    /// :estrategia` closed-set axis — parses the camelCase-schema
6010    /// discriminator scalar back to the typed variant, or `None` when
6011    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
6012    /// emits. Dispatches on the same lifted
6013    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6014    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6015    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
6016    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
6017    /// the round-trip migrate through one caixa-core edit on any future
6018    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
6019    /// §II.5 hint names as a trajectory item lands one variant + one
6020    /// arm per method and the compiler enforces exhaustiveness on every
6021    /// consumer's `match self` arms).
6022    ///
6023    /// Prior to this lift the substrate carried only the forward
6024    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
6025    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
6026    /// derive that emits the same byte-string under
6027    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
6028    /// consumer that wanted to parse a wire-form strategy scalar had to
6029    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
6030    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
6031    /// compile-time link back to the typed variant's canonical lifted
6032    /// constant. A future variant rename or a per-arm serde-attribute
6033    /// drift would silently split the wire byte-string one non-serde
6034    /// consumer parsed from the one the emitter wrote, with the
6035    /// failure surfacing at parse time far from the rebrand commit.
6036    ///
6037    /// Same closed-set-reverse-projection discipline the sibling
6038    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
6039    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
6040    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
6041    /// defining `:placement :estrategia` closed-set axis, the third
6042    /// substrate-side closed-set typed enum to converge on the two-way
6043    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
6044    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
6045    /// and side-step the [`std::str::FromStr`]-collision clippy
6046    /// (`clippy::should_implement_trait`) the plain `from_str` name
6047    /// carries; a future explicit [`std::str::FromStr`] impl can layer
6048    /// on top by delegating to this canonical arm-dispatch method.
6049    ///
6050    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
6051    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
6052    /// picks the diagnostic form appropriate for its use site — a
6053    /// future `feira app placement --set` CLI-side arg-parse that wants
6054    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
6055    /// Sharded)"` diagnostic builds one on top by iterating
6056    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
6057    /// path folds `None` onto its per-CR structured refusal body.
6058    #[must_use]
6059    pub fn from_wire(s: &str) -> Option<Self> {
6060        match s {
6061            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
6062            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
6063            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
6064            _ => None,
6065        }
6066    }
6067
6068    /// Substrate-canonical per-arm predicate naming the cross-slot
6069    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
6070    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
6071    /// consumes the paired [`Placement::shard_key`] axis (and therefore
6072    /// requires — and is the only strategy that permits — a non-empty
6073    /// `:shard-key` on the paired slot). Today the accept-set is the
6074    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
6075    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
6076    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
6077    /// distributed-app takeover — §II.1) and `Replicated` (active-active
6078    /// across every named cluster) have no hash-keyed routing axis to
6079    /// consume the slot and refuse a declared-but-inert `:shard-key`
6080    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
6081    ///
6082    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
6083    /// satisfies `placement.shard_key().is_some() ==
6084    /// placement.estrategia().requires_shard_key()` by construction — the
6085    /// cross-slot partition the pin
6086    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
6087    /// locks load-bearing, so every downstream consumer that reaches for
6088    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6089    /// CR materializer's per-CR shard-key resolver, the future
6090    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
6091    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
6092    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
6093    /// shard-key requirement probe, a future author-facing tatara-lisp
6094    /// linter that flags `(:placement (:estrategia Replicated :shard-key
6095    /// "tenantId"))` shapes before `feira lint` reaches
6096    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
6097    /// the substrate primitive — the predicate names *the cross-slot
6098    /// invariant*, not the arm identity.
6099    ///
6100    /// Prior to this lift the "does this strategy consume `:shard-key`"
6101    /// classification lived under the `gen_platform::IsVariant`-derived
6102    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
6103    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
6104    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
6105    /// } else { None }` cascade, the
6106    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
6107    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
6108    /// "tenantId".to_string())` cascade, and the
6109    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
6110    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
6111    /// cascade). Each site conflated two semantically distinct questions:
6112    /// "is the variant `Sharded`?" (arm-identity, what
6113    /// [`Self::is_sharded`] answers) and "does the variant consume
6114    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
6115    /// The two questions land on the same three-way answer under today's
6116    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
6117    /// future arm addition that consumed `:shard-key` under a different
6118    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
6119    /// §II.5 roadmap-hint names that hash-partitions across the cluster
6120    /// pool by client-IP hash rather than an author-declared extractor
6121    /// expression, a hypothetical `WeightedShard` variant that carries a
6122    /// shard-key + per-cluster weight table under a promoted M5
6123    /// adaptive-placement engine) or an addition that did *not* consume
6124    /// `:shard-key` on a semantically Sharded-shaped arm would silently
6125    /// split the two questions. Any consumer that read
6126    /// `.is_sharded().then(…)` for the shard-key requirement gate would
6127    /// silently misclassify the new arm as non-consuming — a fixture
6128    /// builder would omit `:shard-key` where the new arm required one and
6129    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
6130    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
6131    /// commit, a future M4 CR materializer would fall through the
6132    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
6133    /// silently emit an empty extractor at the Akka reconciler layer.
6134    ///
6135    /// Lifting the classification as a substrate-primitive method on the
6136    /// closed-set typed enum names the cross-slot invariant on the
6137    /// primitive that owns the partition: every future arm addition
6138    /// declares its `:shard-key` consumption in one place (this predicate's
6139    /// `match self` arm-set), and every downstream consumer that reaches
6140    /// for the paired shape reads through one typed dispatch. Same
6141    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
6142    /// per-arm predicate on the pre-projection WIT-shape axis and the
6143    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
6144    /// paired predicate on the post-projection typed-view axis — a
6145    /// per-arm semantic-classification predicate paired with the
6146    /// arm-identity predicate the derive already emits, closing the drift
6147    /// footgun on the cross-slot invariant axis.
6148    ///
6149    /// Method-named `requires_shard_key` (not `has_shard_key`, not
6150    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
6151    /// invariant reads as "this strategy *requires* the paired
6152    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
6153    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
6154    /// merely omit it. The `has_*` framing would read as an accessor
6155    /// (returning the presence of an already-carried value) rather than a
6156    /// requirement (naming the invariant the paired slot must satisfy).
6157    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
6158    /// shape as the sibling [`WitContract::is_capability`] /
6159    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
6160    /// arm-family, so every consumer reaches for `.requires_shard_key()`
6161    /// as a drop-in replacement for the `.is_sharded()` conflated read
6162    /// without a return-shape migration.
6163    #[must_use]
6164    pub const fn requires_shard_key(self) -> bool {
6165        match self {
6166            Self::Sharded => true,
6167            Self::SingleNode | Self::Replicated => false,
6168        }
6169    }
6170}
6171
6172// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
6173// cross-slot-invariant per-arm predicate: the module-scope const-eval
6174// assertions below trip at caixa-core build time (not test time) if a
6175// future edit rewires the predicate's arm-set away from the singleton
6176// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
6177// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
6178// runtime pin covers the same truth-table with a more descriptive
6179// diagnostic on failure; these const-eval items add a build-time failure
6180// surface strictly stronger than the runtime pin (a downstream renderer's
6181// `const`-context reader that composed against a rebound predicate would
6182// still surface here before the test suite even ran) and side-step the
6183// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
6184// would otherwise accumulate on the caixa-core module baseline.
6185const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
6186const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
6187const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
6188
6189/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
6190/// the pretty-printed byte-string every consumer that formats the strategy
6191/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
6192/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
6193/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
6194/// per-Aplicacao strategy line, the future M4 CR materializer's per-
6195/// admission-webhook rejection body) reaches for the same lifted
6196/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6197/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6198/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
6199/// `Serialize` derive already emits under
6200/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
6201/// [`PlacementStrategy::as_str`] helper already returns.
6202///
6203/// Until this lift landed the sibling OTP-shape typed enums —
6204/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
6205/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
6206/// so [`std::fmt::Display`] routes through the same discriminant string
6207/// the wire format emits) — carried a stable [`std::fmt::Display`]
6208/// surface but [`PlacementStrategy`] did not; every consumer reaching
6209/// for a strategy byte-string past the wire format had to pick between
6210/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
6211/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
6212/// derive), any two of which a future variant rename or
6213/// `#[serde(rename_all = "kebab-case")]` attribute would silently
6214/// desynchronize — with the failure surfacing as a downstream renderer /
6215/// operator's per-strategy dispatch reading one spelling while the wire
6216/// format emitted another, far from the source rebrand commit and with
6217/// no field naming the drift. Routing `Display` through
6218/// [`PlacementStrategy::as_str`] makes the three paths
6219/// (`Debug` for structural inspection, `Display` for user-facing text,
6220/// `Serialize` for the wire format) converge on the same lifted
6221/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
6222/// the diagnostic byte-string, and the pretty-printed byte-string move
6223/// as a single unit through one canonical declaration each, by
6224/// construction. Same trajectory as [`PlacementStrategy::as_str`]
6225/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
6226/// closes the third path.
6227///
6228/// Pin tests
6229/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
6230/// and
6231/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
6232/// assert the three paths agree byte-for-byte on every variant, so a
6233/// future variant rename or per-arm serde attribute drift is a build
6234/// error visible at caixa-core test time, not a silent per-consumer
6235/// dispatch miss at apply / reconcile time.
6236impl std::fmt::Display for PlacementStrategy {
6237    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
6238        f.write_str(self.as_str())
6239    }
6240}
6241
6242/// Substrate-canonical [`AsRef<str>`] projection on the M3
6243/// per-Aplicacao distribution-strategy [`PlacementStrategy`] closed-set
6244/// typed enum — routes through the same [`PlacementStrategy::as_str`]
6245/// `pub const fn` scalar accessor the paired [`std::fmt::Display`] impl
6246/// and the un-`rename`d [`serde::Serialize`] derive already key off, so
6247/// any future consumer that binds a [`PlacementStrategy`] through the
6248/// standard-library `impl AsRef<str>` bound (a future `feira app
6249/// placement --set <arm>` verb that composes the emitted
6250/// `PascalCase`/camelCase wire scalar into a
6251/// [`std::process::Command::arg`] shell-out of the future
6252/// `lareira-fleet-programs` aggregator's per-Aplicacao gate, a
6253/// per-Aplicacao structured-log recorder on the future `app-operator`'s
6254/// hierarchical reconciliation surface that accepts `impl AsRef<str>`
6255/// at the `tracing::field::Value` `Str`-arm, a
6256/// [`std::collections::HashMap`] lookup keyed on the strategy wire byte
6257/// through `map.get::<str>(strategy.as_ref())` on a future
6258/// per-strategy dispatch table the M5 adaptive-placement engine
6259/// composes) reaches the paired
6260/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
6261/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
6262/// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted-const
6263/// through one substrate-primitive dispatch rather than an open-coded
6264/// `.as_str()` projection at every wire-up.
6265///
6266/// Peer of the sibling [`std::fmt::Display`] impl on the same
6267/// primitive — both delegate to the shared
6268/// [`PlacementStrategy::as_str`] `pub const fn` accessor, so
6269/// [`format!("{v}")`], `v.as_str()`, and `<PlacementStrategy as
6270/// AsRef<str>>::as_ref(&v)` resolve to the same byte-string per
6271/// instance by construction. A future variant rename or `#[serde(rename_all
6272/// = "kebab-case")]` attribute-drift on the enum reaches every one of
6273/// the three paths (plus the wire-format `Serialize` derive that
6274/// already routes through the same lifted const) through exactly one
6275/// caixa-core edit.
6276///
6277/// Same "route the trait impl through the substrate-primitive
6278/// accessor" discipline the sibling [`crate::CaixaVersion`]
6279/// [`AsRef<str>`] impl (16d5c7e), the paired M2
6280/// [`crate::supervisor::RestartStrategy`] [`AsRef<str>`] impl
6281/// (63eb1a4), and the paired M2 [`crate::supervisor::RestartPolicy`]
6282/// [`AsRef<str>`] impl (419ea81) carry — closes the M2/M3
6283/// closed-set-typed-enum family's standard-library [`AsRef<str>`]
6284/// projection axis onto the last remaining M3 mesh-primitive-defining
6285/// slot, so every OTP/mesh-shape closed-set typed enum on the caixa
6286/// surface now carries the paired [`AsRef<str>`] + [`fmt::Display`] +
6287/// `as_str` triple through one lifted `M3_PLACEMENT_ESTRATEGIA_*` /
6288/// `SUPERVISOR_*` const. Rust-side newtype/typed-enum convention pairs
6289/// [`AsRef<str>`] and [`fmt::Display`] on the same primitive so a
6290/// caller who has one has both; before this lift,
6291/// [`PlacementStrategy`] carried [`fmt::Display`] but not the paired
6292/// [`AsRef<str>`] impl the convention names.
6293///
6294/// Pinned load-bearing by
6295/// [`tests::placement_strategy_as_ref_str_routes_through_as_str_accessor`]
6296/// (byte-parity pin against [`PlacementStrategy::as_str`] across the
6297/// three-arm closed set) and
6298/// [`tests::placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`]
6299/// (three-path convergence: `AsRef<str>` + `Display` + `as_str` all
6300/// resolve to the same lifted `M3_PLACEMENT_ESTRATEGIA_*` const per
6301/// arm) — any future silent detour that routes the impl through a
6302/// divergent projection (a per-arm inline `match self { … }`
6303/// re-inlining that opens a compile-time link to the un-lifted
6304/// arm-literal, a swap onto the kebab-case
6305/// [`gen_platform::Discriminant`] catalog identity that would collide
6306/// the wire axis with the dispatcher-catalog axis) trips at
6307/// caixa-core test time under `assert_eq!` rather than at a downstream
6308/// `impl AsRef<str>`-bound consumer's silent split.
6309impl AsRef<str> for PlacementStrategy {
6310    fn as_ref(&self) -> &str {
6311        self.as_str()
6312    }
6313}
6314
6315/// Where the Aplicacao runs.
6316#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6317#[serde(rename_all = "camelCase")]
6318pub struct Placement {
6319    /// Distribution strategy.
6320    #[serde(default)]
6321    pub estrategia: PlacementStrategy,
6322
6323    /// Named clusters that host this Aplicacao. Required for
6324    /// `Replicated` and `SingleNode`; for `Sharded` declares the
6325    /// shard pool.
6326    #[serde(default)]
6327    pub clusters: Vec<String>,
6328
6329    /// Optional hint to the placement engine: `"data-locality"`,
6330    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
6331    #[serde(default, skip_serializing_if = "Option::is_none")]
6332    pub affinity: Option<String>,
6333
6334    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
6335    #[serde(default, skip_serializing_if = "Option::is_none")]
6336    pub shard_key: Option<String>,
6337}
6338
6339impl Placement {
6340    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
6341    /// `:shard-key` extractor-expression scalar accessor every consumer
6342    /// of the Aplicacao's hash-keyed distribution routing keys off —
6343    /// returns the author-declared `:placement :shard-key` byte-string
6344    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
6345    /// own `Option<String>` storage; `None` when the slot is absent
6346    /// (the canonical shape under `:estrategia Replicated` /
6347    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
6348    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
6349    /// partition — `validate` refuses any `Placement` past this call
6350    /// that lands `Some` on a non-`Sharded` strategy or `None` on
6351    /// `Sharded`).
6352    ///
6353    /// The `:placement :shard-key` slot carries the Akka-style
6354    /// cluster-sharding entity-id extractor expression
6355    /// (MESH-COMPOSITION §II.4) — validated by
6356    /// [`validate_placement_shard_key`] to be a non-empty printable-
6357    /// ASCII single-token reference (`tenantId`, `$tenantId`,
6358    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
6359    /// future M4 Akka-style cluster-sharding reconciler hashes without
6360    /// re-validating at the runtime layer), and every downstream
6361    /// consumer that reads the key keys off this scalar (the
6362    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
6363    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6364    /// declared-but-inert refusal diagnostic, the caixa-mesh
6365    /// per-Aplicacao `placement.shardKey` emit path the substrate
6366    /// operator's per-entity hash-routing reader consumes, the future
6367    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6368    /// per-shard-key resolver).
6369    ///
6370    /// Prior to this lift the `.shard_key` field was accessed inline at
6371    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
6372    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
6373    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
6374    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
6375    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
6376    /// — two open-coded field-accesses that expressed no compile-time
6377    /// link back to the typed slot. A future extension of the
6378    /// `:placement :shard-key` axis to a richer author surface — a
6379    /// per-cluster override the operator pins through a future
6380    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
6381    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
6382    /// alias table the M4 CR materializer resolves per-CR, a
6383    /// per-Aplicacao dynamic `:shard-key` derivation the future
6384    /// adaptive placement engine computes from `:affinity` weights —
6385    /// would have had to be threaded through both open-coded copies in
6386    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
6387    /// arm refusal would silently disagree on which extractor
6388    /// expression a given Placement resolves to. Lifting the resolution
6389    /// rule to a typed method on the substrate primitive means every
6390    /// downstream consumer of the Aplicacao's per-`:placement`
6391    /// hash-key surface reaches for exactly one typed dispatch — the
6392    /// resolver's accept-set migrates as a unit on any future axis
6393    /// addition.
6394    ///
6395    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
6396    /// [`WitContract::destination`] / [`WitContract::world_ref`]
6397    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
6398    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
6399    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
6400    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
6401    /// typed dispatch on the substrate primitive, thin projections at
6402    /// each consumer" discipline extended onto the per-`:placement`
6403    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
6404    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
6405    /// — opens the "optional per-slot scalar" projection pattern the
6406    /// sibling per-`:placement` `:affinity`, per-`:politicas`
6407    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
6408    /// match the storage field's name; the accessor's identity name
6409    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
6410    /// slot's docstring already carries.
6411    #[must_use]
6412    pub const fn shard_key(&self) -> Option<&str> {
6413        match &self.shard_key {
6414            Some(s) => Some(s.as_str()),
6415            None => None,
6416        }
6417    }
6418
6419    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
6420    /// compression-hint scalar accessor every weighting-consumer of the
6421    /// Aplicacao's per-hint routing surface keys off — returns the
6422    /// author-declared `:placement :affinity` byte-string verbatim as
6423    /// an `Option<&str>`, borrowed from the typed slot's own
6424    /// `Option<String>` storage; `None` when the slot is absent (the
6425    /// canonical shape of an Aplicacao that leaves the compression
6426    /// weighting up to the placement engine's cluster-default arm — no
6427    /// author-authored `data-locality` / `low-latency` / etc. hint
6428    /// biases the routing).
6429    ///
6430    /// The `:placement :affinity` slot carries the M3 Adaptive-
6431    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
6432    /// by [`validate_placement_affinity`] to be a DNS-1123 label
6433    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
6434    /// K8s-conformant label-selector shape every apiserver-side pod-
6435    /// affinity / node-affinity materializer already gates on
6436    /// admission), and every downstream consumer that reads the hint
6437    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
6438    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
6439    /// `placement.affinity` overlay emit path the substrate operator's
6440    /// per-hint weighting-consumer reads, the future M4
6441    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
6442    /// pod-affinity / node-affinity selector resolver).
6443    ///
6444    /// Prior to this lift the `.affinity` field was accessed inline at
6445    /// the sole caixa-core site — the
6446    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
6447    /// `if let Some(a) = &self.placement.affinity { …
6448    /// validate_placement_affinity(a)? … }` cascade — one open-coded
6449    /// field-access that expressed no compile-time link back to the
6450    /// typed slot. A future extension of the `:placement :affinity`
6451    /// axis to a richer author surface — a per-cluster override the
6452    /// operator pins through a future `:placement :affinity-overrides`
6453    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
6454    /// tenant hint alias table the M4 CR materializer resolves per-CR,
6455    /// a per-Aplicacao dynamic `:affinity` derivation the future
6456    /// adaptive placement engine computes from `:clusters` topology —
6457    /// would have had to be threaded through the open-coded copy in
6458    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
6459    /// materializer reader that landed on the axis, or the per-hint
6460    /// value-shape gate and its downstream weighting consumers would
6461    /// silently disagree on which hint a given Placement resolves to.
6462    /// Lifting the resolution rule to a typed method on the substrate
6463    /// primitive means every downstream consumer of the Aplicacao's
6464    /// per-`:placement` compression-hint surface reaches for exactly
6465    /// one typed dispatch — the resolver's accept-set migrates as a
6466    /// unit on any future axis addition.
6467    ///
6468    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
6469    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
6470    /// optional-scalar axis — same "one typed dispatch on the substrate
6471    /// primitive, thin projections at each consumer" discipline extended
6472    /// onto the per-`:placement` M3-Adaptive-compression-hint
6473    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
6474    /// return accessor on the M3 mesh-slot family; closes the last
6475    /// un-lifted per-`:placement` `Option<String>` axis. Named
6476    /// `affinity()` to match the storage field's name; the accessor's
6477    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
6478    /// vocabulary the slot's docstring already carries.
6479    #[must_use]
6480    pub const fn affinity(&self) -> Option<&str> {
6481        match &self.affinity {
6482            Some(s) => Some(s.as_str()),
6483            None => None,
6484        }
6485    }
6486
6487    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
6488    /// strategy scalar accessor every consumer that dispatches on the
6489    /// Aplicacao's per-cluster distribution shape keys off — returns the
6490    /// author-declared `:placement :estrategia` variant verbatim as a
6491    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
6492    /// `PlacementStrategy` storage.
6493    ///
6494    /// The `:placement :estrategia` slot carries the closed-set
6495    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
6496    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
6497    /// `Replicated` — active-active across every named cluster; `Sharded`
6498    /// — Akka-style hash-keyed entity distribution across the cluster pool
6499    /// per §II.4) that every downstream consumer of the Aplicacao's
6500    /// per-cluster fan-out shape keys off. Validated by
6501    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
6502    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
6503    /// matches!(estrategia, Sharded)` — the cross-slot partition the
6504    /// [`Placement::shard_key`] accessor's docstring pins), and every
6505    /// downstream consumer that reads the strategy keys off this scalar
6506    /// (the [`AplicacaoSpec::validate_placement`]
6507    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
6508    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
6509    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
6510    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
6511    /// declared-but-inert refusal's
6512    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
6513    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
6514    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
6515    /// emit path the substrate operator's per-strategy fan-out reader
6516    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6517    /// materializer's per-strategy admission-webhook resolver).
6518    ///
6519    /// Prior to this lift the `.estrategia` field was accessed inline at
6520    /// four sites — the [`AplicacaoSpec::validate_placement`]
6521    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
6522    /// `estrategia: self.placement.estrategia`, the same method's
6523    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
6524    /// partition dispatch, the non-`Sharded`-arm
6525    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
6526    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
6527    /// per-Aplicacao strategy print line at
6528    /// `println!("… {} …", spec.placement.estrategia, …)`
6529    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
6530    /// expressed no compile-time link back to the typed slot. A future
6531    /// extension of the `:placement :estrategia` axis to a richer author
6532    /// surface (a per-cluster override the operator pins through a future
6533    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
6534    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
6535    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
6536    /// derivation the future adaptive placement engine computes from
6537    /// `:affinity` + `:clusters` topology) would have had to be threaded
6538    /// through every open-coded copy in lockstep — one consumer reading
6539    /// the raw variant while a peer read the operator-resolved variant
6540    /// would silently split the `PlacementWithoutClusters` /
6541    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
6542    /// partition-dispatch input, a two-consumer split at the validator
6543    /// far from the source `caixa.lisp` with no field naming the
6544    /// strategy-drift root cause. Lifting the resolution rule to a typed
6545    /// method on the substrate primitive means every downstream consumer
6546    /// of the Aplicacao's per-`:placement` distribution-strategy surface
6547    /// reaches for exactly one typed dispatch — the resolver's accept-set
6548    /// migrates as a unit on any future axis addition.
6549    ///
6550    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
6551    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
6552    /// same "one typed dispatch on the substrate primitive, thin
6553    /// projections at each consumer" discipline extended onto the
6554    /// per-`:placement` distribution-strategy `Copy`-composite-enum
6555    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
6556    /// family; first `Copy`-return accessor on the M3 mesh-slot
6557    /// `Placement` type — companion to the sibling per-`:placement`
6558    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6559    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
6560    /// optional-scalar axes, closing the last unlifted per-`:placement`
6561    /// scalar-value axis (the closed-set `PlacementStrategy`
6562    /// distribution-strategy discriminator) so every downstream
6563    /// per-`:placement` reader now routes through a typed dispatch on
6564    /// the substrate primitive. Named `estrategia()` to match the storage
6565    /// field's name; the accessor's identity name maps onto the
6566    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
6567    /// already carries. Declared `pub const fn` (matching the peer M3
6568    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6569    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6570    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6571    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6572    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6573    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6574    /// [`RateLimit`] — every one a `pub const fn`) so every future
6575    /// substrate-side `const`-context consumer of the resolved
6576    /// distribution-strategy variant (a `const _: () = assert!(…)`
6577    /// module-scope invariant pin on a per-fixture typed [`Placement`],
6578    /// a future M4 admission-webhook `const fn` resolver over a typed
6579    /// [`Placement`], any `const fn` composer that fans on the strategy
6580    /// at compile time) reaches through the same typed dispatch on the
6581    /// substrate primitive at const-eval time as at runtime. Pinned by
6582    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
6583    /// const-eval posture at module scope via `const _:() = …` items so
6584    /// any future accidental downgrade to non-`const` trips at caixa-core
6585    /// build time.
6586    #[must_use]
6587    pub const fn estrategia(&self) -> PlacementStrategy {
6588        self.estrategia
6589    }
6590
6591    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
6592    /// per-cluster distribution-target slice accessor every consumer that
6593    /// walks the Aplicacao's declared cluster-pool keys off — returns the
6594    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
6595    /// `&[String]` slice-view, borrowed from the typed slot's own
6596    /// `Vec<String>` storage (a zero-copy slice-view over the same
6597    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
6598    /// through). Non-optional: the empty slice is the load-bearing
6599    /// pre-validation sentinel every downstream consumer of the paired
6600    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
6601    /// off — every strategy in the closed
6602    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
6603    /// requires a non-empty list (`SingleNode` / `Replicated` use the
6604    /// list as hosting / takeover candidates per Erlang/OTP distributed-
6605    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
6606    /// shard pool per Akka cluster-sharding convention, §II.4), so the
6607    /// `.is_empty()` probe is the shared pre-condition every
6608    /// [`AplicacaoSpec::validate_placement`] arm heads on.
6609    ///
6610    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
6611    /// 1123-label per-cluster distribution-target list — the same
6612    /// set-not-multiset shape the sibling `:membros :caixa` /
6613    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
6614    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
6615    /// pins the shape). Every downstream consumer that fans on the list
6616    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
6617    /// pre-flight `.is_empty()` probe that trips
6618    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
6619    /// per-cluster value-shape + duplicate-detection fan-out loop, the
6620    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
6621    /// that materializes the list verbatim onto every
6622    /// programs.yaml entry the substrate operator's per-cluster
6623    /// `placement.clusters | contains .Values.cluster` filter reads,
6624    /// the `feira app graph` per-Aplicacao cluster print line, the
6625    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6626    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
6627    /// placement engine's cluster-topology reader).
6628    ///
6629    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
6630    /// inline at three production sites — the
6631    /// [`AplicacaoSpec::validate_placement`] pre-flight
6632    /// `self.placement.clusters.is_empty()` refusal probe, the same
6633    /// method's per-cluster validate loop's
6634    /// `for c in &self.placement.clusters` traversal head, and the
6635    /// `feira app graph` per-Aplicacao print line's
6636    /// `spec.placement.clusters` `{:?}` formatter argument
6637    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
6638    /// that expressed no compile-time link back to the typed slot. A
6639    /// future extension of the `:placement :clusters` axis to a richer
6640    /// author surface (a per-tenant cluster-pool overlay the operator
6641    /// pins through a future `:placement :clusters-overrides` slot the
6642    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
6643    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
6644    /// the future M5 adaptive-placement engine computes from
6645    /// `:affinity` weights + live cluster-topology probes, a promotion
6646    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
6647    /// partition once the substrate operator's cluster-membership
6648    /// reconciler comes into typed scope) would have had to be threaded
6649    /// through all three open-coded copies in lockstep or one consumer
6650    /// would silently disagree with the peers on which cluster-pool a
6651    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
6652    /// reading the raw slot while the peer per-cluster validate loop
6653    /// read an operator-resolved slot would silently split the paired
6654    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
6655    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
6656    /// input from the pre-flight input, a three-consumer split at the
6657    /// validator and formatter far from the source `caixa.lisp` with
6658    /// no field naming the cluster-pool-drift root cause. Lifting the
6659    /// resolution rule to a typed method on the substrate primitive
6660    /// means every downstream consumer of the Aplicacao's
6661    /// per-`:placement` cluster-pool surface reaches for exactly one
6662    /// typed dispatch — the resolver's accept-set migrates as a unit
6663    /// on any future axis addition.
6664    ///
6665    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
6666    /// slot — sibling to the seed M2
6667    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
6668    /// slice-return accessor on the peer per-`:supervisor` static-
6669    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
6670    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
6671    /// primitive, thin projections at each consumer" discipline. The
6672    /// three peer `Vec`-carry axes still unlifted at the time of this
6673    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
6674    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
6675    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
6676    /// [`crate::UpgradeFromEntry::instructions`]
6677    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6678    /// — inherit this accessor's discipline as future compounding runs
6679    /// migrate their consumers onto the shared slice-return shape.
6680    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
6681    /// type, sibling to the two `Option<&str>`-return
6682    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
6683    /// (74ec2d3) accessors and the `Copy`-return
6684    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
6685    /// unlifted per-`:placement` field axis (the `Vec<String>`
6686    /// distribution-target-list carrier) so every downstream
6687    /// per-`:placement` reader now routes through a typed dispatch on
6688    /// the substrate primitive. Named `clusters()` to match the storage
6689    /// field's name verbatim and the tatara-lisp author-surface term
6690    /// (`:clusters`) the field's own docstring already carries; the
6691    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6692    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
6693    /// for. Returns `&[String]` (not `&Vec<String>`) because every
6694    /// downstream consumer of the cluster list treats it as a read-only
6695    /// sequence — the slice-view is the narrowest borrow that supports
6696    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
6697    /// `.len()`) without leaking the backing `Vec`'s
6698    /// grow/push/reserve surface that no consumer of the typed view
6699    /// reaches for (the storage-side `Vec` remains reachable through
6700    /// the `pub clusters` field for the mutation-carrying serde
6701    /// round-trip and per-test fixture-mutation paths).
6702    #[must_use]
6703    pub const fn clusters(&self) -> &[String] {
6704        self.clusters.as_slice()
6705    }
6706}
6707
6708impl Default for Placement {
6709    fn default() -> Self {
6710        Self {
6711            // Route the struct-literal `estrategia` default arm through
6712            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
6713            // typed `pub const` rather than the transitively-derived
6714            // [`PlacementStrategy::default`] route — one source of truth
6715            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
6716            // active-active-across-every-named-cluster arm
6717            // (MESH-COMPOSITION §II.2) that both this struct-literal
6718            // altitude and the sibling [`Default for PlacementStrategy`]
6719            // impl already key off through the same substrate primitive.
6720            // Pinned by
6721            // `placement_default_estrategia_routes_through_lifted_default`.
6722            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
6723            clusters: Vec::new(),
6724            affinity: None,
6725            shard_key: None,
6726        }
6727    }
6728}
6729
6730// ── external entry point ─────────────────────────────────────────────
6731
6732/// External entry point — what an outside caller sees. Renders to a
6733/// Gateway / Ingress + a route to the named member Servico.
6734#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6735#[serde(rename_all = "camelCase")]
6736pub struct Entrada {
6737    /// Public hostname (e.g. `"checkout.quero.cloud"`).
6738    pub host: String,
6739
6740    /// Member Servico the gateway routes to. Must be in `:membros`.
6741    pub para: String,
6742
6743    /// Optional path filter — if set, only matching paths route to
6744    /// this Aplicacao (the rest fall through to other route rules).
6745    #[serde(default)]
6746    pub paths: Vec<String>,
6747
6748    /// Default port on the destination Servico (the trigger.service.port).
6749    #[serde(default = "default_port")]
6750    pub port: u16,
6751}
6752
6753impl Entrada {
6754    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
6755    /// every HTTPRoute-aware renderer keys off — returns the author-
6756    /// declared `:entrada :paths` list verbatim when non-empty, and the
6757    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
6758    /// all fallback otherwise (so an Aplicacao author who declares an
6759    /// external `:entrada` block but no per-path rule surface still
6760    /// gets a route whose sole `HTTPPathMatch` matches every incoming
6761    /// request under the paired
6762    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
6763    ///
6764    /// Prior to this lift the "if `:entrada :paths` is empty use the
6765    /// substrate catch-all; else return each declared path verbatim"
6766    /// cascade lived inline at
6767    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
6768    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
6769    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
6770    /// substrate ships today, with no typed method on the substrate
6771    /// primitive that named the rule. A future path-resolution axis
6772    /// addition — a per-cluster `:entrada :default-path` override the
6773    /// operator pins through a future `:placement`-scoped slot, an
6774    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6775    /// admission-webhook floor that materializes the catch-all before
6776    /// the CR lands, a future per-`:entrada :paths` overlay from a
6777    /// per-cluster policy the future `feira app deploy` pipeline
6778    /// consumes — would have to be threaded through every renderer's
6779    /// inline copy of the cascade in lockstep or one consumer would
6780    /// silently disagree with the peers on which path list a given
6781    /// `:entrada` block resolves to. Lifting the rule to a typed
6782    /// method on the substrate primitive means every downstream
6783    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
6784    /// per-cluster overlay resolver, every future per-Aplicacao
6785    /// snapshot renderer) reaches for exactly one typed dispatch —
6786    /// the resolver's accept-set moves as a unit on any future axis
6787    /// addition.
6788    ///
6789    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
6790    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
6791    /// per-`:entrada` scalar-value axes — extends the "one typed
6792    /// dispatch on the substrate primitive, thin projections at each
6793    /// consumer" discipline onto the per-`:entrada` path-list
6794    /// resolution axis every HTTPRoute-aware renderer consumes. Same
6795    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
6796    /// sibling `:politicas` primitive — one typed method on the
6797    /// substrate primitive that names the cascade every renderer
6798    /// otherwise re-inlines.
6799    #[must_use]
6800    pub fn resolved_paths(&self) -> Vec<&str> {
6801        // Route the internal cascade-head + per-entry projection reads
6802        // through the lifted [`Self::paths`] slice accessor rather than
6803        // the raw `self.paths` field access — the substrate-primitive
6804        // per-`:entrada` path-list resolver's two internal reads now
6805        // key off the canonical raw-slot surface every downstream
6806        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
6807        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
6808        // entrada summary line's `{:?}` Debug print) routes through, so
6809        // any future rebrand on the typed slot's raw-slot reader lands
6810        // at exactly one place. Same two-consumer coherence discipline
6811        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
6812        // the peer M3 mesh-slot `Vec<String>`-carry axis.
6813        if self.paths().is_empty() {
6814            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
6815        } else {
6816            self.paths().iter().map(String::as_str).collect()
6817        }
6818    }
6819
6820    /// Substrate-canonical per-`:entrada` DNS-hostname singular
6821    /// accessor every Gateway-API `Listener.hostname` reader keys off
6822    /// — returns the author-declared `:entrada :host` byte-string
6823    /// verbatim as a `&str`, borrowed from the typed slot's own
6824    /// [`String`] storage.
6825    ///
6826    /// Named the "singular" half of the DNS-hostname resolver pair on
6827    /// the substrate primitive: the parent-Gateway per-listener
6828    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
6829    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
6830    /// hostname per listener), and this accessor is the typed dispatch
6831    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
6832    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
6833    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
6834    /// per-Aplicacao ingress-hostname surface projects onto.
6835    ///
6836    /// Prior to this lift the `entrada.host.clone()` byte-string was
6837    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
6838    /// per-listener singular `hostname:` axis
6839    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
6840    /// per-HTTPRoute plural `spec.hostnames[]` axis
6841    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
6842    /// consumers read the same `entrada.host` field but the two-site
6843    /// duplication expressed no compile-time contract that the singular
6844    /// Gateway-listener filter and the plural `HTTPRoute` filter list
6845    /// stay in lockstep on future extensions of the `:entrada` slot to
6846    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
6847    /// overlay, a per-cluster SNI fan-out the operator pins through a
6848    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
6849    /// Aplicacao` CR materializer's per-listener virtual-host filter
6850    /// admission-webhook overlay). Any such extension would have to be
6851    /// threaded through every renderer's inline copy of the resolution
6852    /// in lockstep or the Gateway listener's `hostname:` filter would
6853    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
6854    /// — a Gateway-API-conformance divergence whose apply-time symptom
6855    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
6856    /// `NoMatchingParent` — the API server rejects the route because
6857    /// its `hostnames[]` filter doesn't intersect the parent listener's
6858    /// `hostname` filter) is far from the source `caixa.lisp` and never
6859    /// surfaces in the emitted YAML. Lifting the singular and plural
6860    /// resolvers to typed methods on the substrate primitive means
6861    /// every consumer of the Aplicacao's ingress-hostname surface
6862    /// reaches for exactly one typed dispatch, and the pair-invariant
6863    /// `hostnames() == vec![hostname()]` pinned by the sibling
6864    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
6865    /// keeps the two axes in lockstep by construction.
6866    ///
6867    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
6868    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
6869    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
6870    /// the substrate primitive, thin projections at each consumer"
6871    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6872    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6873    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6874    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
6875    /// `:entrada` scalar-value + list-value axes.
6876    #[must_use]
6877    pub const fn hostname(&self) -> &str {
6878        self.host.as_str()
6879    }
6880
6881    /// Substrate-canonical per-`:entrada` DNS-hostname plural
6882    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
6883    /// keys off — returns the singleton `[hostname()]` list under
6884    /// today's single-hostname-per-Aplicacao author surface, and the
6885    /// authoritative multi-hostname list under a future
6886    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
6887    ///
6888    /// Plural half of the DNS-hostname resolver pair — see the
6889    /// companion [`Entrada::hostname`] docstring for the two-consumer
6890    /// lift + pair-invariant discipline (`hostnames() ==
6891    /// vec![hostname()]`, pinned load-bearing by the sibling
6892    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
6893    /// test).
6894    ///
6895    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
6896    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
6897    /// per-rule path-list axis — same `Vec<&str>` shape, same
6898    /// substrate-primitive-owns-the-resolver discipline extended to
6899    /// the per-HTTPRoute virtual-host filter-list axis.
6900    #[must_use]
6901    pub fn hostnames(&self) -> Vec<&str> {
6902        vec![self.hostname()]
6903    }
6904
6905    /// Substrate-canonical per-`:entrada` destination-Servico scalar
6906    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
6907    /// the author-declared `:entrada :para` byte-string verbatim as a
6908    /// `&str`, borrowed from the typed slot's own [`String`] storage.
6909    ///
6910    /// The `:entrada :para` slot names the single member Servico the
6911    /// external Gateway routes to (validated by
6912    /// [`AplicacaoSpec::validate`] to be a
6913    /// [`Membro::caixa`] the Aplicacao declares — a stray
6914    /// `:para` that doesn't name a member is
6915    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
6916    /// backend-attachment miss at cluster-apply time). Under today's
6917    /// single-destination author surface `:entrada :para` is the ingress
6918    /// apex Servico's canonical identity; under a hypothetical
6919    /// future multi-backend author surface (a `:entrada
6920    /// :split :backends` weighted-fan-out overlay for canary /
6921    /// blue-green traffic-split rollouts, per-path override for
6922    /// path-based per-Servico routing beyond the single-apex model,
6923    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6924    /// per-CR admission-webhook that promotes the scalar to a
6925    /// weighted list) this accessor is the substrate primitive's typed
6926    /// dispatch every downstream `HTTPRoute`-aware consumer routes
6927    /// through, so the resolution shape migrates as a unit on one
6928    /// caixa-core edit rather than a coordinated rewrite across every
6929    /// renderer's inline field-access.
6930    ///
6931    /// Prior to this lift the `entrada.para` byte-string was accessed
6932    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6933    /// `metadata.name` composer's per-destination discriminator arg
6934    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6935    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6936    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6937    /// (`entrada.para.clone()`,
6938    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6939    /// consumers read the same `entrada.para` field but the two-site
6940    /// duplication expressed no compile-time contract that the HTTPRoute
6941    /// name-discriminator and the per-rule backend name stay in
6942    /// lockstep on future extensions of the `:entrada` slot to a
6943    /// multi-destination author surface. Any such extension would have
6944    /// to be threaded through every renderer's inline copy of the
6945    /// destination projection in lockstep or the HTTPRoute
6946    /// `metadata.name` would silently reference a different destination
6947    /// than its own `backendRefs[]` — an operator-side
6948    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6949    /// grep-by-name lookup would land on a route whose `backendRefs[]`
6950    /// silently point at a peer Servico, dropping every external
6951    /// `:entrada` flow at the gateway with the destination-drift root
6952    /// cause invisible in the emitted YAML.
6953    ///
6954    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6955    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6956    /// the per-listener singular / per-HTTPRoute plural filter axes and
6957    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6958    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6959    /// typed dispatch on the substrate primitive, thin projections at
6960    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6961    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6962    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6963    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6964    /// sibling per-`:entrada` scalar-value + list-value axes — this
6965    /// accessor closes the last unlifted per-`:entrada` scalar axis
6966    /// (the destination-Servico byte-string) so every downstream
6967    /// per-`:entrada` reader now routes through a typed dispatch on
6968    /// the substrate primitive.
6969    #[must_use]
6970    pub const fn destination(&self) -> &str {
6971        self.para.as_str()
6972    }
6973
6974    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6975    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6976    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6977    /// reader keys off — returns the author-declared `:entrada :port`
6978    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6979    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6980    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6981    /// [`AplicacaoError::EntradaPortZero`], not a silent
6982    /// admission-webhook rejection at cluster-apply time).
6983    ///
6984    /// The `:entrada :port` slot carries the destination Servico's
6985    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6986    /// the `pleme-computeunit` library chart), and every downstream
6987    /// consumer that reads the port keys off this scalar (the
6988    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6989    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6990    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6991    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6992    /// CR materializer's per-Aplicacao gateway port resolver).
6993    ///
6994    /// Prior to this lift the `.port` field was accessed inline at two
6995    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6996    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6997    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6998    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6999    /// open-coded field-accesses that expressed no compile-time link
7000    /// back to the typed slot. A future extension of the `:entrada :port`
7001    /// axis to a richer author surface — a per-cluster override the
7002    /// operator pins through a future `:placement :default-port` slot the
7003    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
7004    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
7005    /// heterogeneous listener ports, an M4
7006    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7007    /// admission-webhook floor that promotes the scalar to a
7008    /// per-destination map — would have had to be threaded through both
7009    /// open-coded copies in lockstep or the structural-floor validator
7010    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
7011    /// silently disagree on which port a given [`Entrada`] resolves to.
7012    /// Lifting the resolution rule to a typed method on the substrate
7013    /// primitive means every downstream consumer of the Aplicacao's
7014    /// per-`:entrada` L4-port surface reaches for exactly one typed
7015    /// dispatch — the resolver's accept-set migrates as a unit on any
7016    /// future axis addition.
7017    ///
7018    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
7019    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
7020    /// accessors on the per-`:entrada` scalar-value axis — same "one
7021    /// typed dispatch on the substrate primitive, thin projections at
7022    /// each consumer" discipline extended onto the per-`:entrada`
7023    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
7024    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
7025    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
7026    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
7027    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
7028    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
7029    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
7030    /// storage field's name; the accessor's identity name maps onto the
7031    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
7032    /// already carries. Declared `pub const fn` (matching the peer M3
7033    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
7034    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
7035    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
7036    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
7037    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
7038    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
7039    /// [`RateLimit`], and the sibling per-`:placement`
7040    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
7041    /// enum scalar axis — every one a `pub const fn`) so every future
7042    /// substrate-side `const`-context consumer of the resolved
7043    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
7044    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
7045    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
7046    /// admission-webhook `const fn` per-CR gateway-port floor over a
7047    /// typed [`Entrada`], any `const fn` composer that fans on the port
7048    /// at compile time) reaches through the same typed dispatch on the
7049    /// substrate primitive at const-eval time as at runtime. Pinned by
7050    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
7051    /// const-eval posture at module scope via `const _:() = …` items so
7052    /// any future accidental downgrade to non-`const` trips at caixa-core
7053    /// build time.
7054    #[must_use]
7055    pub const fn port(&self) -> u16 {
7056        self.port
7057    }
7058
7059    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
7060    /// slice accessor every HTTPRoute-aware renderer keys off when it
7061    /// wants the raw author-declared path-list (not the fallback-
7062    /// applied projection [`Self::resolved_paths`] returns) — returns
7063    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
7064    /// borrowed from the typed slot's own [`Vec<String>`] storage.
7065    ///
7066    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
7067    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
7068    /// (1449891) closes the fallback-applying arm every per-Aplicacao
7069    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
7070    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
7071    /// catch-all; non-empty slot → per-entry verbatim projection); this
7072    /// accessor closes the raw-slot arm every consumer that must see the
7073    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
7074    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
7075    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
7076    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
7077    /// external-gateway summary line's `{:?}` Debug print — which must
7078    /// name the author's declaration, not the substrate's fallback, so
7079    /// an author reading their graph output can grep their caixa.lisp
7080    /// for the exact list they authored) routes through.
7081    ///
7082    /// Prior to this lift the `.paths` field was accessed inline at four
7083    /// production sites: the two internal reads in [`Self::resolved_paths`]
7084    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
7085    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
7086    /// value-shape gate's `for p in &e.paths` traversal head, and the
7087    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
7088    /// Debug print — four open-coded field-accesses that expressed no
7089    /// compile-time link back to the typed slot. A future extension of
7090    /// the `:entrada :paths` axis to a richer author surface — a
7091    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
7092    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
7093    /// spec supports through `matches[].method`), a per-path per-header
7094    /// filter overlay (`matches[].headers[]`), a per-cluster override
7095    /// the operator pins through a future `:placement :path-overlay`
7096    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7097    /// per-CR admission-webhook that normalized the list at admission
7098    /// time — would have had to be threaded through every open-coded
7099    /// copy in lockstep or the validator's per-entry gate would silently
7100    /// disagree with the renderer's per-entry emit on which list a given
7101    /// `:entrada` block resolves to. Lifting the resolution to a typed
7102    /// method on the substrate primitive means every downstream consumer
7103    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
7104    /// exactly one typed dispatch — the resolver's accept-set migrates
7105    /// as a unit on any future axis addition.
7106    ///
7107    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
7108    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
7109    /// carry axis — same "one typed dispatch on the substrate primitive,
7110    /// thin projections at each consumer" discipline extended onto the
7111    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
7112    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
7113    /// carrier) so every downstream per-`:entrada` reader now routes
7114    /// through a typed dispatch on the substrate primitive. Returns
7115    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
7116    /// treats the list as a read-only sequence — the slice-view is the
7117    /// narrowest borrow that supports every present + roadmapped consumer
7118    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
7119    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
7120    /// view reaches for (the storage-side `Vec` remains reachable through
7121    /// the `pub paths` field for the mutation-carrying serde round-trip
7122    /// and per-test fixture-mutation paths).
7123    #[must_use]
7124    pub const fn paths(&self) -> &[String] {
7125        self.paths.as_slice()
7126    }
7127}
7128
7129/// Canonical default L4 port every typed Servico exposes on its
7130/// in-cluster K8s Service (the `trigger.service.port` axis the
7131/// `pleme-computeunit` library chart emits, the `:entrada :port` author
7132/// surface defaults to when the author omits the slot, and the
7133/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
7134/// `:entrada` block matches the per-`:contratos` destination Servico).
7135/// The single source of truth all three typed-port consumers reach for:
7136///
7137///   - [`Entrada::port`]'s serde default (via the
7138///     [`default_port`] helper this constant feeds); the author surface
7139///     `(:entrada (:host … :para …))` without an explicit `:port` slot
7140///     reads back as a typed [`Entrada`] carrying this exact value;
7141///   - the
7142///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
7143///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
7144///     fallback, fired when the typed `:entrada` block doesn't name
7145///     the per-`:contratos` destination Servico — the typed
7146///     `:contratos` graph carries no per-destination port axis (the
7147///     destination port is the destination Servico's
7148///     `lareira-<nome>` chart's `trigger.service.port`, which the
7149///     Aplicacao-level renderer has no visibility into without a
7150///     resolver round-trip), so the renderer falls back to the
7151///     substrate's canonical Servico-port assumption — by
7152///     construction the same value the destination's own
7153///     `pleme-computeunit` chart emits, the same value the
7154///     destination's own typed `:entrada :port` slot defaults to;
7155///   - every future per-Servico renderer the absorption-roadmap
7156///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
7157///     CR materializer's per-edge port resolver, the future
7158///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
7159///     emitter's per-route bucket key, the future caixa-otel
7160///     collector-pipeline emitter's per-Servico scrape port).
7161///
7162/// Until this lift landed the value `8080` lived at two production-code
7163/// call-sites: the [`default_port`] helper at
7164/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
7165/// and the `.unwrap_or(8080)` literal at
7166/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
7167/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
7168/// resolver). A future Servico-port rebrand — the substrate moving the
7169/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
7170/// gateway grows direct `:80` listeners, to `8443` once the substrate
7171/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
7172/// override the operator pins through a future
7173/// `:placement :default-port` slot — without a coordinated edit on
7174/// both sides would silently emit Servicos listening on one port and
7175/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
7176/// The CNP's apply-time symptom (the policy is admitted but every L4
7177/// flow on the destination Servico's actual port silently drops because
7178/// it doesn't match the whitelisted port) is far from the rebrand
7179/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
7180/// in hubble traces, not in `kubectl describe`. Lifting the literal to
7181/// a shared constant closes the drift footgun structurally — both
7182/// consumers read from the same `u16`, so any rebrand reaches both
7183/// sites by construction.
7184///
7185/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
7186/// per-renderer canonical-K8s-axis constant — the namespace string
7187/// and the canonical Servico port both lived as duplicated literals
7188/// across caixa-core / caixa-mesh / caixa-flux before their respective
7189/// lifts. Same "the typed constant lives in one place" discipline the
7190/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
7191/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
7192/// shared-string axes.
7193///
7194/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
7195pub const DEFAULT_SERVICO_PORT: u16 = 8080;
7196
7197/// Structural floor for the typed `:entrada :port` axis — every
7198/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
7199/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
7200///
7201/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
7202/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
7203/// interprets as "let the kernel pick a free port at bind time", not a
7204/// well-defined destination the substrate's per-`:entrada` Gateway API
7205/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
7206/// carrying `port: 0` degenerates to a nominal-only routing target: the
7207/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
7208/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
7209/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
7210/// at build time rather than at `kubectl apply` time), and the
7211/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
7212/// (caixa-mesh/src/lib.rs:2657 through
7213/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
7214/// [`Entrada::port`] typed value — silently emits a policy whose
7215/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
7216/// actual listener, dropping every L4 flow at the eBPF data plane far
7217/// from the source caixa.lisp with no field naming the port-zero-drift
7218/// root cause.
7219///
7220/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
7221/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
7222/// on the top edge (unlike the peer capped-`u32` `:politicas` /
7223/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
7224/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
7225/// well below `u32::MAX` and therefore need explicit typed caps).
7226///
7227/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
7228/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
7229/// scalar every `(:entrada (:host … :para …))` slot without an explicit
7230/// `:port` inherits through the serde default hook; this constant names
7231/// the accept-set floor every declared port must satisfy. The pair is
7232/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
7233/// substrate's default must satisfy its own accept-set floor by
7234/// construction) — a future rebrand that accidentally moved
7235/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
7236/// negative-cast typo, a per-cluster override the operator pins through
7237/// a future `:placement :default-port` slot that lands out-of-range)
7238/// would silently invalidate the serde-default emission at every
7239/// author-side `(:entrada (:host … :para …))` slot — the compile-time
7240/// invariant pin
7241/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
7242/// closes the drift footgun at caixa-core build time.
7243///
7244/// Lifted as a typed `pub const` (rather than an inline `0` literal at
7245/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
7246/// has exactly one source of truth — the future M4
7247/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
7248/// gateway resolver, the future per-Servico
7249/// `computeunit.trigger.service.port` renderer's per-CR port-value
7250/// validator, and every downstream test-fixture navigator asserting
7251/// the accept-set floor all read from one place. Same shape every
7252/// other typed bracket-floor / bracket-ceiling in this crate carries
7253/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
7254/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
7255/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
7256/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
7257/// [`POLICY_RATE_LIMIT_MAX`]).
7258pub const SERVICO_PORT_MIN: u16 = 1;
7259
7260const fn default_port() -> u16 {
7261    DEFAULT_SERVICO_PORT
7262}
7263
7264// ── the typed view ───────────────────────────────────────────────────
7265
7266/// Typed composition view of the flat Aplicacao slots on
7267/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
7268/// validation + downstream renderer consumption.
7269#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
7270#[serde(rename_all = "camelCase")]
7271pub struct AplicacaoSpec {
7272    pub membros: Vec<Membro>,
7273    pub contratos: Vec<WitContract>,
7274    pub politicas: MeshPolicy,
7275    pub placement: Placement,
7276    pub entrada: Option<Entrada>,
7277}
7278
7279impl AplicacaoSpec {
7280    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
7281    /// per-Aplicacao member-list slice-return accessor every
7282    /// per-Aplicacao member-list reader keys off — returns the author-
7283    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
7284    /// over the same backing buffer the raw `self.membros.as_slice()`
7285    /// field access borrows from.
7286    ///
7287    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
7288    /// member list — the load-bearing identity of the application graph
7289    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
7290    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
7291    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
7292    /// accessor) with a `:versao` semver-requirement string (through
7293    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
7294    /// and every downstream consumer that fans on the member-set keys
7295    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
7296    /// membership-lookup `HashSet<&str>` seed's collect input, the
7297    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
7298    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
7299    /// per-member DNS-1123 / semver-requirement / duplicate-detection
7300    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
7301    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
7302    /// programs.yaml per-`:membros` fan-out emitter's per-entry
7303    /// mapping-composition loop, the `feira app graph` per-Aplicacao
7304    /// member-count print line and per-member tree traversal,
7305    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
7306    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
7307    /// placement engine's per-member weight-topology reader).
7308    ///
7309    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
7310    /// inline at six production sites — the [`AplicacaoSpec::validate`]
7311    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
7312    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
7313    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
7314    /// probe, the same method's per-member `for m in &self.membros`
7315    /// validate-loop traversal head, the
7316    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7317    /// `for m in &self.membros` adjacency-list seed, the
7318    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
7319    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
7320    /// paired with the peer `for m in &spec.membros` per-entry fan-out
7321    /// loop, and the `feira app graph` per-Aplicacao print line's
7322    /// `spec.membros.len()` count formatter argument paired with the
7323    /// peer `for m in &spec.membros` per-member tree traversal — six
7324    /// open-coded field-accesses that expressed no compile-time link
7325    /// back to the typed slot. A future extension of the `:membros`
7326    /// axis to a richer author surface (a per-cluster member-set
7327    /// overlay the operator pins through a future
7328    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
7329    /// roadmap acknowledges, a per-tenant member-alias table the M4
7330    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
7331    /// CR at admission time, a per-Aplicacao dynamic member-set
7332    /// derivation the future adaptive-placement engine computes from
7333    /// weighted membership topology, a promotion of the plain
7334    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
7335    /// Orleans-style virtual-actor dynamic-membership comes into typed
7336    /// scope) would have had to be threaded through all six open-coded
7337    /// copies in lockstep or one consumer would silently disagree with
7338    /// the peers on which member-set a given Aplicacao resolves to —
7339    /// the `HashSet<&str>` name-set seed reading the raw slot while
7340    /// the peer `.is_empty()` refusal probe read an operator-resolved
7341    /// slot would silently split the `:contratos` membership-lookup
7342    /// input from the pre-flight-refusal input, a six-consumer split
7343    /// at the validator + programs.yaml emitter + graph printer far
7344    /// from the source `caixa.lisp` with no field naming the member-
7345    /// set-drift root cause. Lifting the resolution rule to a typed
7346    /// method on the substrate primitive means every downstream
7347    /// consumer of the Aplicacao's per-`:membros` member-list surface
7348    /// reaches for exactly one typed dispatch — the resolver's accept-
7349    /// set migrates as a unit on any future axis addition.
7350    ///
7351    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
7352    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7353    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7354    /// static-child-list `Vec`-carry axis, and to the M3
7355    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7356    /// on the peer per-`:placement` distribution-target-list `Vec`-
7357    /// carry axis. Same "one typed dispatch on the substrate primitive,
7358    /// thin projections at each consumer" discipline. The two peer
7359    /// `Vec`-carry axes still unlifted at the time of this lift —
7360    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
7361    /// WIT-typed edge list) and
7362    /// [`crate::UpgradeFromEntry::instructions`]
7363    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
7364    /// — inherit this accessor's discipline as future compounding runs
7365    /// migrate their consumers onto the shared slice-return shape.
7366    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
7367    /// `AplicacaoSpec` type itself, extending the discipline beyond
7368    /// the inner per-slot types ([`crate::Placement`],
7369    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
7370    /// view every renderer consumes. Named `membros()` to match the
7371    /// storage field's name verbatim and the tatara-lisp author-
7372    /// surface term (`:membros`) the field's own docstring already
7373    /// carries; the accessor's identity maps onto the canonical
7374    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
7375    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
7376    /// every downstream consumer of the member list treats it as a
7377    /// read-only sequence — the slice-view is the narrowest borrow
7378    /// that supports every present + roadmapped consumer
7379    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7380    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7381    /// the typed view reaches for (the storage-side `Vec` remains
7382    /// reachable through the `pub membros` field for the mutation-
7383    /// carrying serde round-trip and per-test fixture-mutation paths).
7384    #[must_use]
7385    pub const fn membros(&self) -> &[Membro] {
7386        self.membros.as_slice()
7387    }
7388
7389    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
7390    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
7391    /// accessor every per-Aplicacao contract-list reader keys off —
7392    /// returns the author-declared `:contratos` list verbatim as a
7393    /// `&[WitContract]` slice-view over the same backing buffer the raw
7394    /// `self.contratos.as_slice()` field access borrows from.
7395    ///
7396    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
7397    /// WIT-typed edge list — the load-bearing set of directed edges
7398    /// on the application graph whose nodes are the `:membros` entries
7399    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
7400    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
7401    /// six-tuple is the edge identity every downstream duplicate gate
7402    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
7403    /// Servico caller name + a `:para` destination-Servico callee name
7404    /// (through the lifted [`WitContract::source`] +
7405    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
7406    /// caller/callee-Servico axis) with a `:wit` world-reference
7407    /// (through the lifted [`WitContract::world_ref`] (0804823)
7408    /// accessor) and the target-shape-appropriate payload-carrier
7409    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
7410    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
7411    /// (ed22b66) accessor on the per-target-shape payload-carrier
7412    /// axis). Every downstream consumer that fans on the edge-set
7413    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
7414    /// name-set / self-edge / target-shape / dedup fan-out loop, the
7415    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
7416    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
7417    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
7418    /// grouping loop, the `feira app graph` per-Aplicacao contract-
7419    /// count print line and per-contract tree traversal, every future
7420    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
7421    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
7422    /// mesh-policy overlay resolver's per-contract typed-edge weight
7423    /// reader).
7424    ///
7425    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
7426    /// accessed inline at four production sites — the
7427    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
7428    /// per-edge validate-loop traversal head (which drives every
7429    /// per-edge name-set membership lookup, self-edge check,
7430    /// target-shape dispatch, and dedup `HashSet` insert), the
7431    /// [`AplicacaoSpec::detect_sync_cycles`]'s
7432    /// `for c in &self.contratos` adjacency-list seed head (which
7433    /// drives every per-edge sync-vs-pub-sub partition and per-edge
7434    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
7435    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
7436    /// `BTreeMap` grouping loop head (which drives every per-CNP
7437    /// fan-out emit), and the `feira app graph` per-Aplicacao print
7438    /// line's `spec.contratos.len()` count formatter argument paired
7439    /// with the peer `for c in &spec.contratos` per-contract tree
7440    /// traversal — four open-coded field-accesses that expressed no
7441    /// compile-time link back to the typed slot. A future extension
7442    /// of the `:contratos` axis to a richer author surface (a
7443    /// per-cluster contract overlay the operator pins through a
7444    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
7445    /// federation roadmap acknowledges, a per-tenant edge-policy
7446    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
7447    /// materializer resolves per-CR at admission time, a per-edge
7448    /// weight scalar the future adaptive-placement engine reads to
7449    /// bias sync-subgraph routing, a promotion of the plain
7450    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
7451    /// once virtual-actor-style dynamic-edge composition comes into
7452    /// typed scope) would have had to be threaded through all four
7453    /// open-coded copies in lockstep or one consumer would silently
7454    /// disagree with the peers on which edge-set a given Aplicacao
7455    /// resolves to — the validator's per-edge dedup `HashSet` seed
7456    /// reading the raw slot while the peer sync-cycle adjacency-list
7457    /// seed read an operator-resolved slot would silently split the
7458    /// build-time edge-set gate from the runtime deadlock-detection
7459    /// gate, a four-consumer split at the validator, the cycle
7460    /// detector, the CNP emitter, and the graph printer far from
7461    /// the source `caixa.lisp` with no field naming the edge-set-
7462    /// drift root cause. Lifting the resolution rule to a typed method on the
7463    /// substrate primitive means every downstream consumer of the
7464    /// Aplicacao's per-`:contratos` edge-list surface reaches for
7465    /// exactly one typed dispatch — the resolver's accept-set
7466    /// migrates as a unit on any future axis addition.
7467    ///
7468    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
7469    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
7470    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
7471    /// static-child-list `Vec`-carry axis, to the M3
7472    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
7473    /// on the peer per-`:placement` distribution-target-list `Vec`-
7474    /// carry axis, and to the immediately-adjacent sibling M3
7475    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
7476    /// the peer per-`:membros` node-list `Vec`-carry axis — the
7477    /// per-`:contratos` edge-list accessor is the natural pair of
7478    /// the per-`:membros` node-list accessor (graph edges over graph
7479    /// nodes; every graph-shaped consumer reads both). Same "one
7480    /// typed dispatch on the substrate primitive, thin projections
7481    /// at each consumer" discipline. The last remaining `Vec`-carry
7482    /// axis still unlifted at the time of this lift —
7483    /// [`crate::UpgradeFromEntry::instructions`]
7484    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
7485    /// list) — inherits this accessor's discipline as future
7486    /// compounding runs migrate its consumers onto the shared slice-
7487    /// return shape. Second `&[T]`-return accessor on the top-level
7488    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
7489    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
7490    /// `:contratos` are the two `Vec` fields on the outer typed
7491    /// composition view — `:politicas`, `:placement`, `:entrada` are
7492    /// scalar/option-shaped and already route through their per-slot
7493    /// accessor families). Named `contratos()` to match the storage
7494    /// field's name verbatim and the tatara-lisp author-surface term
7495    /// (`:contratos`) the field's own docstring already carries; the
7496    /// accessor's identity maps onto the canonical MESH-COMPOSITION
7497    /// §III.1 vocabulary the slot's docstring already reaches for.
7498    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
7499    /// every downstream consumer of the contract list treats it as a
7500    /// read-only sequence — the slice-view is the narrowest borrow
7501    /// that supports every present + roadmapped consumer
7502    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
7503    /// backing `Vec`'s grow/push/reserve surface that no consumer of
7504    /// the typed view reaches for (the storage-side `Vec` remains
7505    /// reachable through the `pub contratos` field for the mutation-
7506    /// carrying serde round-trip and per-test fixture-mutation paths).
7507    #[must_use]
7508    pub const fn contratos(&self) -> &[WitContract] {
7509        self.contratos.as_slice()
7510    }
7511
7512    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
7513    /// per-Aplicacao mesh-policy composite-reference accessor every
7514    /// per-Aplicacao policy-block reader keys off — returns the author-
7515    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
7516    /// reference over the same backing storage the raw `&self.politicas`
7517    /// field access borrows from.
7518    ///
7519    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
7520    /// mesh-policy composite — the load-bearing container of every
7521    /// mesh-level operational-policy axis every downstream mesh-artifact
7522    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
7523    /// mesh-policy overlay is the single typed surface a
7524    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
7525    /// from). Every per-`:politicas` axis threads through a lifted
7526    /// per-slot accessor on the [`MeshPolicy`] type: the
7527    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
7528    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
7529    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
7530    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
7531    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
7532    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
7533    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
7534    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
7535    /// accessor. Every downstream consumer that reaches for a policy
7536    /// axis first passes through this outer accessor onto the composite
7537    /// and then dispatches onto the per-axis accessor — the two-level
7538    /// dispatch means every per-`:politicas` reader now routes through
7539    /// a typed dispatch on the substrate primitive at both altitudes.
7540    ///
7541    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
7542    /// accessed inline at four production sites — the
7543    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
7544    /// &self.politicas;` traversal seed (which drives every per-axis
7545    /// zero-floor + upper-cap + canonical-form bracket dispatch through
7546    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
7547    /// `p.rate_limit()` on the axis-level lifted accessors), the
7548    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
7549    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
7550    /// chain (which drives every per-`(:de, :para)` CNP
7551    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
7552    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
7553    /// timeout + retry overlay emitter's paired
7554    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
7555    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
7556    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
7557    /// open-coded outer-field accesses that expressed no compile-time
7558    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
7559    /// future extension of the `:politicas` outer axis to a richer
7560    /// author surface (a per-cluster policy overlay the operator pins
7561    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
7562    /// §V federation roadmap acknowledges, a per-tenant policy-alias
7563    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7564    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7565    /// policy-composite derivation the future adaptive-placement engine
7566    /// computes from a per-cluster load-topology reader, a promotion of
7567    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
7568    /// partition once virtual-actor-style dynamic-mesh-policy
7569    /// composition comes into typed scope) would have had to be threaded
7570    /// through all four open-coded copies in lockstep or one consumer
7571    /// would silently disagree with the peers on which mesh-policy
7572    /// composite a given Aplicacao resolves to — the validator's
7573    /// per-axis bracket-dispatch seed reading the raw slot while the
7574    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
7575    /// would silently split the build-time policy-shape gate from the
7576    /// runtime CNP-emission gate, a four-consumer split at the
7577    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
7578    /// the source `caixa.lisp` with no field naming the policy-drift
7579    /// root cause. Lifting the resolution rule to a typed method on the
7580    /// substrate primitive means every downstream consumer of the
7581    /// Aplicacao's per-`:politicas` mesh-policy composite surface
7582    /// reaches for exactly one typed dispatch — the resolver's accept-
7583    /// set migrates as a unit on any future axis addition.
7584    ///
7585    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
7586    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
7587    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7588    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
7589    /// close the two `Vec`-carry axes on the outer typed composition
7590    /// view; the outer `:politicas` composite-reference axis is the
7591    /// natural pair to the paired outer `Vec`-carry accessors on the
7592    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
7593    /// emitter reads all four axes as one unit (graph nodes + graph
7594    /// edges + mesh policy + placement pool). Peer to the same
7595    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
7596    /// slot: every M2 `SupervisorSpec`-scoped composite reader
7597    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
7598    /// `restart_window`, `children`) already routes through the M2
7599    /// `SupervisorSpec` accessor family — this lift extends the same
7600    /// "one typed dispatch on the substrate primitive at the outer
7601    /// composition altitude" discipline to the M3 mesh-slot
7602    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
7603    /// remaining peer outer-composite axes still unlifted at the time
7604    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
7605    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
7606    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
7607    /// inherit this accessor's discipline as future compounding runs
7608    /// migrate their consumers onto the shared reference-return shape.
7609    /// Named `politicas()` to match the storage field's name verbatim
7610    /// and the tatara-lisp author-surface term (`:politicas`) the
7611    /// field's own docstring already carries; the accessor's identity
7612    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
7613    /// slot's docstring already reaches for. Returns `&MeshPolicy`
7614    /// (not the owning composite by copy or clone) because every
7615    /// downstream consumer of the mesh-policy composite treats it as a
7616    /// read-only per-axis dispatch source — the reference-view is the
7617    /// narrowest borrow that supports every present + roadmapped
7618    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
7619    /// emptiness probe) without cloning the composite through every
7620    /// consumer's fast path.
7621    #[must_use]
7622    pub const fn politicas(&self) -> &MeshPolicy {
7623        &self.politicas
7624    }
7625
7626    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
7627    /// per-Aplicacao distribution-composite composite-reference accessor
7628    /// every per-Aplicacao placement-block reader keys off — returns the
7629    /// author-declared `:placement` composite verbatim as a `&Placement`
7630    /// reference over the same backing storage the raw `&self.placement`
7631    /// field access borrows from.
7632    ///
7633    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
7634    /// distribution composite — the load-bearing container of every
7635    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
7636    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
7637    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
7638    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
7639    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
7640    /// `:affinity` hint). Every per-`:placement` axis threads through a
7641    /// lifted per-slot accessor on the [`Placement`] type: the
7642    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
7643    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
7644    /// per-cluster distribution-target slice-return accessor, the
7645    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
7646    /// optional-scalar accessor, and the [`Placement::shard_key`]
7647    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
7648    /// downstream consumer that reaches for a placement axis first passes
7649    /// through this outer accessor onto the composite and then dispatches
7650    /// onto the per-axis accessor — the two-level dispatch means every
7651    /// per-`:placement` reader now routes through a typed dispatch on the
7652    /// substrate primitive at both altitudes.
7653    ///
7654    /// Prior to this lift the `.placement` `Placement` composite was
7655    /// accessed inline at three production sites — the
7656    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
7657    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
7658    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
7659    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
7660    /// cluster `.clusters()` validate-loop traversal head, the per-
7661    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
7662    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
7663    /// paired with the shape-gate cascade's `.shard_key()` /
7664    /// `.estrategia()` diagnostic-carry pair), the
7665    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
7666    /// per-entry placement-block emitter's outer
7667    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
7668    /// seed (which fans onto every per-cluster `programs[]` entry as a
7669    /// self-describing distribution overlay the aggregator filters by),
7670    /// and the `feira app graph` per-Aplicacao print line's paired
7671    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
7672    /// then-inner-accessor chains (which drive the human-readable
7673    /// distribution summary of the typed Aplicacao view) — three open-
7674    /// coded outer-field accesses that expressed no compile-time link
7675    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
7676    /// extension of the `:placement` outer axis to a richer author surface
7677    /// (a per-cluster placement overlay the operator pins through a
7678    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
7679    /// federation roadmap acknowledges, a per-tenant placement-alias
7680    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
7681    /// resolves per-CR at admission time, a per-Aplicacao dynamic
7682    /// placement-composite derivation the future M5 adaptive-placement
7683    /// engine computes from a per-cluster load-topology reader, a
7684    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
7685    /// partition once Orleans-style virtual-actor dynamic-placement comes
7686    /// into typed scope) would have had to be threaded through all three
7687    /// open-coded copies in lockstep or one consumer would silently
7688    /// disagree with the peers on which placement composite a given
7689    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
7690    /// seed reading the raw slot while the peer
7691    /// `programs_for_aplicacao` emitter read an operator-resolved slot
7692    /// would silently split the build-time distribution-shape gate from
7693    /// the runtime programs.yaml distribution-annotation gate, a three-
7694    /// consumer split at the validator, the programs.yaml emitter, and
7695    /// the `feira app graph` printer far from the source `caixa.lisp`
7696    /// with no field naming the placement-drift root cause. Lifting the
7697    /// resolution rule to a typed method on the substrate primitive
7698    /// means every downstream consumer of the Aplicacao's per-
7699    /// `:placement` distribution composite surface reaches for exactly
7700    /// one typed dispatch — the resolver's accept-set migrates as a unit
7701    /// on any future axis addition.
7702    ///
7703    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
7704    /// `AplicacaoSpec` type itself — sibling to the seed
7705    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
7706    /// composite-reference accessor on the peer per-`:politicas` outer-
7707    /// composite axis, and to the paired slice-return accessors
7708    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
7709    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
7710    /// the two `Vec`-carry axes on the outer typed composition view; the
7711    /// outer `:placement` composite-reference axis is the natural pair
7712    /// to the peer `:politicas` composite-reference axis on the two
7713    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
7714    /// how-to-run policy overlay, `:placement` carries the where-to-run
7715    /// distribution composite — every whole-Aplicacao mesh-artifact
7716    /// emitter reads both as one unit). Same "one typed dispatch on the
7717    /// substrate primitive, thin projections at each consumer"
7718    /// discipline the peer per-`:politicas` composite-reference axis
7719    /// already routes through. The one remaining outer-composite axis
7720    /// still unlifted at the time of this lift —
7721    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
7722    /// external-gateway composite) — inherits this accessor's discipline
7723    /// as the next compounding run migrates its consumers onto the shared
7724    /// reference-return shape, closing the outer-composite altitude on
7725    /// every M3 mesh-slot axis. Named `placement()` to match the storage
7726    /// field's name verbatim and the tatara-lisp author-surface term
7727    /// (`:placement`) the field's own docstring already carries; the
7728    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
7729    /// vocabulary the slot's docstring already reaches for. Returns
7730    /// `&Placement` (not the owning composite by copy or clone) because
7731    /// every downstream consumer of the placement composite treats it as
7732    /// a read-only per-axis dispatch source — the reference-view is the
7733    /// narrowest borrow that supports every present + roadmapped consumer
7734    /// (per-axis accessor dispatch, serde composite-serialization) without
7735    /// cloning the composite through every consumer's fast path.
7736    #[must_use]
7737    pub const fn placement(&self) -> &Placement {
7738        &self.placement
7739    }
7740
7741    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
7742    /// per-Aplicacao external-gateway composite optional-composite-
7743    /// reference accessor every per-Aplicacao gateway-block reader
7744    /// keys off — returns the author-declared `:entrada` composite
7745    /// verbatim as an `Option<&Entrada>` reference over the same
7746    /// backing storage the raw `self.entrada.as_ref()` field access
7747    /// borrows from, with `None` naming the internal-only mesh shape
7748    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
7749    /// gateway_routes emitter treats as "emit nothing" and the peer
7750    /// `feira app graph` printer treats as "internal-only mesh").
7751    ///
7752    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
7753    /// external-gateway composite — the load-bearing container of
7754    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
7755    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
7756    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
7757    /// hostname axis, §III.4 for the `:para` destination-Servico
7758    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
7759    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
7760    /// axis threads through a lifted per-slot accessor on the
7761    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
7762    /// Gateway-API `Listener.hostname` scalar accessor, the paired
7763    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
7764    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
7765    /// backendRefs destination-Servico scalar accessor, the
7766    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
7767    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
7768    /// scalar accessor. Every downstream consumer that reaches for
7769    /// an entrada axis first passes through this outer accessor onto
7770    /// the composite and then dispatches onto the per-axis accessor
7771    /// — the two-level dispatch means every per-`:entrada` reader
7772    /// now routes through a typed dispatch on the substrate primitive
7773    /// at both altitudes.
7774    ///
7775    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
7776    /// was accessed inline at four production sites — the
7777    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
7778    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
7779    /// (which drives every per-axis refusal on the composite: the
7780    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
7781    /// `EntradaMemberMissing` membership lookup against the
7782    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
7783    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
7784    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
7785    /// per-path shape gate on each entry of `e.paths`), the
7786    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
7787    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
7788    /// composite-projection seed (which drives the destination-
7789    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
7790    /// backendRefs port emitter fans on), the
7791    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
7792    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
7793    /// early-return seed (which drives the "no `:entrada` ⇒ no
7794    /// external artifacts" partition on the whole-Aplicacao Gateway-
7795    /// API emitter's fan-out), and the `feira app graph` per-
7796    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
7797    /// external-gateway summary emitter (which drives the human-
7798    /// readable `entrada: host → para (paths=…, port=…)` /
7799    /// `entrada: (internal-only mesh)` partition on the typed
7800    /// Aplicacao view) — four open-coded outer-field accesses that
7801    /// expressed no compile-time link back to the typed slot at the
7802    /// [`AplicacaoSpec`] altitude. A future extension of the
7803    /// `:entrada` outer axis to a richer author surface (a
7804    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
7805    /// at admission time so an Aplicacao can expose a public-web +
7806    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
7807    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
7808    /// operator can pin a per-cluster hostname override without
7809    /// re-authoring the `caixa.lisp`, a promotion of the plain
7810    /// `Option<Entrada>` to a richer `{single, multi}` partition once
7811    /// the multi-`:entrada` roadmap lands) would have had to be
7812    /// threaded through all four open-coded copies in lockstep or one
7813    /// consumer would silently disagree with the peers on which
7814    /// entrada composite a given Aplicacao resolves to — the
7815    /// validator's per-axis bracket-dispatch seed reading the raw
7816    /// slot while the peer `gateway_routes` emitter read an
7817    /// operator-resolved slot would silently split the build-time
7818    /// gateway-shape gate from the runtime Gateway + HTTPRoute
7819    /// emission gate, a four-consumer split at the validator, the
7820    /// `port_for_destination` L4-port resolver, the `gateway_routes`
7821    /// emitter, and the `feira app graph` printer far from the
7822    /// source `caixa.lisp` with no field naming the entrada-drift
7823    /// root cause. Lifting the resolution rule to a typed method on
7824    /// the substrate primitive means every downstream consumer of
7825    /// the Aplicacao's per-`:entrada` external-gateway composite
7826    /// surface reaches for exactly one typed dispatch — the
7827    /// resolver's accept-set migrates as a unit on any future axis
7828    /// addition.
7829    ///
7830    /// Third and final `&Composite`-return accessor on the top-level
7831    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
7832    /// unlifted outer-composite axis on the outer typed composition
7833    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
7834    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
7835    /// accessor on the per-`:politicas` outer-composite axis and to
7836    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
7837    /// distribution-composite composite-reference accessor on the
7838    /// per-`:placement` outer-composite axis; extends the outer-
7839    /// composite reference-return discipline the two peers already
7840    /// route through onto the last unlifted per-`AplicacaoSpec`
7841    /// outer-composite axis. The `:entrada` outer-composite axis is
7842    /// the natural pair to the two peer outer-composite axes on the
7843    /// three operationally-symmetric M3 mesh-slot outer composites
7844    /// (`:politicas` carries the how-to-run policy overlay,
7845    /// `:placement` carries the where-to-run distribution composite,
7846    /// `:entrada` carries the who-can-reach-it external-gateway
7847    /// composite — every whole-Aplicacao mesh-artifact emitter reads
7848    /// all three as one unit). Same "one typed dispatch on the
7849    /// substrate primitive, thin projections at each consumer"
7850    /// discipline the peer outer-composite axes already route through.
7851    /// Named `entrada()` to match the storage field's name verbatim
7852    /// and the tatara-lisp author-surface term (`:entrada`) the
7853    /// field's own docstring already carries; the accessor's
7854    /// identity maps onto the canonical MESH-COMPOSITION §III.4
7855    /// vocabulary the slot's docstring already reaches for. Returns
7856    /// `Option<&Entrada>` (not the owning composite by copy or
7857    /// clone) because every downstream consumer of the entrada
7858    /// composite treats it as a read-only per-axis dispatch source
7859    /// — the reference-view is the narrowest borrow that supports
7860    /// every present + roadmapped consumer (per-axis accessor
7861    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
7862    /// port-fallback projection, early-return partition on the
7863    /// `None` arm) without cloning the composite through every
7864    /// consumer's fast path. The `Option` half of the return-type
7865    /// preserves the load-bearing "author-omitted `:entrada` ⇒
7866    /// internal-only mesh" partition (not a default composite the
7867    /// downstream must reject on emptiness) — the accessor projects
7868    /// the raw `Option<Entrada>` slot's presence bit through the
7869    /// reference-return unchanged.
7870    #[must_use]
7871    pub const fn entrada(&self) -> Option<&Entrada> {
7872        self.entrada.as_ref()
7873    }
7874
7875    /// Validate the typed shape:
7876    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
7877    ///     and a non-empty `:versao`; no two entries share the same
7878    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
7879    ///     not a multiset)
7880    ///   - every `:contratos` :de + :para must be in `:membros`
7881    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
7882    ///     contract is an inter-Servico edge, so a Servico contracting
7883    ///     with itself is a build error under every WIT shape
7884    ///     (MESH-COMPOSITION §III.1)
7885    ///   - no two `:contratos` entries agree on
7886    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
7887    ///     edges are a set, not a multiset (peer of the `:membros` /
7888    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
7889    ///   - `:entrada :para` must be in `:membros`
7890    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
7891    ///     `:placement Replicated`/`SingleNode` must NOT declare
7892    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
7893    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
7894    ///     between strategy and shard-key is symmetric: every validated
7895    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
7896    ///     Sharded`
7897    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
7898    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
7899    ///     the shard pool (MESH-COMPOSITION §III.1)
7900    ///   - every `:clusters` entry is non-empty and unique
7901    ///   - `:placement :affinity`, when set, is non-empty
7902    ///   - the synchronous-`:contratos` subgraph is acyclic
7903    ///     (MESH-COMPOSITION §III.3)
7904    ///   - every declared `:politicas` value is operationally meaningful
7905    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
7906    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
7907    ///     omit the field instead to express "no policy on this axis")
7908    pub fn validate(&self) -> Result<(), AplicacaoError> {
7909        self.validate_membros()?;
7910
7911        // `:contratos` per-slot gate — folds both structural axes on the
7912        // slot into one substrate primitive: the per-entry cascade (shape
7913        // + membership + self-loop + `:wit` emptiness + WIT-shape ↔
7914        // target + whole-edge dedup) and the cross-edge sync-cycle axis
7915        // ([`AplicacaoSpec::detect_sync_cycles`], MESH-COMPOSITION §III.3
7916        // — pub-sub edges excluded, "acyclic by construction"). Same
7917        // fold-per-axis-plus-cross-axis discipline the sibling
7918        // [`AplicacaoSpec::validate_politicas`] per-slot gate carries via
7919        // [`MeshPolicy::validate`] (f03a154 / 90a6f87), extended here
7920        // onto `:contratos` so every future consumer of the slot (the M4
7921        // admission webhook re-checking `:contratos` after a per-edge
7922        // patch, the per-edge policy resolver MESH-COMPOSITION §III.2 #3
7923        // acknowledges) reaches *both* structural axes through one call.
7924        self.validate_contratos()?;
7925
7926        self.validate_entrada()?;
7927
7928        self.validate_placement()?;
7929
7930        self.validate_politicas()?;
7931
7932        Ok(())
7933    }
7934
7935    /// The `:membros` graph-node name set — the membership oracle every
7936    /// per-Aplicacao name-reference axis resolves against.
7937    ///
7938    /// Three per-Aplicacao axes carry a Servico-name *reference* rather
7939    /// than a Servico-name *declaration*: `:contratos :de`, `:contratos
7940    /// :para`, and `:entrada :para`. Each must resolve to a declared
7941    /// `:membros :caixa` (MESH-COMPOSITION §III.1 — the typed edges and
7942    /// the external gateway both address graph nodes, so a reference to
7943    /// a node the graph does not contain is a build error). All three
7944    /// resolve against *this* set, so the set's construction is the one
7945    /// shared substrate primitive underneath the whole reference-
7946    /// resolution surface.
7947    ///
7948    /// Lifted out of [`AplicacaoSpec::validate`]'s inline
7949    /// `self.membros().iter().map(Membro::nome).collect()` builder so
7950    /// the two per-slot gates that consume it — the per-`:contratos`
7951    /// membership arms still inline at `validate` and the lifted
7952    /// [`AplicacaoSpec::validate_entrada`] below — reach the same
7953    /// oracle through one dispatch rather than each open-coding the
7954    /// projection. Every future consumer on the same axis (the M4
7955    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
7956    /// reference resolver, the per-`:contratos`-edge `:politicas`
7957    /// override MESH-COMPOSITION §III.2 #3 acknowledges — which
7958    /// resolves an edge's endpoints against the same membership set
7959    /// before it can key a per-edge policy off them) inherits the
7960    /// projection through the same call, so a future rebrand of the
7961    /// node-identity axis (a namespace-qualified member name the CR
7962    /// materializer applies per-CR, the `:membros :nome-suffix`
7963    /// overlay §III.2 acknowledges) lands at exactly one place rather
7964    /// than at every reference-resolution site in lockstep. Peer of
7965    /// the sibling per-slot substrate primitives
7966    /// [`MeshPolicy::validate`] (f03a154) and
7967    /// [`WitContract::identity`] on their own axes.
7968    fn membro_names(&self) -> std::collections::HashSet<&str> {
7969        self.membros().iter().map(Membro::nome).collect()
7970    }
7971
7972    /// Reject `:contratos` entries whose endpoints are malformed,
7973    /// reference a Servico outside the graph, self-loop, carry an
7974    /// empty `:wit` shape, duplicate a prior entry on the six-axis
7975    /// identity key, or close a synchronous-edge cycle in the
7976    /// resulting typed graph.
7977    ///
7978    /// The `:contratos` slot is the typed inter-Servico edge set
7979    /// (MESH-COMPOSITION §III.1): each entry is a WIT-typed directed
7980    /// edge whose `:de` / `:para` reference two distinct members and
7981    /// whose `:wit` picks the payload shape the paired L4/L7 renderer
7982    /// (caixa-mesh's per-`(:de, :para)` `CiliumNetworkPolicy` +
7983    /// per-HTTP `HTTPRoute`) fans out on.
7984    ///
7985    /// Two structural axes on the slot are folded into this per-slot
7986    /// gate: the per-entry axis (six per-edge arms, listed below) and
7987    /// the cross-edge synchronous-cycle axis (MESH-COMPOSITION §III.3,
7988    /// dispatched to [`AplicacaoSpec::detect_sync_cycles`] after the
7989    /// per-entry cascade). Same
7990    /// per-axis-plus-cross-axis-fold-into-one-per-slot-gate discipline
7991    /// the sibling [`AplicacaoSpec::validate_politicas`] per-slot gate
7992    /// carries via [`MeshPolicy::validate`] (f03a154 / 90a6f87) on the
7993    /// `:politicas` slot, extended here onto `:contratos`.
7994    ///
7995    /// Six per-entry axes are gated first, in the canonical
7996    /// edge-direction order the paired diagnostics already encode
7997    /// (per-arm value shape before graph-membership lookup; structural
7998    /// self-edge before payload-shape target dispatch; whole-edge dedup
7999    /// last):
8000    ///
8001    ///   - per-arm `:de` / `:para` value shape via
8002    ///     [`validate_contrato_caixa`] (empty + DNS-1123 grammar),
8003    ///     `:de` before `:para`;
8004    ///   - per-edge graph-membership against the
8005    ///     [`AplicacaoSpec::membro_names`] oracle via
8006    ///     [`WitContract::require_endpoints_in`] (folds the twin
8007    ///     `:de` / `:para` arms onto one substrate-primitive
8008    ///     dispatch), `:de` before `:para`;
8009    ///   - structural self-edge via [`WitContract::is_self_loop`]
8010    ///     (caller-equals-callee under any WIT shape);
8011    ///   - `:wit` emptiness ([`AplicacaoError::EmptyWit`]);
8012    ///   - WIT shape ↔ target consistency via [`WitContract::target`]
8013    ///     (the four `WitTarget` arms — `Http` / `PubSub` / `Store` /
8014    ///     `Capability` — each carry their own required payload field);
8015    ///   - six-axis whole-edge dedup via [`WitContract::identity`]
8016    ///     ([`ContratoIdentity`]'s `(de, para, wit, endpoint, subject,
8017    ///     slot)` tuple).
8018    ///
8019    /// One cross-edge axis is gated last, after the per-entry cascade
8020    /// completes cleanly:
8021    ///
8022    ///   - synchronous-edge cycle detection via
8023    ///     [`AplicacaoSpec::detect_sync_cycles`] (iterative DFS with
8024    ///     three-coloring over the sync-only subgraph, pub-sub edges
8025    ///     skipped per MESH-COMPOSITION §III.3 —
8026    ///     [`AplicacaoError::ContratoCycle`]). Runs *after* the
8027    ///     per-entry cascade so a per-entry defect surfaces through its
8028    ///     narrower shape/membership/dedup arm before the cross-edge
8029    ///     cycle diagnostic, matching the pre-fold `validate`-side
8030    ///     dispatch ordering (`validate_contratos()? →
8031    ///     detect_sync_cycles()?`).
8032    ///
8033    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `let mut
8034    /// seen_contracts = …; for c in self.contratos() { … }` block onto
8035    /// a named per-slot gate, closing the last unlifted per-slot gate
8036    /// on the M3 mesh-slot family. Every peer slot already carries the
8037    /// shape ([`AplicacaoSpec::validate_membros`],
8038    /// [`AplicacaoSpec::validate_entrada`],
8039    /// [`AplicacaoSpec::validate_placement`],
8040    /// [`AplicacaoSpec::validate_politicas`]).
8041    ///
8042    /// Self-contained on `&self` — it resolves its own membership
8043    /// oracle through [`AplicacaoSpec::membro_names`] rather than
8044    /// borrowing one threaded down from `validate`, and runs its own
8045    /// cross-edge cycle probe rather than deferring the axis to an
8046    /// outer dispatch — so a future consumer that re-validates *one*
8047    /// slot against a mutated spec (the M4 admission webhook
8048    /// re-checking `:contratos` after a per-`(:de, :para)` edge patch
8049    /// without re-walking `:membros` / `:entrada` / `:placement` /
8050    /// `:politicas`, or the M4 per-edge policy resolver
8051    /// MESH-COMPOSITION §III.2 #3 acknowledges — which resolves an
8052    /// effective per-edge [`MeshPolicy`] and must re-check the edge's
8053    /// own identity closure *and* the sync-cycle invariant before it
8054    /// can key a per-edge override off the endpoint tuple) reaches
8055    /// *both* structural axes on the slot through one call, exactly as
8056    /// [`AplicacaoSpec::validate_politicas`] reaches both per-axis and
8057    /// cross-axis surfaces on `:politicas` through
8058    /// [`MeshPolicy::validate`].
8059    fn validate_contratos(&self) -> Result<(), AplicacaoError> {
8060        let names = self.membro_names();
8061
8062        // Identity key for the typed-edge duplicate gate below: every
8063        // field that distinguishes one contract from another. Two
8064        // entries that agree on all six are *the same edge declared
8065        // twice*, the typed-graph analogue of duplicate `:membros` /
8066        // `:placement :clusters` / `:entrada :paths` entries (which
8067        // are already build errors at this layer). Rejecting it at the
8068        // validate gate closes a renderer-side footgun: caixa-mesh's
8069        // `cilium_network_policies` keys each emitted policy by
8070        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
8071        // (de, para) and identical payload would land as two K8s
8072        // objects with colliding `metadata.name`, rejected at apply
8073        // time far from the source caixa.lisp.
8074        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
8075            std::collections::HashSet::new();
8076        for c in self.contratos() {
8077            // Per-axis value-shape gate on every `:contratos` name
8078            // reference, before any graph-membership lookup. Empty +
8079            // DNS-1123-malformed `:de`/`:para` values silently fell
8080            // through to `ContratoMemberMissing` at the lookup arm
8081            // because every `:membros :caixa` is shape-validated
8082            // (3f9d7a0), so the `names` set structurally cannot contain
8083            // an empty / malformed string and the membership-lookup
8084            // diagnostic always misframed the root cause as
8085            // "this caixa is not in `:membros`". The shape gate runs
8086            // ahead of the lookup so structurally-impossible-to-match
8087            // inputs route through the narrower self-locating
8088            // diagnostic, preserving the legitimate "well-shaped
8089            // phantom reference" arm. `:de` runs before `:para` per
8090            // the canonical edge-direction order the existing
8091            // membership lookup, self-edge check, target dispatch,
8092            // and diagnostic strings already use.
8093            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
8094            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
8095            // Per-edge graph-membership gate on the twin `:de` / `:para`
8096            // arms — folded onto the substrate-primitive dispatch
8097            // [`WitContract::require_endpoints_in`] so every per-edge
8098            // consumer of the endpoint-resolution axis (this per-slot
8099            // gate at build time, the M4 admission webhook re-checking
8100            // one edge after a per-`(:de, :para)` patch, the per-edge
8101            // `:politicas` override MESH-COMPOSITION §III.2 #3
8102            // acknowledges) reaches the axis through one call rather
8103            // than re-inlining the twin `if !names.contains(...)`
8104            // cascade. `:de` fires before `:para` inside the primitive,
8105            // preserving byte-equal diagnostic ordering with the
8106            // pre-lift inline cascade.
8107            c.require_endpoints_in(&names)?;
8108            // A `:contratos` entry is an *inter*-Servico contract
8109            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
8110            // typed edge between two distinct graph nodes. An edge whose
8111            // `:de` equals its `:para` is a Servico contracting with
8112            // itself — a degenerate edge under every WIT shape. Firing
8113            // the gate before the `:wit`/`target()` shape checks means
8114            // the structural "this edge can't exist" error precedes the
8115            // narrower payload-shape diagnostics, and shape-agnostically
8116            // covers all four `WitTarget` arms (HTTP / Store / Capability
8117            // / PubSub) at one point. Peer of the duplicate-`:contratos`
8118            // / duplicate-`:membros` set gates: both reject a structurally
8119            // ill-formed graph at the typed surface, before the renderer
8120            // emits a K8s object that fails or no-ops far from the source
8121            // caixa.lisp.
8122            if c.is_self_loop() {
8123                return Err(AplicacaoError::contrato_self_loop(c));
8124            }
8125            if c.world_ref().is_empty() {
8126                return Err(AplicacaoError::empty_wit(c.edge_pair()));
8127            }
8128            // Shape ↔ target consistency — surfaces "HTTP wit without
8129            // :endpoint", "NATS wit with :endpoint set", etc. as named
8130            // build errors instead of silent renderer drops. Threaded
8131            // through the duplicate-edge diagnostic below (via
8132            // [`WitTarget::label`]) so the "which typed target arm did
8133            // the duplicate carry" question is answered by the typed
8134            // enum's variant discriminator, not by re-probing the raw
8135            // `Option<String>` payload fields.
8136            let target_view = c.target()?;
8137            // Contract identity: (de, para, wit, endpoint, subject, slot).
8138            // Two contracts that match on all six are the same typed edge
8139            // declared twice — author error, not a legitimate variant of
8140            // "same caller-callee pair, different payload" (e.g.
8141            // cart→catalog at /products vs /search), which keeps distinct
8142            // identity keys via the differing endpoint payloads.
8143            let key = c.identity();
8144            crate::render::insert_first_seen(&mut seen_contracts, key, || {
8145                AplicacaoError::contrato_duplicate(c, &target_view)
8146            })?;
8147        }
8148
8149        // Cross-edge cycle axis on the `:contratos` slot — folded into
8150        // the per-slot gate so the two structural axes on `:contratos`
8151        // (per-entry shape + membership + dedup above; cross-edge sync-
8152        // cycle detection here) reach every consumer through one call.
8153        // Same discipline the sibling per-slot compound gate
8154        // [`MeshPolicy::validate`] (f03a154) established on `:politicas`
8155        // — one named per-slot gate that folds *both* per-axis and
8156        // cross-axis surfaces on the same slot onto one substrate
8157        // primitive — extended here onto `:contratos`, closing the last
8158        // per-slot-axis-family that lived split across `validate` (the
8159        // per-entry `validate_contratos` half here and the cross-edge
8160        // `detect_sync_cycles` call the sibling below at `validate`
8161        // dispatched separately).
8162        //
8163        // Runs after the per-entry cascade so a per-entry defect (empty
8164        // arm, unknown endpoint, self-loop, empty `:wit`, WIT-shape ↔
8165        // target inconsistency, whole-edge duplicate) surfaces first
8166        // through its narrower [`AplicacaoError`] arm before the cross-
8167        // edge cycle diagnostic. This matches the pre-lift ordering the
8168        // `validate`-side dispatch used verbatim (`self.validate_contratos()?
8169        // → self.detect_sync_cycles()?`) — the cycle detector was
8170        // already the second `:contratos`-axis gate in the dispatch,
8171        // just at the outer altitude; the fold moves it under the same
8172        // named per-slot gate without reshaping the diagnostic order.
8173        self.detect_sync_cycles()?;
8174
8175        Ok(())
8176    }
8177
8178    /// Reject `:entrada` values that are operationally meaningless,
8179    /// structurally malformed, or reference a Servico outside the
8180    /// graph.
8181    ///
8182    /// The `:entrada` slot is the Aplicacao's single external ingress
8183    /// (MESH-COMPOSITION §III.1): `:host` + `:port` become a K8s
8184    /// Gateway API v1 `Listener`, `:paths` become the paired
8185    /// `HTTPRoute`'s `matches[].path.value` entries, and `:para` names
8186    /// the member the route forwards to. Omitting the slot entirely is
8187    /// the internal-only-mesh partition — an Aplicacao with no external
8188    /// surface — so the `None` arm is a clean pass, not a refusal.
8189    ///
8190    /// Five axes are gated here, in the canonical order the paired
8191    /// diagnostics already encode (reference-resolution before value
8192    /// shape, per-axis emptiness before per-axis grammar):
8193    ///
8194    ///   - `:para` — DNS-1123 value shape, then membership against the
8195    ///     [`AplicacaoSpec::membro_names`] oracle;
8196    ///   - `:host` — emptiness, then the Gateway API hostname grammar;
8197    ///   - `:port` — the [`SERVICO_PORT_MIN`] structural floor;
8198    ///   - `:paths` — per-entry emptiness, leading-`/`, the Gateway API
8199    ///     path grammar, and set-not-multiset uniqueness.
8200    ///
8201    /// Lifted out of [`AplicacaoSpec::validate`]'s inline `if let
8202    /// Some(e) = self.entrada() { … }` block onto a named per-slot
8203    /// gate, the shape the three peer M3 mesh slots already carry
8204    /// ([`AplicacaoSpec::validate_membros`],
8205    /// [`AplicacaoSpec::validate_placement`],
8206    /// [`AplicacaoSpec::validate_politicas`]). Self-contained on
8207    /// `&self` — it resolves its own membership oracle through
8208    /// [`AplicacaoSpec::membro_names`] rather than borrowing one
8209    /// threaded down from `validate` — so a future consumer that
8210    /// re-validates *one* slot against a mutated spec (the M4 admission
8211    /// webhook re-checking `:entrada` after a gateway-host patch
8212    /// without re-walking the whole `:contratos` graph) reaches the
8213    /// axis through one call, exactly as `detect_sync_cycles` is
8214    /// already self-contained for the M4 per-edge policy resolver.
8215    fn validate_entrada(&self) -> Result<(), AplicacaoError> {
8216        let names = self.membro_names();
8217        if let Some(e) = self.entrada() {
8218            // Route the per-`:entrada` composite-reference read
8219            // through the lifted [`AplicacaoSpec::entrada`] accessor
8220            // rather than the raw `&self.entrada` field access — the
8221            // shape-and-membership gate's traversal head is now the
8222            // canonical read-side surface every per-Aplicacao entrada
8223            // consumer routes through, closing the fourth of four
8224            // open-coded outer-field accesses on the per-`:entrada`
8225            // outer-composite axis.
8226            //
8227            // Shape gate on `:entrada :para` runs ahead of the
8228            // membership lookup. Every `:membros :caixa` past
8229            // `validate_membro_caixa` is a valid DNS-1123 label
8230            // (3f9d7a0), so the `names` set structurally cannot
8231            // contain an empty / malformed string and the membership-
8232            // lookup diagnostic always misframed the root cause as
8233            // "this caixa is not in `:membros`". The shape gate
8234            // routes structurally-impossible-to-match inputs through
8235            // the narrower self-locating diagnostic, preserving the
8236            // legitimate "well-shaped phantom reference" arm — the
8237            // same trajectory the peer `:membros :caixa` (3f9d7a0),
8238            // `:placement :clusters` (6c8c00b), and `:contratos :de`
8239            // / `:para` (8d5af6b) axes already follow. This closes
8240            // the fourth and last Aplicacao-level Servico-name
8241            // reference axis on the canonical DNS-1123 floor.
8242            // Route the per-`:entrada :para` byte-string reads through
8243            // the lifted [`Entrada::destination`] accessor rather than
8244            // the raw `e.para` field access — the three
8245            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
8246            // (shape-gate `validate_entrada_para` arg, membership
8247            // lookup, `EntradaMemberMissing` diagnostic carry) now key
8248            // off exactly one typed dispatch on the substrate
8249            // primitive, closing the last unlifted per-`:entrada :para`
8250            // raw-field-access axis on the M3 mesh-slot validator.
8251            // The `.destination().to_string()` at the diagnostic site
8252            // is byte-identical to `.para.clone()` — pinned by the
8253            // sibling `destination_returns_entrada_para_byte_equal` +
8254            // `destination_borrows_from_entrada_para_storage` accessor
8255            // tests — so a future rebrand of the underlying `:para`
8256            // storage (a lift from `String` to a typed
8257            // `ServicoName(String)` newtype, a per-Aplicacao interning
8258            // arena the M4 CR materializer authors, a
8259            // `smol_str::SmolStr` inline-buffer swap) flows through
8260            // the accessor's one body without a coordinated
8261            // per-consumer rewrite across the M3 mesh validator.
8262            validate_entrada_para(e.destination())?;
8263            if !names.contains(e.destination()) {
8264                return Err(AplicacaoError::entrada_member_missing(e));
8265            }
8266            // Route the per-`:entrada :host` byte-string reads through
8267            // the lifted [`Entrada::hostname`] accessor rather than
8268            // the raw `e.host` field access — the emptiness gate and
8269            // the shape-gate `validate_entrada_host` arg now key off
8270            // exactly one typed dispatch on the substrate primitive,
8271            // closing the last unlifted per-`:entrada :host` raw-
8272            // field-access axis on the M3 mesh-slot validator. Peer
8273            // of the sibling per-`:entrada :para` convergence above
8274            // and pinned by the existing
8275            // `hostname_returns_entrada_host_byte_equal` +
8276            // `hostnames_returns_singleton_of_hostname_accessor`
8277            // accessor tests, so any future
8278            // Gateway-API-shaped host renormalization (a wildcard-
8279            // label lift, a trailing-`.` FQDN substitution, an IDNA
8280            // Punycode round-trip the SNI fan-out overlay authors)
8281            // flows through the accessor's one body without a
8282            // coordinated per-consumer rewrite across the M3 mesh
8283            // validator.
8284            if e.hostname().is_empty() {
8285                return Err(AplicacaoError::EmptyEntradaHost);
8286            }
8287            // The `:host` lands verbatim as a K8s Gateway API v1
8288            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
8289            // both apiserver-validated against the same restrictive
8290            // pattern: lowercase RFC 1123 DNS subdomain, optional
8291            // single leading wildcard label (`*.`), max length 253,
8292            // per-label max length 63, no IP literals, no scheme,
8293            // no port. Until this gate landed `validate()` only
8294            // refused the empty string (`EmptyEntradaHost`); a
8295            // structurally invalid hostname (`"https://example.com"`,
8296            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
8297            // `"_underscored.example.com"`, `"FOO.example.com"`,
8298            // `"checkout.quero.cloud."`) silently passed validate
8299            // and the apiserver `field is invalid` error surfaced at
8300            // `kubectl apply` time, far from the source caixa.lisp.
8301            // Lifting the gate to caixa-build time mirrors the
8302            // `:entrada :paths` value-shape trajectory (eb3456d) and
8303            // closes the last unstructured `:entrada` axis.
8304            validate_entrada_host(e.hostname())?;
8305            // Structural-floor gate on `:entrada :port`: every
8306            // validated `Entrada::port` past this gate lies in
8307            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
8308            // type-inferred ceiling closes the top edge, so no companion
8309            // upper-cap arm is needed here — unlike the peer capped-
8310            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
8311            // `require_positive_bounded_u32` bracket covers both edges).
8312            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
8313            // accept-set-floor const rather than the prior inline
8314            // `if e.port == 0` byte-check so a future rebrand of the
8315            // accept-set floor (a hypothetical unprivileged-only
8316            // migration lifting the floor to `1024`, a per-cluster
8317            // scoping the operator pins through a future
8318            // `:placement :port-floor` slot as the M4 typed-slot
8319            // trajectory adds it, the future
8320            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8321            // per-Aplicacao gateway resolver reaching for the same
8322            // floor) is a one-line edit on the canonical
8323            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
8324            // rewrite across the emit site + the pin test + every
8325            // future per-target renderer the substrate adds.
8326            if e.port() < SERVICO_PORT_MIN {
8327                return Err(AplicacaoError::EntradaPortZero);
8328            }
8329            // Each `:entrada :paths` entry becomes a K8s Gateway API
8330            // HTTPRoute `matches[].path.value`. The Gateway API rejects
8331            // values that don't start with `/` for `type: PathPrefix`,
8332            // and an empty value is meaningless. Surface those as build
8333            // errors (MESH-COMPOSITION §III.3) rather than apply-time
8334            // failures. Empty `:paths` itself is fine — caixa-mesh
8335            // falls back to a single `/` catch-all.
8336            let mut seen = std::collections::HashSet::new();
8337            // Route the per-entry value-shape gate's traversal head
8338            // through the lifted [`Entrada::paths`] slice accessor
8339            // rather than the raw `&e.paths` field access — the
8340            // per-Aplicacao `:entrada :paths` validate loop now keys
8341            // off the canonical raw-slot surface every downstream
8342            // per-`:entrada` path-list consumer (the sibling
8343            // [`Entrada::resolved_paths`] fallback-applying resolver
8344            // internal reads, `feira app graph`'s per-Aplicacao entrada
8345            // summary line's `{:?}` Debug print) routes through, so any
8346            // future rebrand on the typed slot's raw-slot reader lands
8347            // at exactly one place. Same convergence discipline as the
8348            // sibling [`Placement::clusters`] (a6e18d7) reader-site
8349            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
8350            // axis.
8351            for p in e.paths() {
8352                if p.is_empty() {
8353                    return Err(AplicacaoError::EntradaPathEmpty);
8354                }
8355                if !p.starts_with('/') {
8356                    return Err(AplicacaoError::entrada_path_not_absolute(p));
8357                }
8358                // Per-entry value-shape gate: the path lands verbatim
8359                // as a K8s Gateway API HTTPRoute `matches[].path.value`
8360                // (caixa-mesh/src/lib.rs:498), apiserver-validated
8361                // against `maxLength: 1024` + the Gateway API webhook's
8362                // path-grammar rules (no `//`, no `/./`, no `/../`, no
8363                // query/fragment separators, no whitespace, no control
8364                // characters, no non-ASCII bytes). Until this gate
8365                // landed `validate` only refused the empty string and
8366                // missing-leading-slash (eb3456d); a structurally
8367                // invalid path (`"/api?q=1"`, `"/api#frag"`,
8368                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
8369                // 1025-byte URL-shaped slug) silently passed validate
8370                // and the failure surfaced at `kubectl apply` time as
8371                // a Gateway API webhook rejection, far from the source
8372                // caixa.lisp, with no field naming the offending
8373                // `:paths` entry. Lifting the gate to caixa-build time
8374                // mirrors the `:entrada :host` value-shape trajectory
8375                // (c7d05ec) on the sibling axis — every author surface
8376                // that emits a Gateway API field now matches the
8377                // apiserver's accepted set at validate time.
8378                validate_entrada_path(p)?;
8379                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
8380                    AplicacaoError::entrada_path_duplicate(p)
8381                })?;
8382            }
8383        }
8384
8385        Ok(())
8386    }
8387
8388    /// Reject `:membros` values that are operationally meaningless. The
8389    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
8390    /// every entry names a Servico that participates in the Aplicacao,
8391    /// and the rendered programs.yaml fan-out emits one entry per
8392    /// `:membros`. Three authoring footguns are closed here:
8393    ///
8394    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
8395    ///     a `programs:` entry whose `name:` is the empty string, which
8396    ///     downstream `lareira-fleet-programs` rejects at template time
8397    ///     with a non-localized error;
8398    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
8399    ///     an empty semver constraint, so the failure surfaces far from
8400    ///     the source caixa.lisp;
8401    ///   - duplicate `:caixa` names — two entries with the same name
8402    ///     produce duplicate programs.yaml entries (one silently
8403    ///     overwrites the other in the cluster's HelmRelease values), and
8404    ///     contract membership lookups against `:contratos` collapse the
8405    ///     two onto one node, masking authoring mistakes.
8406    ///
8407    /// Same value-shape discipline as `:placement :clusters` (where empty
8408    /// + duplicate cluster names are rejected) and `:entrada :paths`
8409    /// (where empty + duplicate path entries are rejected). Lifting these
8410    /// invariants to the typed surface mirrors the MESH-COMPOSITION
8411    /// §III.3 promise that the `:membros` set — the load-bearing identity
8412    /// of the application graph — is well-formed by construction.
8413    fn validate_membros(&self) -> Result<(), AplicacaoError> {
8414        if self.membros().is_empty() {
8415            return Err(AplicacaoError::NoMembros);
8416        }
8417        let mut seen = std::collections::HashSet::new();
8418        for m in self.membros() {
8419            // Every emitted cluster artifact's `metadata.name` derives
8420            // from a `:membros :caixa` value verbatim — the rendered
8421            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
8422            // the [`crate::LABEL_PROGRAM`] label value on every CNP
8423            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
8424            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
8425            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
8426            // `metadata.name` when the member is the `:entrada :para`
8427            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
8428            // schema enforces the DNS-1123 label rule on admission;
8429            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
8430            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
8431            // mistaken-identity slug) silently passes the prior empty-/
8432            // duplicate-only gate and the failure surfaces at `kubectl
8433            // apply` time as a `metadata.name: Invalid value` rejection,
8434            // far from the source caixa.lisp, with no field naming the
8435            // offending `:membros` entry. Lifting the gate to caixa-build
8436            // time mirrors the `:entrada :host` value-shape trajectory
8437            // (c7d05ec) on the peer axis — every author surface that
8438            // emits a K8s name now matches the apiserver's accepted set
8439            // at validate time.
8440            validate_membro_caixa(m.nome())?;
8441            // The author surface for `:versao` is the same Cargo-shaped
8442            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
8443            // `"*"`) every `:deps` entry carries — and the lacre pipeline
8444            // resolves both axes through the same
8445            // [`crate::version::parse_requirement`] entry-point. The
8446            // shared [`crate::render::require_valid_versao_requirement`]
8447            // helper brackets the empty-first + parse cascade both peer
8448            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
8449            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
8450            // route through, so drift between the three axes' accepted
8451            // requirement sets is structurally impossible and the parse-
8452            // side no-op the empty-first arm closes (semver's empty
8453            // parse yields an implicit `*`) lives in exactly one
8454            // predicate.
8455            crate::render::require_valid_versao_requirement(
8456                m.versao_requirement(),
8457                || AplicacaoError::membro_versao_empty(m.nome()),
8458                |reason| {
8459                    AplicacaoError::membro_versao_invalid(m.nome(), m.versao_requirement(), reason)
8460                },
8461            )?;
8462            crate::render::insert_first_seen(&mut seen, m.nome(), || {
8463                AplicacaoError::membro_duplicate(m.nome())
8464            })?;
8465        }
8466        Ok(())
8467    }
8468
8469    /// Reject `:placement` values that are operationally meaningless or
8470    /// internally contradictory. Each strategy variant has the same
8471    /// invariants on `:clusters` (non-empty list, non-empty unique
8472    /// entries) — the §III.1 author surface is uniform on this axis,
8473    /// even though the *meaning* of the list differs by strategy
8474    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
8475    /// shard pool).
8476    ///
8477    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
8478    /// are the same authoring footgun closed for `:politicas` zero
8479    /// values and `:entrada` empty paths: the field is *declared* but
8480    /// carries no meaning, so downstream renderers either skip it
8481    /// silently (cluster-fanout drops the empty entry, no diagnostic)
8482    /// or apply it literally and fail at admission time. Lifting both
8483    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
8484    /// violation is a build error" promise.
8485    ///
8486    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
8487    /// is required exactly when `:estrategia Sharded` (hash-keyed
8488    /// distribution, Akka cluster-sharding convention, §II.4) and
8489    /// refused on `:estrategia Replicated`/`SingleNode` (where no
8490    /// hash-keyed routing axis consumes it). The partition closes the
8491    /// "I think I configured sharding" footgun where an author writes
8492    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
8493    /// the typed slot's value silently vanishes at the renderer layer
8494    /// — every validated `Placement` past this call satisfies
8495    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
8496    fn validate_placement(&self) -> Result<(), AplicacaoError> {
8497        // Every strategy needs at least one named cluster: `Replicated`
8498        // and `SingleNode` use the list as hosting/takeover candidates
8499        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
8500        // §II.1), while `Sharded` uses it as the shard pool
8501        // (Akka cluster-sharding convention — §II.4). An empty list is
8502        // meaningless under any of the three.
8503        //
8504        // Route the paired pre-flight `.is_empty()` refusal probe and
8505        // the per-cluster validate loop's traversal head through the
8506        // lifted [`Placement::clusters`] slice-return accessor rather
8507        // than the raw `self.placement.clusters` field access — the
8508        // two production consumers of the per-`:placement` cluster-
8509        // pool `Vec`-carry now key off exactly one typed dispatch on
8510        // the substrate primitive, so any future rebrand on the axis
8511        // (a per-tenant cluster-pool overlay the operator pins through
8512        // a future `:placement :clusters-overrides` slot, a per-
8513        // Aplicacao dynamic cluster-pool derivation the future M5
8514        // adaptive-placement engine computes from `:affinity` weights)
8515        // migrates as a single caixa-core edit rather than a
8516        // coordinated rewrite of the paired arms — sibling of the
8517        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
8518        // arm migration on the per-`:supervisor` static-child-list
8519        // `Vec`-carry axis.
8520        //
8521        // Route the per-`:placement` outer-composite reference read
8522        // through the lifted [`AplicacaoSpec::placement`] outer accessor
8523        // rather than the raw `&self.placement` field access — the
8524        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
8525        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
8526        // axis-level lifted accessor family) now routes through the
8527        // substrate-primitive typed dispatch at the outer composition
8528        // altitude, the same shape the peer caixa-mesh
8529        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
8530        // and the sibling `feira app graph` per-Aplicacao print line
8531        // now key off after this accessor lift.
8532        let p = self.placement();
8533        if p.clusters().is_empty() {
8534            // Route the per-`:placement` empty-clusters diagnostic
8535            // through the substrate-primitive
8536            // [`AplicacaoError::placement_without_clusters`] ctor rather
8537            // than the pre-lift three-line open-coded
8538            // `AplicacaoError::PlacementWithoutClusters { estrategia:
8539            // p.estrategia() }` struct-literal — folds the sole in-crate
8540            // wire-up on this variant onto one dispatch matching the
8541            // sibling per-`:placement :clusters` dedup /
8542            // per-`:contratos` self-edge / per-`:upgrade-from :from`
8543            // duplicate substrate-primitive-projection ctors on the
8544            // same `AplicacaoError` / `UpgradeError` envelopes.
8545            return Err(AplicacaoError::placement_without_clusters(p));
8546        }
8547        let mut seen = std::collections::HashSet::new();
8548        for c in p.clusters() {
8549            // Per-entry value-shape gate: the cluster name lands in
8550            // every K8s context / `lareira-fleet-programs` aggregator
8551            // filter / future M4 CR materializer's per-cluster axis
8552            // a validated `:clusters` entry passes through, each
8553            // enforcing the DNS-1123 label rule on admission. Same
8554            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
8555            // on the peer name axis — both axes' validated values
8556            // are guaranteed-accepted by the apiserver without
8557            // re-validation at any downstream renderer or admission
8558            // layer.
8559            validate_placement_cluster(c)?;
8560            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
8561                // Route the per-`:placement :clusters` dedup diagnostic
8562                // through the substrate-primitive
8563                // [`AplicacaoError::placement_cluster_duplicate`] ctor
8564                // rather than the pre-lift three-line open-coded
8565                // `AplicacaoError::PlacementClusterDuplicate { cluster:
8566                // c.clone() }` struct-literal — folds the sole in-crate
8567                // wire-up on this variant onto one dispatch matching the
8568                // sibling per-`:membros :caixa` / per-`:entrada :paths` /
8569                // per-`:politicas <scalar>` single-slot ctor families on
8570                // the same [`AplicacaoError`] envelope.
8571                AplicacaoError::placement_cluster_duplicate(c)
8572            })?;
8573        }
8574        // Route the per-`:placement :affinity` per-hint value-shape
8575        // gate through the typed [`Placement::affinity`] accessor rather
8576        // than the raw `&self.placement.affinity` field access — the
8577        // sole open-coded field-access site on the per-`:placement`
8578        // M3-Adaptive-compression-hint axis the accessor lift now owns.
8579        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
8580        // the accessor's `Option<&str>` return type;
8581        // [`validate_placement_affinity`]'s `&str` parameter accepts
8582        // the narrower borrow without a re-allocation, so the routing
8583        // change is byte-for-byte in the pass arm and remains
8584        // byte-for-byte in every failure diagnostic
8585        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
8586        // String` field is populated inside
8587        // [`validate_placement_affinity`] via the peer `.to_string()`
8588        // path on the same borrowed slice). Peer of the sibling
8589        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
8590        // routing through [`Placement::shard_key`] at the caixa-core
8591        // site above — extends the "read `:placement` optional-scalars
8592        // through the typed accessor" discipline to the second
8593        // `Option<String>`-shape slot on the M3 mesh-slot family.
8594        //
8595        // Per-hint value-shape gate: the `:affinity` value lands
8596        // verbatim in the M3 Adaptive compression overlay
8597        // (caixa-mesh's `placement.affinity` emission) and every
8598        // future M4 placement-engine routing axis keying off the
8599        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
8600        // selector — each enforces the DNS-1123 label rule on
8601        // admission. Same typed-shape trajectory as `:placement
8602        // :clusters` (6c8c00b) on the sibling slot and the four
8603        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
8604        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
8605        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
8606        // on the Aplicacao surface to land on the canonical
8607        // [`crate::render::is_dns_1123_label`] floor.
8608        if let Some(a) = p.affinity() {
8609            validate_placement_affinity(a)?;
8610        }
8611        match p.estrategia() {
8612            // Route the `Sharded`-arm shape-gate cascade through the
8613            // typed [`Placement::shard_key`] accessor rather than the
8614            // raw `&self.placement.shard_key` field access — one of the
8615            // two open-coded field-access sites on the per-`:placement`
8616            // Akka-cluster-sharding-key axis the accessor lift now
8617            // owns. The `Some(k)`-bound `k` narrows from `&String` to
8618            // `&str` under the accessor's `Option<&str>` return type;
8619            // `str::is_empty` and [`validate_placement_shard_key`]'s
8620            // `&str` parameter both accept the narrower borrow without
8621            // a re-allocation.
8622            PlacementStrategy::Sharded => match p.shard_key() {
8623                None => return Err(AplicacaoError::ShardedWithoutKey),
8624                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
8625                // Per-axis value-shape gate on the Akka-cluster-sharding
8626                // `:shard-key` extractor expression. The shape gate runs
8627                // after the more self-locating `ShardedKeyEmpty` arm so
8628                // a `:shard-key ""` surfaces the narrower empty
8629                // diagnostic first; every non-empty `:shard-key` past
8630                // this call is guaranteed to be a printable-ASCII
8631                // single-token reference the future M4 Akka-style
8632                // cluster-sharding reconciler can hash without
8633                // re-validating at the runtime layer. Mirrors the
8634                // payload-axis shape gates on the peer `:contratos`
8635                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
8636                // 63e18a0 / c4213a4) — each lifts the runtime parser's
8637                // intersection-floor to a caixa-build-time gate.
8638                Some(k) => validate_placement_shard_key(k)?,
8639            },
8640            // `:shard-key` is the Akka-cluster-sharding axis
8641            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
8642            // across the cluster pool. `Replicated` (active-active across
8643            // every named cluster) and `SingleNode` (Erlang/OTP
8644            // distributed-app takeover/failover, §II.1) have no hash-keyed
8645            // routing axis to consume the slot; downstream renderers
8646            // (caixa-mesh's `placement.shardKey` overlay at
8647            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
8648            // sharding reconciler) ignore `:shard-key` outside the
8649            // `Sharded` arm by construction. Until this gate landed an
8650            // author who wrote `:placement (:estrategia Replicated
8651            // :shard-key "tenantId")` (an off-by-one strategy typo, a
8652            // copy-paste from a Sharded sibling caixa, the "I think I
8653            // configured sharding" footgun) silently passed validate and
8654            // the typed slot's value vanished at the renderer layer with
8655            // no diagnostic — the canonical "declared-but-inert" footgun
8656            // the empty-:affinity / empty-shard-key / zero-:politicas /
8657            // empty-:contratos-target gates already close on every other
8658            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
8659            // Lifting the rejection to a build-time gate closes the
8660            // Sharded ↔ non-Sharded partition over the typed
8661            // `:placement` slot: every validated `Placement` past this
8662            // call has `shard_key.is_some()` iff `estrategia ==
8663            // Sharded`, structurally — the future Akka reconciler can
8664            // reach for `placement.shard_key` knowing it's `Some` exactly
8665            // when the strategy consumes it, without re-deriving the
8666            // partition from inline strategy probes.
8667            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
8668                // Route the non-`Sharded`-arm declared-but-inert refusal
8669                // through the typed [`Placement::shard_key`] accessor —
8670                // the second of the two open-coded field-access sites the
8671                // accessor lift now owns. The `Some(k)`-bound `k` narrows
8672                // from `&String` to `&str`; the `AplicacaoError::
8673                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
8674                // materializes the owned `String` via `k.to_string()`
8675                // (peer to the sibling per-Membro `String`-carry sites
8676                // 4127bb6 routed through `m.nome().to_string()` /
8677                // `m.versao_requirement().to_string()`), so the whole
8678                // `Sharded` ↔ non-`Sharded` partition on the
8679                // `:shard-key` axis now flows through the same typed
8680                // dispatch as the sibling `Sharded`-arm shape gate.
8681                if let Some(k) = p.shard_key() {
8682                    return Err(AplicacaoError::shard_key_on_non_sharded(p, k));
8683                }
8684            }
8685        }
8686        Ok(())
8687    }
8688
8689    /// Reject `:politicas` values that are operationally meaningless.
8690    /// Each axis is optional — omitting it expresses "no policy on this
8691    /// axis". Carrying a *zero* value for a declared axis is the bug
8692    /// this function rejects: zero is either
8693    ///
8694    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
8695    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
8696    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
8697    ///     "every Aplicacao declares :politicas :timeout (no infinite
8698    ///     blocking)", or
8699    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
8700    ///     first call; a 0-rate rate-limit denies every request).
8701    ///
8702    /// Lifting these "0 means the opposite of what you think" idioms to
8703    /// the typed Aplicacao surface as build errors mirrors the §III.3
8704    /// promise that contract drift, capability leaks, and cycles are all
8705    /// build errors — not runtime surprises.
8706    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
8707        // Route the whole per-axis + cross-axis `:politicas` cascade
8708        // through the substrate primitive [`MeshPolicy::validate`],
8709        // which folds all six per-axis brackets (`:timeout`,
8710        // `:retries`, `:circuit-breaker :max-failures`,
8711        // `:circuit-breaker :window`, `:rate-limit` rate, `:rate-limit`
8712        // window-canonical-form) plus the compound cross-axis fold
8713        // [`MeshPolicy::first_cross_axis_violation`] into one
8714        // `Result<(), AplicacaoError>` return. The whole per-axis-
8715        // brackets + cross-axis-fold cascade collapses to one call, and
8716        // every future [`MeshPolicy`] consumer (the future M4
8717        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
8718        // admission webhook, the per-`:contratos`-edge `:politicas`
8719        // override MESH-COMPOSITION §III.2 #3 acknowledges — the last
8720        // of which resolves an *effective* per-edge [`MeshPolicy`] and
8721        // must emit *the same* diagnostic on the same input as `feira
8722        // build`) reaches through the same substrate-primitive dispatch
8723        // rather than re-inlining the four-per-axis + one-cross-axis
8724        // cascade in lockstep with this validate gate. Same trajectory
8725        // the peer per-kind compound entry gates
8726        // [`crate::render::require_aplicacao_view`] (7242d45 / 3aefefb),
8727        // [`crate::render::require_supervisor_view`] (8d8a5c3),
8728        // [`crate::render::require_v0_servico_shape`] (per-Caixa
8729        // layout axis) and the sibling compound cross-axis fold
8730        // [`MeshPolicy::first_cross_axis_violation`] (90a6f87) carry —
8731        // extended here onto the per-slot compound entry gate that
8732        // folds both per-axis + cross-axis surfaces on the M3
8733        // mesh-slot family.
8734        self.politicas().validate()
8735    }
8736
8737    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8738    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8739    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8740    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8741    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8742    /// block on its subscribers, so they can never close a sync loop.
8743    ///
8744    /// Iterative DFS with three-coloring; the reported cycle is the
8745    /// path of caixa names traversed from the back-edge target around
8746    /// to itself, in declaration order. Adjacency lists and DFS roots
8747    /// are visited in `BTreeMap` key order so the diagnostic is
8748    /// deterministic across runs.
8749    ///
8750    /// Now the cross-edge axis of the per-slot compound gate
8751    /// [`AplicacaoSpec::validate_contratos`] — invoked at the tail of
8752    /// the per-entry cascade rather than at the outer
8753    /// [`AplicacaoSpec::validate`] dispatch, so both structural axes on
8754    /// `:contratos` (per-entry shape + membership + dedup; cross-edge
8755    /// sync-cycle) reach every consumer through one call. Kept
8756    /// standalone (rather than inlined) so consumers that want only the
8757    /// cross-edge axis (the M4 per-edge policy resolver
8758    /// MESH-COMPOSITION §III.2 #3 acknowledges, whose per-edge patch
8759    /// mutates one `:contratos` entry and needs to re-probe *just* the
8760    /// cycle invariant against the post-patch adjacency without
8761    /// re-running the per-entry shape/membership/dedup cascade the
8762    /// per-entry-only [M4 admission] fast path already covered) still
8763    /// have a self-contained entry point on the cycle axis.
8764    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8765        use std::collections::{BTreeMap, BTreeSet};
8766
8767        #[derive(Clone, Copy, PartialEq, Eq)]
8768        enum Mark {
8769            White,
8770            Gray,
8771            Black,
8772        }
8773
8774        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8775        for m in self.membros() {
8776            adj.entry(m.nome()).or_default();
8777        }
8778        for c in self.contratos() {
8779            // target() was already called by validate(); re-running here
8780            // keeps detect_sync_cycles self-contained for callers that
8781            // reuse it (M4 per-edge policy resolver) without revalidating.
8782            //
8783            // The pub-sub-arm check routes through the lifted
8784            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8785            // arm-discriminator predicate rather than a raw `matches!(…,
8786            // WitTarget::PubSub { .. })` on the variant so a future
8787            // rebrand on the axis (an M4 per-edge WIT registry split of
8788            // [`WitTarget::PubSub`] into shape-specific peers, a
8789            // per-consumer rename that the accept-set already carries)
8790            // reaches this call site through the derive rather than a
8791            // scattered per-arm `matches!` rewrite — same
8792            // `IsVariant`-derived-arm-discriminator discipline the
8793            // peer closed-set typed enums ([`crate::CaixaKind`] via
8794            // f5bba80, [`PlacementStrategy`] via 766ec63,
8795            // [`crate::supervisor::RestartStrategy`] +
8796            // [`crate::supervisor::RestartPolicy`],
8797            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8798            // already route through on the substrate's other typed-enum
8799            // arm-discriminator axes.
8800            if c.target()?.is_pubsub() {
8801                continue;
8802            }
8803            adj.entry(c.source()).or_default().insert(c.destination());
8804        }
8805
8806        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8807        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8808
8809        // Stable DFS root order — BTreeMap iteration is sorted by key.
8810        let roots: Vec<&str> = adj.keys().copied().collect();
8811
8812        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8813        for root in roots {
8814            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8815                continue;
8816            }
8817            let root_neighbors: Vec<&str> = adj
8818                .get(root)
8819                .map(|s| s.iter().copied().collect())
8820                .unwrap_or_default();
8821            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8822            color.insert(root, Mark::Gray);
8823
8824            loop {
8825                // Read+advance the top frame in one borrow scope so we
8826                // can later mutate the stack (push/pop) without holding
8827                // a borrow across.
8828                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8829                    let node = top.0;
8830                    if top.2 >= top.1.len() {
8831                        (node, None)
8832                    } else {
8833                        let nxt = top.1[top.2];
8834                        top.2 += 1;
8835                        (node, Some(nxt))
8836                    }
8837                });
8838                let Some((node, nxt_opt)) = step else { break };
8839                let Some(nxt) = nxt_opt else {
8840                    color.insert(node, Mark::Black);
8841                    stack.pop();
8842                    continue;
8843                };
8844                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8845                match nxt_color {
8846                    Mark::Gray => {
8847                        // Reconstruct the cycle from `node` back through
8848                        // the parent chain to `nxt`, then close.
8849                        let mut cycle = Vec::new();
8850                        let mut cur = node;
8851                        cycle.push(cur.to_string());
8852                        while cur != nxt {
8853                            match parent.get(cur).copied() {
8854                                Some(p) => {
8855                                    cur = p;
8856                                    cycle.push(cur.to_string());
8857                                }
8858                                None => break,
8859                            }
8860                        }
8861                        cycle.reverse();
8862                        cycle.push(nxt.to_string());
8863                        return Err(AplicacaoError::contrato_cycle(cycle));
8864                    }
8865                    Mark::White => {
8866                        parent.insert(nxt, node);
8867                        color.insert(nxt, Mark::Gray);
8868                        let nxt_neighbors: Vec<&str> = adj
8869                            .get(nxt)
8870                            .map(|s| s.iter().copied().collect())
8871                            .unwrap_or_default();
8872                        stack.push((nxt, nxt_neighbors, 0));
8873                    }
8874                    Mark::Black => {}
8875                }
8876            }
8877        }
8878        Ok(())
8879    }
8880
8881    /// Substrate-canonical destination-facing TCP port every emitted
8882    /// per-Aplicacao artifact must key `destination`-shaped port axes
8883    /// off. Returns the typed `:entrada :port` scalar when this
8884    /// Aplicacao's `:entrada` block names `destination` under its
8885    /// `:para` axis (the destination Servico *is* the ingress apex, so
8886    /// the substrate honors the author-declared listener port
8887    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8888    /// fallback otherwise (every non-apex destination — the internal
8889    /// mesh Servicos `:contratos` reach across, the future per-edge
8890    /// policy resolver's per-destination probe targets, the
8891    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8892    /// L4 port resolver — reads the same substrate-canonical port floor
8893    /// by construction).
8894    ///
8895    /// Prior to this lift the "if :entrada matches this destination use
8896    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8897    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8898    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8899    /// prior to this lift), with no typed method on the substrate primitive
8900    /// that named the rule. A future per-destination port axis addition
8901    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8902    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8903    /// per-Servico listener ports land, a per-cluster override the operator
8904    /// pins through a future `:placement :default-port` slot — would have
8905    /// to be threaded through every renderer's inline cascade in lockstep
8906    /// or one consumer would silently disagree on which port a given
8907    /// destination Servico's ingress lands at. Lifting the rule to a
8908    /// typed method on the substrate primitive means the M4 CR
8909    /// materializer, the future per-edge policy resolver, and every
8910    /// downstream test-fixture navigator reach for exactly one typed
8911    /// dispatch — the resolver's accept-set moves as a unit on any
8912    /// future axis addition.
8913    ///
8914    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8915    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8916    /// the typed primitive, thin projections at each consumer"
8917    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8918    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8919    /// destination-facing port-resolution axis every per-Aplicacao
8920    /// L4-fallback renderer consumes.
8921    #[must_use]
8922    pub fn port_for_destination(&self, destination: &str) -> u16 {
8923        // Route the per-`:entrada` composite-reference read through
8924        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8925        // the raw `self.entrada.as_ref()` field access — the
8926        // per-destination L4-port fallback resolver's composite-
8927        // projection seed is now the canonical read-side surface
8928        // every per-Aplicacao entrada consumer routes through, peer
8929        // of the sibling `validate` per-`:entrada` shape-and-
8930        // membership gate migration on the same outer-composite
8931        // axis.
8932        // Route the per-`:entrada` apex-destination membership probe
8933        // through the lifted [`Entrada::destination`] accessor rather
8934        // than the raw `e.para == destination` field access — the last
8935        // un-lifted `.para` production-code read site on the per-
8936        // `:entrada` `:para` axis, sibling to the four caixa-core
8937        // consumer sites the peer 15ddd8c converge already routed
8938        // through the accessor (the three
8939        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8940        // membership gate sites: the `validate_entrada_para` DNS-1123
8941        // shape gate, the per-`:membros` membership lookup, and the
8942        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8943        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8944        // `entrada.para`-projection converge at
8945        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8946        // route-name projection site). Prior to this converge the
8947        // `port_for_destination` resolver was the solitary consumer
8948        // bypassing the typed dispatch on the `.para` axis — the two
8949        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8950        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8951        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8952        // reach through the same accessor family compose with this
8953        // resolver at the emit boundary via the apex-identity
8954        // invariant `spec.port_for_destination(entrada.destination())
8955        // == entrada.port` the sibling
8956        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8957        // pin pins across four permutations. A future extension of the
8958        // `:entrada :para` axis to a richer author surface (a per-
8959        // cluster alias overlay the operator pins through a future
8960        // `:placement`-scoped slot, a namespace-qualified rewrite the
8961        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8962        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8963        // §III.2 acknowledges) that lands on the accessor would silently
8964        // disagree between this resolver and the two `caixa-mesh` emit
8965        // sites — an author-declared `:para "cart"` value the accessor
8966        // rewrote to `"cart-v2"` under a future canary arm would leave
8967        // the resolver's membership arm falling through to
8968        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8969        // `.para`) while the peer emit-site consumers landed on the
8970        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8971        // silently disagreed on which destination port a given typed
8972        // `:entrada` resolves to at cluster-apply time. Pinned by the
8973        // drift-detection test
8974        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8975        // below.
8976        self.entrada()
8977            .filter(|e| e.destination() == destination)
8978            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8979    }
8980}
8981
8982/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8983/// entry may name the Aplicacao's own `:nome`.
8984///
8985/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8986/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8987/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8988/// Servicos that compose the app; an Aplicacao is never its own constituent),
8989/// and the lacre pipeline's closure-resolution would otherwise be handed a
8990/// node that is its own parent: a one-node cycle it either rejects far from
8991/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8992/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8993/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8994/// label + lacre closure root), a member whose `:caixa` equals the
8995/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8996/// peer.
8997///
8998/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8999/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
9000/// gate `validate_upgrade_from_against_versao` and the supervision-tree
9001/// self-parent gate `crate::supervisor::validate_no_self_supervision`
9002/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
9003/// not a tree/mesh edge" discipline, here on the second typed-graph axis
9004/// (the Aplicacao :membros set; the supervision-tree :children list was the
9005/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
9006/// every validated Supervisor's children are distinct from its `:nome`,
9007/// every validated Aplicacao's membros are distinct from its `:nome`. The
9008/// transitive consequence is that `:entrada :para` and `:contratos`
9009/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
9010/// name the Aplicacao itself, without re-deriving the partition.
9011pub fn validate_no_self_membership(
9012    membros: &[Membro],
9013    parent_nome: &str,
9014) -> Result<(), AplicacaoError> {
9015    for m in membros {
9016        if m.nome() == parent_nome {
9017            return Err(AplicacaoError::membro_is_self_aplicacao(parent_nome));
9018        }
9019    }
9020    Ok(())
9021}
9022
9023#[derive(Debug, Error, PartialEq, Eq)]
9024pub enum AplicacaoError {
9025    #[error("Aplicacao must declare at least one :membros entry")]
9026    NoMembros,
9027    #[error(
9028        ":membros entry has empty :caixa (every member must name a Servico; \
9029         omit the entry instead of carrying an empty name)"
9030    )]
9031    MembroCaixaEmpty,
9032    #[error(
9033        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
9034         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
9035         name / label value the member name lands in; use a lowercase \
9036         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
9037    )]
9038    MembroCaixaInvalid { caixa: String, reason: String },
9039    #[error(
9040        ":membros entry {caixa:?} has empty :versao (every member must pin a \
9041         semver constraint that resolves through the lacre pipeline)"
9042    )]
9043    MembroVersaoEmpty { caixa: String },
9044    #[error(
9045        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
9046         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
9047         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
9048         carries; the lacre pipeline resolves both through the same parser)"
9049    )]
9050    MembroVersaoInvalid {
9051        caixa: String,
9052        versao: String,
9053        reason: String,
9054    },
9055    #[error(
9056        ":membros entry {caixa:?} appears more than once (the graph node set \
9057         is a set, not a multiset; duplicate members produce duplicate \
9058         programs.yaml entries and ambiguous :contratos membership lookups)"
9059    )]
9060    MembroDuplicate { caixa: String },
9061    #[error(
9062        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
9063         never its own constituent Servico (the application graph is a DAG rooted \
9064         at the Aplicacao; :membros names the *other* caixas that compose the \
9065         app, not the app itself). Since every :nome is a globally-unique \
9066         substrate identity, a member naming the Aplicacao's own :nome is a \
9067         one-node lacre-closure recursion, not a coincidentally-named peer; \
9068         drop the self-referential :membros entry or rename it to the actual \
9069         constituent caixa."
9070    )]
9071    MembroIsSelfAplicacao { caixa: String },
9072    #[error(
9073        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
9074         caixa declared in :membros; omit the contract or fill the {slot} field with a \
9075         member name)"
9076    )]
9077    ContratoCaixaEmpty { slot: &'static str },
9078    #[error(
9079        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
9080         :contratos {slot} value names a member of :membros, which is itself a \
9081         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
9082         object the member name lands in — Service, Pod, identity-based Cilium \
9083         selector; use a lowercase alphanumeric + hyphen identifier like \
9084         `\"checkout\"` or `\"cart-v2\"`)"
9085    )]
9086    ContratoCaixaInvalid {
9087        slot: &'static str,
9088        caixa: String,
9089        reason: String,
9090    },
9091    #[error("contrato references caixa {caixa:?} not declared in :membros")]
9092    ContratoMemberMissing { caixa: String },
9093    #[error(
9094        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
9095         entry is an inter-Servico contract whose :de and :para must name distinct \
9096         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
9097         the contract, or point :para at the member it actually calls)"
9098    )]
9099    ContratoSelfLoop { caixa: String, wit: String },
9100    #[error("contrato {de:?} → {para:?} has empty :wit")]
9101    EmptyWit { de: String, para: String },
9102    #[error(
9103        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
9104         {reason} (the substrate dispatches `:wit` values on the canonical \
9105         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
9106         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
9107         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
9108         kebab-case identifier per segment)"
9109    )]
9110    ContratoWitInvalid {
9111        de: String,
9112        para: String,
9113        wit: String,
9114        reason: String,
9115    },
9116    #[error(
9117        ":entrada :para is empty (every :entrada must route to a caixa declared in \
9118         :membros; fill the :para field with a member name)"
9119    )]
9120    EntradaParaEmpty,
9121    #[error(
9122        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
9123         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
9124         label per the K8s apiserver's `metadata.name` rule on every object the \
9125         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
9126         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
9127         `\"checkout\"` or `\"cart-v2\"`)"
9128    )]
9129    EntradaParaInvalid { para: String, reason: String },
9130    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
9131    EntradaMemberMissing { para: String },
9132    #[error(":entrada must declare a non-empty :host")]
9133    EmptyEntradaHost,
9134    #[error(
9135        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
9136         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
9137         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
9138         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
9139    )]
9140    EntradaHostInvalid { host: String, reason: String },
9141    #[error(":entrada :port must be in 1..=65535, got 0")]
9142    EntradaPortZero,
9143    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
9144    EntradaPathEmpty,
9145    #[error(
9146        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
9147    )]
9148    EntradaPathNotAbsolute { path: String },
9149    #[error(
9150        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
9151         value: {reason} (the K8s apiserver enforces the same shape on \
9152         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
9153         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
9154         requires percent-encoding `%XX` for non-ASCII and whitespace)"
9155    )]
9156    EntradaPathInvalid { path: String, reason: String },
9157    #[error(":entrada :paths entry {path:?} appears more than once")]
9158    EntradaPathDuplicate { path: String },
9159    #[error(
9160        ":placement {estrategia} requires at least one :clusters entry \
9161         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
9162    )]
9163    PlacementWithoutClusters { estrategia: PlacementStrategy },
9164    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
9165    PlacementClusterEmpty,
9166    #[error(
9167        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
9168         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
9169         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
9170         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
9171         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
9172         identifier like `\"rio\"` or `\"mar-east\"`)"
9173    )]
9174    PlacementClusterInvalid { cluster: String, reason: String },
9175    #[error(":placement :clusters entry {cluster:?} appears more than once")]
9176    PlacementClusterDuplicate { cluster: String },
9177    #[error(
9178        ":placement :affinity must be non-empty when set (omit :affinity to express \
9179         `no placement hint`)"
9180    )]
9181    PlacementAffinityEmpty,
9182    #[error(
9183        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
9184         (placement hints land verbatim in the M3 Adaptive compression overlay's \
9185         `placement.affinity` field and in every future M4 placement-engine routing \
9186         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
9187         selector — both enforce the DNS-1123 label rule on admission; use a \
9188         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
9189         `\"low-latency\"`, or `\"anti-affinity\"`)"
9190    )]
9191    PlacementAffinityInvalid { affinity: String, reason: String },
9192    #[error(":placement Sharded requires :shard-key")]
9193    ShardedWithoutKey,
9194    #[error(
9195        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
9196         hashes every entity onto the same shard, defeating sharding entirely)"
9197    )]
9198    ShardedKeyEmpty,
9199    #[error(
9200        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
9201         entity-id extractor expression: {reason} (the future M4 Akka-style \
9202         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
9203         as a single-token property reference and hashes the extracted entity ID \
9204         to compute shard placement; use a printable-ASCII extractor expression \
9205         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
9206         `\"${{tenant}}\"`)"
9207    )]
9208    ShardKeyInvalid { shard_key: String, reason: String },
9209    #[error(
9210        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
9211         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
9212         convention); :estrategia Replicated runs every cluster active-active and \
9213         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
9214         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
9215         to :estrategia Sharded if hash-keyed routing is the intent"
9216    )]
9217    ShardKeyOnNonSharded {
9218        estrategia: PlacementStrategy,
9219        shard_key: String,
9220    },
9221    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
9222    ContratoMissingTarget {
9223        de: String,
9224        para: String,
9225        wit: String,
9226        expected: &'static str,
9227    },
9228    #[error(
9229        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
9230         expected `:{expected}` only"
9231    )]
9232    ContratoWrongTarget {
9233        de: String,
9234        para: String,
9235        wit: String,
9236        expected: &'static str,
9237    },
9238    #[error(
9239        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
9240         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
9241         that matches no traffic and silently drops every request)"
9242    )]
9243    ContratoEndpointEmpty { de: String, para: String },
9244    #[error(
9245        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
9246         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
9247         :entrada :paths)"
9248    )]
9249    ContratoEndpointNotAbsolute {
9250        de: String,
9251        para: String,
9252        endpoint: String,
9253    },
9254    #[error(
9255        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
9256         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
9257         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
9258         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
9259         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
9260         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
9261         and whitespace)"
9262    )]
9263    ContratoEndpointInvalid {
9264        de: String,
9265        para: String,
9266        endpoint: String,
9267        reason: String,
9268    },
9269    #[error(
9270        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
9271         subject is a no-op subscribe; omit :subject only if the WIT world is not \
9272         pub-sub-shaped)"
9273    )]
9274    ContratoSubjectEmpty { de: String, para: String },
9275    #[error(
9276        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
9277         NATS subject: {reason} (the NATS server's subject parser enforces the \
9278         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
9279         single-token and `>` multi-token wildcards — at publish/subscribe time; \
9280         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
9281         `\"orders.*.completed\"` — a malformed subject silently drops every \
9282         message at runtime far from the source caixa.lisp)"
9283    )]
9284    ContratoSubjectInvalid {
9285        de: String,
9286        para: String,
9287        subject: String,
9288        reason: String,
9289    },
9290    #[error(
9291        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
9292         addresses the bucket root, defeating the per-key isolation the slot exists \
9293         for; omit :slot only if the WIT world is not store-shaped)"
9294    )]
9295    ContratoSlotEmpty { de: String, para: String },
9296    #[error(
9297        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
9298         WASI keyvalue store slot template: {reason} (the substrate enforces \
9299         the printable-ASCII intersection-floor every kv backend admits — \
9300         use a single-token path / template expression like `\"checkout/$orderId\"`, \
9301         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
9302         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
9303         slot either gets rejected on write by strict backends or silently \
9304         corrupts the next read on permissive ones, far from the source caixa.lisp)"
9305    )]
9306    ContratoSlotInvalid {
9307        de: String,
9308        para: String,
9309        slot: String,
9310        reason: String,
9311    },
9312    #[error(
9313        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
9314         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
9315        cycle.join(" → ")
9316    )]
9317    ContratoCycle { cycle: Vec<String> },
9318    #[error(
9319        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
9320         than once (the typed graph edges are a set, not a multiset; duplicate \
9321         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
9322         values that K8s admission rejects far from the source caixa.lisp)"
9323    )]
9324    ContratoDuplicate {
9325        de: String,
9326        para: String,
9327        wit: String,
9328        target: String,
9329    },
9330    #[error(
9331        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
9332         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
9333         express `no per-call deadline on this axis`"
9334    )]
9335    PolicyTimeoutZero,
9336    #[error(
9337        ":politicas :retries must be > 0 when set; omit :retries to express \
9338         `no retries on transient failure`"
9339    )]
9340    PolicyRetriesZero,
9341    #[error(
9342        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
9343         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
9344         retry policy into a thundering-herd amplification vector on transient \
9345         failure (one caller request fans out to `(retries+1)^depth` server-side \
9346         calls across the synchronous-:contratos subgraph), exactly the failure \
9347         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
9348         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
9349         or omit :retries to disable retries entirely"
9350    )]
9351    PolicyRetriesExceedsCap { retries: u32 },
9352    #[error(
9353        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
9354         breaker trips on the first call); omit :circuit-breaker to disable it"
9355    )]
9356    PolicyBreakerZeroFailures,
9357    #[error(
9358        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
9359         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
9360         above this cap turns the typed breaker policy into a no-op: the trip \
9361         threshold is structurally so high that no realistic failures-per-:window \
9362         traffic shape can reach it, so the breaker never trips and every typed-slot \
9363         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
9364         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
9365         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
9366         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
9367         omit :circuit-breaker to disable the breaker entirely"
9368    )]
9369    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
9370    #[error(
9371        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
9372         tracks no failures); omit :circuit-breaker to disable it"
9373    )]
9374    PolicyBreakerZeroWindow,
9375    #[error(
9376        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
9377         request); omit :rate-limit to disable rate limiting"
9378    )]
9379    PolicyRateLimitZero,
9380    #[error(
9381        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
9382         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
9383         rate-limit policy into a no-op limiter: the token-bucket capacity is \
9384         structurally so high that no realistic per-edge traffic shape can drain it, \
9385         so the limiter never trips and every typed-slot consumer (the future \
9386         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9387         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
9388         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
9389         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
9390         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
9391         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
9392         to disable rate limiting entirely"
9393    )]
9394    PolicyRateLimitExceedsCap { rate: u32 },
9395    #[error(
9396        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
9397         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
9398         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
9399         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
9400         three canonical windows)"
9401    )]
9402    PolicyRateLimitWindowNotCanonical { window: Duration },
9403    #[error(
9404        ":politicas :timeout must be an integer number of milliseconds — the canonical \
9405         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
9406         duration codec round-trips losslessly; got {timeout:?} which carries a \
9407         sub-millisecond residue that either truncates to a different `Duration` on \
9408         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
9409         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
9410         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
9411         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
9412    )]
9413    PolicyTimeoutNotCanonical { timeout: Duration },
9414    #[error(
9415        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
9416         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
9417         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
9418         overlays carry a deadline so long no realistic synchronous-:contratos \
9419         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
9420         CSE invariant degenerates to enforcement only at the per-Servico \
9421         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
9422         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
9423         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
9424         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
9425         maxes out at the same `3600s` ceiling) or omit :timeout to express \
9426         `no per-call deadline on this axis` (the synchronous-call deadline then \
9427         relies entirely on the per-Servico `:limits :wall-clock` axis)"
9428    )]
9429    PolicyTimeoutExceedsCap { timeout: Duration },
9430    #[error(
9431        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
9432         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
9433         the shared duration codec round-trips losslessly; got {window:?} which carries a \
9434         sub-millisecond residue that either truncates to a different `Duration` on \
9435         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
9436         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
9437    )]
9438    PolicyBreakerWindowNotCanonical { window: Duration },
9439    #[error(
9440        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
9441         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
9442         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
9443         is structurally so long that transient failures are never forgotten, the breaker \
9444         trips once and stays tripped for the lifetime of the component, and every typed-slot \
9445         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9446         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
9447         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
9448         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
9449         the breaker entirely"
9450    )]
9451    PolicyBreakerWindowExceedsCap { window: Duration },
9452    #[error(
9453        ":politicas :circuit-breaker :window ({window:?}) is shorter than :politicas \
9454         :timeout ({timeout:?}) — the rolling failure-observation interval closes before \
9455         a single timing-out call can be declared failed, so the dominant failure mode \
9456         the breaker exists to catch is structurally never counted: a call dispatched at \
9457         t=0 is only reported failed at t={timeout:?}, by which point the window that was \
9458         open at dispatch has already rolled, and every typed-slot consumer (the future \
9459         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9460         outlier_detection.interval paired against the per-route request timeout) emits a \
9461         breaker that cannot trip on timeouts however high the call volume. Pin :window \
9462         at or above :timeout (Hystrix defaults 10s rolling window against a 1s execution \
9463         timeout — a 10× ratio; Envoy / resilience4j production playbooks recommend the \
9464         same shape), lower :timeout, or omit one of the two axes"
9465    )]
9466    PolicyBreakerWindowBelowTimeout { window: Duration, timeout: Duration },
9467    #[error(
9468        ":politicas :rate-limit ({rate} per {rl_window:?}) starves :politicas \
9469         :circuit-breaker so :max-failures ({max_failures}) cannot be reached inside \
9470         :window ({cb_window:?}) — the token-bucket dispatches at most \
9471         `rate × cb_window / rl_window` calls per rolling breaker window, which is \
9472         structurally below the trip threshold, so the breaker cannot trip even under \
9473         100% failure and every typed-slot consumer (the future \
9474         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
9475         outlier_detection.consecutive_5xx paired against \
9476         local_rate_limit.token_bucket.max_tokens) emits a protection that is \
9477         structurally never enforced. Raise :rate, shorten :rate-limit :window, lower \
9478         :max-failures, lengthen :circuit-breaker :window, or omit one of the two axes"
9479    )]
9480    PolicyBreakerCannotTripUnderRateLimit {
9481        rate: u32,
9482        rl_window: Duration,
9483        max_failures: u32,
9484        cb_window: Duration,
9485    },
9486    #[error(
9487        ":politicas :retries ({retries}) plus the initial attempt saturates :politicas \
9488         :circuit-breaker :max-failures ({max_failures}) mid-retry — one client's failing \
9489         attempts alone accumulate {retries}+1 failures, which reaches the trip threshold \
9490         at or before the last retry, so the breaker opens with declared retries still \
9491         unused and every typed-slot consumer (the future CiliumClusterwideEnvoyConfig \
9492         per-:politicas overlay, Envoy's retry_policy.num_retries paired against \
9493         outlier_detection.consecutive_5xx) emits a retry policy the substrate \
9494         structurally truncates. Pin :max-failures strictly above :retries (Hystrix / \
9495         Envoy / resilience4j production playbooks recommend the breaker's trip \
9496         threshold be observably larger than any single client's retry budget so the \
9497         breaker distinguishes one persistently-failing client from sustained \
9498         multi-client failure), lower :retries, or omit one of the two axes"
9499    )]
9500    PolicyBreakerTripsBeforeRetriesExhausted { retries: u32, max_failures: u32 },
9501    #[error(
9502        ":politicas :rate-limit ({rate} per window) cannot admit :politicas :retries \
9503         ({retries}) plus the initial attempt — one client's declared retry sequence is \
9504         {retries}+1 attempts, each of which consumes one token from the local rate-limit \
9505         bucket, but the bucket admits at most {rate} tokens per refill window, so the \
9506         retry policy is silently truncated by the same rate limiter it feeds through and \
9507         every typed-slot consumer (the future CiliumClusterwideEnvoyConfig per-:politicas \
9508         overlay, Envoy's retry_policy.num_retries paired against \
9509         local_rate_limit.token_bucket.max_tokens) emits a retry policy the substrate \
9510         structurally throttles. Raise :rate strictly above :retries (Envoy / Istio / \
9511         resilience4j / AWS App Mesh production playbooks recommend the local rate-limit \
9512         bucket capacity be observably larger than any single client's retry budget so the \
9513         limiter distinguishes one client's declared retries from sustained multi-client \
9514         load), lower :retries, or omit one of the two axes"
9515    )]
9516    PolicyRateLimitCannotAdmitRetryBurst { retries: u32, rate: u32 },
9517}
9518
9519// The `AplicacaoError::EntradaHostInvalid { host, reason }` variant's
9520// ctor `entrada_host_invalid` is folded onto the sibling
9521// [`aplicacao_field_reason_ctors!`] macro below alongside the six peer
9522// `{ <field>: String, reason: String }` variants
9523// (`MembroCaixaInvalid` / `EntradaParaInvalid` / `EntradaPathInvalid` /
9524// `PlacementClusterInvalid` / `PlacementAffinityInvalid` /
9525// `ShardKeyInvalid`), so every variant on the uniform two-slot
9526// `{ <field>: String, reason: String }` envelope on [`AplicacaoError`]
9527// reads through one substrate-primitive family rather than one macro
9528// closing six sites plus a hand-written seventh ctor closing the
9529// paired site alone. Prior separate-ctor rationale (17dd504) migrates
9530// verbatim to the macro's outer doc block.
9531
9532// Fold the seven `AplicacaoError::Contrato{Wrong,Missing}Target { de, para,
9533// wit, expected }` wire-up sites at [`WitContract::target`] onto one
9534// substrate-primitive family per typed variant — the paired sibling on
9535// [`AplicacaoError`] of the four `LayoutError` constructor families
9536// [`layout_violation_ctors!`] (131ca0d, 16 variants on `{ caixa, issue }`),
9537// [`layout_slot_kind_ctors!`] (0419438, 4 variants on
9538// `{ caixa, kind, slots }`), [`LayoutError::missing_entry`] (1b09f9d,
9539// 1 variant on `{ kind, path }`), and [`layout_nome_only_ctors!`] (3fe3dd7,
9540// 6 variants on `<Variant>(String)`) each carry on the sibling layout-side
9541// envelope. Every one of the seven wire-up sites in [`WitContract::target`]
9542// (four `ContratoWrongTarget` arms on the payload-field-mismatch axis —
9543// HTTP with subject/slot, PubSub with endpoint/slot, Store with
9544// endpoint/subject, Capability with any payload; three
9545// `ContratoMissingTarget` arms on the payload-field-absent axis — HTTP
9546// without `:endpoint`, PubSub without `:subject`, Store without `:slot`)
9547// opened the identical six-line
9548// `AplicacaoError::Contrato<Wrong|Missing>Target { de, para, wit, expected:
9549// WitTarget::<label> }` struct-literal against the local `edge()` closure
9550// returning `(de, para, wit) = self.edge_triple()` — the exact "same block
9551// re-inlined at every consumer" shape the PRIME DIRECTIVE names as a bug,
9552// on the same altitude the peer four `LayoutError` constructor families
9553// each closed on their sibling envelopes.
9554//
9555// The macro below generates one `#[must_use]` inherent constructor per
9556// variant of shape `fn <ctor>(edge: (String, String, String), expected:
9557// &'static str) -> AplicacaoError`, collapsing the seven sites onto one
9558// dispatch per arm: `return
9559// Err(AplicacaoError::contrato_wrong_target(edge(), <label>));` / `.ok_or_else(||
9560// AplicacaoError::contrato_missing_target(edge(), <label>))?`, byte-equal to
9561// the pre-lift struct-literal on the same edge fixture. The uniform four-
9562// field construction (`de, para, wit` triple-destructure onto same-named
9563// fields + `expected` verbatim) is spelled once — inside the macro —
9564// rather than at every wire-up site. `#[must_use]` fires a compile warning
9565// at any wire-up that mistakenly discards the constructed error.
9566//
9567// Every future consumer that wants to construct one of these two variants
9568// outside [`WitContract::target`] (a deferred
9569// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9570// admission validator raising wrong-target / missing-target diagnostics
9571// on unrecognized shapes, a future `feira validate --contratos` per-caixa
9572// admission verb, a per-`WitContract` payload-axis pre-emitter probing
9573// the [`WitTarget`] arm against the declared `:endpoint`/`:subject`/`:slot`
9574// slots) reaches the variant through one call rather than re-inlining the
9575// six-line struct-literal block in lockstep with the seven in-crate
9576// wire-up sites.
9577macro_rules! contrato_target_ctors {
9578    ($($ctor:ident => $variant:ident),* $(,)?) => {
9579        impl AplicacaoError {
9580            $(
9581                #[doc = concat!(
9582                    "Construct an [`AplicacaoError::",
9583                    stringify!($variant),
9584                    "`] naming the offending edge `(de, para, wit)` triple ",
9585                    "under the given `expected` payload-field-name label. ",
9586                    "Folds the uniform `{ de, para, wit, expected }` four-",
9587                    "slot struct-literal onto one substrate primitive so ",
9588                    "every [`WitContract::target`] wire-up on this variant ",
9589                    "reads through one dispatch rather than the pre-lift ",
9590                    "six-line open-coded block. The `edge` triple threads ",
9591                    "verbatim from [`WitContract::edge_triple`] via the ",
9592                    "local `edge()` closure at the call site."
9593                )]
9594                #[must_use]
9595                pub fn $ctor(edge: (String, String, String), expected: &'static str) -> Self {
9596                    let (de, para, wit) = edge;
9597                    Self::$variant { de, para, wit, expected }
9598                }
9599            )*
9600        }
9601    };
9602}
9603
9604contrato_target_ctors! {
9605    contrato_wrong_target => ContratoWrongTarget,
9606    contrato_missing_target => ContratoMissingTarget,
9607}
9608
9609// Fold the four `AplicacaoError::{EmptyWit, ContratoEndpointEmpty,
9610// ContratoSubjectEmpty, ContratoSlotEmpty} { de, para }` wire-up sites
9611// onto one substrate-primitive family per typed variant — the paired
9612// `{ de: String, para: String }` two-slot sibling on [`AplicacaoError`]
9613// of the peer four-slot [`contrato_target_ctors!`] (14b81d5,
9614// `{ de, para, wit, expected }` on `ContratoWrongTarget` /
9615// `ContratoMissingTarget`) and of the two-slot
9616// [`AplicacaoError::entrada_host_invalid`] (17dd504, `{ host, reason }`)
9617// on the sibling per-`:entrada :host` envelope. Every one of the four
9618// wire-up sites — three under [`WitContract::target`] (the empty
9619// [`WitTarget::Http`] `:endpoint`, empty [`WitTarget::PubSub`]
9620// `:subject`, empty [`WitTarget::Store`] `:slot`) and one under
9621// [`AplicacaoSpec::validate`] (the empty `:contratos :wit` field the
9622// value-shape gate fires ahead of) — opened the identical two-line
9623// `let (de, para) = <contract>.edge_pair(); return Err(
9624// AplicacaoError::<Variant> { de, para });` block against the local
9625// [`WitContract::edge_pair`] composite-projection accessor, the exact
9626// "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
9627// names as a bug, on the same altitude the peer [`contrato_target_ctors!`]
9628// and [`AplicacaoError::entrada_host_invalid`] each closed on their
9629// sibling envelopes.
9630//
9631// The macro below generates one `#[must_use]` inherent constructor per
9632// variant of shape `fn <ctor>(edge: (String, String)) -> AplicacaoError`,
9633// collapsing the four sites onto one dispatch per arm:
9634// `return Err(AplicacaoError::<ctor>(<contract>.edge_pair()));`, byte-
9635// equal to the pre-lift struct-literal on the same edge pair. The
9636// uniform two-field construction (`de, para` pair-destructure onto
9637// same-named fields) is spelled once — inside the macro — rather than
9638// at every wire-up site. `#[must_use]` fires a compile warning at any
9639// wire-up that mistakenly discards the constructed error.
9640//
9641// Every future consumer that wants to construct one of these four
9642// variants outside the two in-crate wire-up sites (a deferred
9643// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
9644// admission validator raising empty-payload / empty-`:wit` diagnostics,
9645// a future `feira validate --contratos` per-caixa admission verb, an
9646// M4 typed WIT-registry-driven per-arm pre-emitter probing the
9647// [`WitContract`] payload slot against a canonical per-arm requirement
9648// table) reaches the variant through one call rather than re-inlining
9649// the two-line pair-destructure block in lockstep with the four
9650// in-crate wire-up sites.
9651macro_rules! contrato_empty_pair_ctors {
9652    ($($ctor:ident => $variant:ident),* $(,)?) => {
9653        impl AplicacaoError {
9654            $(
9655                #[doc = concat!(
9656                    "Construct an [`AplicacaoError::",
9657                    stringify!($variant),
9658                    "`] naming the offending edge `(de, para)` pair. ",
9659                    "Folds the uniform `{ de, para }` two-slot struct-",
9660                    "literal onto one substrate primitive so every ",
9661                    "wire-up on this variant reads through one dispatch ",
9662                    "rather than the pre-lift two-line open-coded ",
9663                    "`let (de, para) = <contract>.edge_pair(); return ",
9664                    "Err(<Variant> { de, para });` block. The `edge` ",
9665                    "pair threads verbatim from [`WitContract::edge_pair`] ",
9666                    "at the call site."
9667                )]
9668                #[must_use]
9669                pub fn $ctor(edge: (String, String)) -> Self {
9670                    let (de, para) = edge;
9671                    Self::$variant { de, para }
9672                }
9673            )*
9674        }
9675    };
9676}
9677
9678contrato_empty_pair_ctors! {
9679    empty_wit => EmptyWit,
9680    contrato_endpoint_empty => ContratoEndpointEmpty,
9681    contrato_subject_empty => ContratoSubjectEmpty,
9682    contrato_slot_empty => ContratoSlotEmpty,
9683}
9684
9685// Fold the last open-coded `AplicacaoError::ContratoEndpointNotAbsolute
9686// { de, para, endpoint: <val>.to_string() }` three-slot struct-literal
9687// wire-up site at [`WitContract::target`]'s HTTP-arm leading-slash gate
9688// onto one substrate primitive on [`AplicacaoError`] — sibling on the
9689// `{ de: String, para: String, <field>: String }` three-slot envelope of
9690// the peer [`contrato_empty_pair_ctors!`] macro just above (8580068, four
9691// variants on the paired `{ de, para }` two-slot envelope carrying the
9692// same `let (de, para) = <contract>.edge_pair(); return Err(<Variant>
9693// { de, para });` pair-destructure prelude), the peer four-slot
9694// [`contrato_pair_value_reason_ctors!`] macro (14e13f1, four variants on
9695// the paired `{ de, para, <field>: String, reason: String }` envelope
9696// carrying the parser-shaped `reason` trailer), and the peer four-slot
9697// [`contrato_target_ctors!`] macro (14b81d5, two variants on the paired
9698// `{ de, para, wit, expected: &'static str }` envelope carrying the
9699// canonical target-field-name label). The `ContratoEndpointNotAbsolute`
9700// variant is the sole occupant of the three-slot `{ de, para, <field>:
9701// String }` shape on [`AplicacaoError`] (no sibling
9702// `ContratoSubjectNotAbsolute` / `ContratoSlotNotAbsolute` — the `:subject`
9703// and `:slot` axes carry no "must start with /" invariant, since the
9704// NATS subject grammar and the WASI keyvalue slot template grammar don't
9705// share the Gateway-API-HTTPPathMatch leading-slash prelude the
9706// `:endpoint` axis does), so a full macro isn't warranted; a single
9707// `#[must_use]` inherent ctor matching the ambient
9708// `fn <ctor>(edge: (String, String), <field>: &str) -> Self` shape the
9709// peer per-`:contratos` ctor families each carry closes the last
9710// open-coded three-slot struct-literal on the envelope, matching the
9711// same standalone-ctor discipline the sibling
9712// [`crate::LayoutError::missing_entry`] (1b09f9d, one variant on the
9713// `{ kind: &'static str, path: PathBuf }` two-slot envelope),
9714// [`crate::SupervisorError::child_caixa_invalid`] /
9715// [`::child_versao_invalid`] (d2ef2ec, two variants on the paired
9716// `{ caixa: String, [versao: String,] reason: String }` two- and three-
9717// slot envelopes), and [`AplicacaoError::entrada_host_invalid`] (17dd504,
9718// one variant on the `{ host: String, reason: String }` two-slot
9719// envelope) apply on their sibling one-off variants.
9720//
9721// The one wire-up site on this variant — [`WitContract::target`]'s
9722// HTTP-arm leading-slash gate at `if !ep.starts_with('/')`, one of the
9723// six per-`:contratos` value-shape gates inside the same method body,
9724// where the other five (`ContratoWrongTarget`, `ContratoMissingTarget`,
9725// `ContratoEndpointEmpty`, `ContratoEndpointInvalid`,
9726// `ContratoWitInvalid`) each already reach through one of the three
9727// peer macro-generated ctor families above — opened the same five-line
9728// `let (de, para) = self.edge_pair(); return
9729// Err(AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint:
9730// ep.to_string() });` struct-literal against the local
9731// [`WitContract::edge_pair`] composite-projection accessor and the
9732// caller-side `&str` endpoint — the exact "same block re-inlined at
9733// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
9734// altitude the six peer `AplicacaoError` constructor families each
9735// closed on their sibling envelopes. Every guarantee in MESH-COMPOSITION
9736// §III.3 (a `:contratos :endpoint` value that doesn't start with `/`
9737// becomes a caixa-build error, not a Cilium L7 policy-side path-match
9738// silent traffic drop far from the source caixa.lisp) now routes through
9739// one substrate primitive on the envelope.
9740//
9741// The ctor below folds the site onto one dispatch:
9742// `return Err(AplicacaoError::contrato_endpoint_not_absolute(
9743// self.edge_pair(), ep));`, byte-equal to the pre-lift struct-literal
9744// on the same `(edge_pair, endpoint)` pair. The uniform three-field
9745// construction (`de, para` pair-destructure onto same-named fields +
9746// `endpoint: endpoint.to_string()`) is spelled once — inside the ctor
9747// body — rather than at the wire-up site. `#[must_use]` fires a compile
9748// warning at any future wire-up that mistakenly discards the constructed
9749// error.
9750//
9751// Every future consumer that wants to construct this variant outside
9752// [`WitContract::target`] (a deferred `mesh.pleme.io/v1alpha1/Aplicacao`
9753// CR materializer's per-`:contratos` admission validator raising the
9754// leading-slash diagnostic on unrecognized `:endpoint` shapes, a future
9755// `feira validate --contratos` per-caixa admission verb re-running the
9756// leading-slash arm on demand, an M4 typed Cilium L7 rule pre-emitter
9757// probing each declared `:endpoint` against the same shared
9758// HTTPPathMatch grammar prelude, a per-tenant per-`Aplicacao` overlay
9759// resolver rejecting a leading-slash-missing `:endpoint` against a
9760// cluster-local Cilium snapshot the M4 CR materializer projects) now
9761// reaches this variant through one call rather than re-inlining the
9762// five-line pair-destructure + struct-literal block in lockstep with
9763// the sole in-crate wire-up site.
9764impl AplicacaoError {
9765    /// Construct an [`AplicacaoError::ContratoEndpointNotAbsolute`]
9766    /// naming the offending edge `(de, para)` pair and the per-payload
9767    /// `endpoint` value. Folds the uniform `{ de, para, endpoint:
9768    /// endpoint.to_string() }` three-slot struct-literal onto one
9769    /// substrate primitive so every wire-up on this variant reads
9770    /// through one dispatch rather than the pre-lift five-line
9771    /// pair-destructure + struct-literal block. The `edge` pair threads
9772    /// verbatim from [`WitContract::edge_pair`] at the call site,
9773    /// matching the sibling [`AplicacaoError::contrato_endpoint_empty`] /
9774    /// [`AplicacaoError::contrato_endpoint_invalid`] ctors' shape on the
9775    /// paired two-slot and four-slot per-`:contratos :endpoint`
9776    /// envelopes on the same [`AplicacaoError`] type.
9777    #[must_use]
9778    pub fn contrato_endpoint_not_absolute(edge: (String, String), endpoint: &str) -> Self {
9779        let (de, para) = edge;
9780        Self::ContratoEndpointNotAbsolute {
9781            de,
9782            para,
9783            endpoint: endpoint.to_string(),
9784        }
9785    }
9786
9787    /// Construct an [`AplicacaoError::ContratoSelfLoop`] naming the
9788    /// offending self-edge's owning `caixa` and its `:wit` world
9789    /// reference, projecting both slots through the [`WitContract`]'s
9790    /// own [`WitContract::source`] and [`WitContract::world_ref`]
9791    /// scalar accessors on the substrate primitive.
9792    ///
9793    /// Folds the uniform `{ caixa: contract.source().to_string(), wit:
9794    /// contract.world_ref().to_string() }` two-slot struct-literal onto
9795    /// one substrate primitive so every wire-up on this variant reads
9796    /// through one dispatch rather than the pre-lift four-line
9797    /// twin-`.to_string()` struct-literal block. The `contract` borrow
9798    /// threads verbatim from the caller-side `for c in
9799    /// self.contratos()` iteration at the sole in-crate wire-up site
9800    /// [`AplicacaoSpec::validate_contratos`], matching the sibling
9801    /// per-`:contratos` `WitContract`-projection ctor discipline the
9802    /// peer [`AplicacaoError::empty_wit`] /
9803    /// [`AplicacaoError::contrato_endpoint_empty`] /
9804    /// [`AplicacaoError::contrato_subject_empty`] /
9805    /// [`AplicacaoError::contrato_slot_empty`] ctors carry through
9806    /// [`WitContract::edge_pair`] on the sibling two-slot `{ de, para }`
9807    /// envelope.
9808    ///
9809    /// The `caixa` slot is projected through [`WitContract::source`]
9810    /// rather than [`WitContract::destination`] to preserve byte-equal
9811    /// diagnostic ordering with the pre-lift open-coded body — a
9812    /// [`WitContract::is_self_loop`]-gated call site has
9813    /// `source() == destination()` by that predicate's own contract, so
9814    /// the two accessors are exchange-symmetric at this call site, but
9815    /// naming `source` at the ctor definition matches the pre-lift
9816    /// site's field selection and pins the discipline for any future
9817    /// consumer that constructs the variant against a not-yet-gated
9818    /// candidate contract (e.g. an M4
9819    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9820    /// webhook re-checking a per-`(:de, :para)` patched contract, a
9821    /// future `feira validate --contratos` per-caixa verb re-running
9822    /// the self-loop diagnostic on demand, a per-tenant per-Aplicacao
9823    /// overlay resolver rejecting a self-edge introduced by a
9824    /// cluster-local `:contratos` override the M4 CR materializer
9825    /// projects).
9826    ///
9827    /// Peer of the sibling `WitContract`-projection ctors on the
9828    /// per-`:contratos` envelopes on the same [`AplicacaoError`] type —
9829    /// same "one typed dispatch on the substrate primitive, projecting
9830    /// through the paired [`WitContract`] accessors, thin projections
9831    /// at each consumer" discipline extended here onto the last unlifted
9832    /// two-slot `{ caixa: String, wit: String }` per-self-edge envelope
9833    /// inside [`AplicacaoSpec::validate_contratos`].
9834    #[must_use]
9835    pub fn contrato_self_loop(contract: &WitContract) -> Self {
9836        Self::ContratoSelfLoop {
9837            caixa: contract.source().to_string(),
9838            wit: contract.world_ref().to_string(),
9839        }
9840    }
9841
9842    /// Construct an [`AplicacaoError::ContratoDuplicate`] naming the
9843    /// offending duplicate edge's `(:de, :para, :wit)` triple and the
9844    /// per-payload `:target` byte-string, projecting the first three slots
9845    /// through the paired [`WitContract::edge_triple`] typed-accessor and
9846    /// the trailing `target:` slot through [`WitTarget::label`] on the
9847    /// substrate primitive.
9848    ///
9849    /// Folds the uniform `let (de, para, wit) = contract.edge_triple();
9850    /// Self::ContratoDuplicate { de, para, wit, target: target.label() }`
9851    /// six-line pair-destructure + struct-literal onto one substrate
9852    /// primitive so every wire-up on this variant reads through one
9853    /// dispatch rather than the pre-lift open-coded block inside the
9854    /// [`AplicacaoSpec::validate_contratos`] whole-edge dedup closure
9855    /// passed to [`crate::render::insert_first_seen`]. Peer of the sibling
9856    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
9857    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
9858    /// per-`:contratos` self-edge two-slot envelope) and the sibling
9859    /// [`AplicacaoError::empty_wit`] (projecting through
9860    /// [`WitContract::edge_pair`] on the sibling per-`:contratos` empty-
9861    /// `:wit` two-slot envelope) `WitContract`-projection ctors on the
9862    /// same [`AplicacaoError`] type — extended here onto the last unlifted
9863    /// four-slot `{ de: String, para: String, wit: String, target: String }`
9864    /// per-`:contratos` whole-edge-dedup envelope inside
9865    /// [`AplicacaoSpec::validate_contratos`], closing the paired
9866    /// duplicate-gate diagnostic constructor site the peer
9867    /// [`WitContract::edge_triple`] (5dbcfaf) lift's doc-block flagged as
9868    /// the last unlifted composite-projection wire-up.
9869    ///
9870    /// The `contract` borrow threads verbatim from the caller-side `for c
9871    /// in self.contratos()` iteration at the sole in-crate wire-up site
9872    /// [`AplicacaoSpec::validate_contratos`], and `target` threads
9873    /// verbatim from the paired `let target_view = c.target()?` local
9874    /// materialized upstream of the [`crate::render::insert_first_seen`]
9875    /// dedup dispatch — both project onto their respective substrate-
9876    /// primitive accessors ([`WitContract::edge_triple`] +
9877    /// [`WitTarget::label`]) inside the ctor body, matching the sibling
9878    /// [`AplicacaoError::contrato_self_loop`] `WitContract`-projection
9879    /// posture verbatim on the paired self-edge envelope.
9880    ///
9881    /// Every future consumer that wants to construct this variant outside
9882    /// [`AplicacaoSpec::validate_contratos`] — a deferred
9883    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9884    /// webhook re-checking a per-`(:de, :para, :wit, :target)`-patched
9885    /// candidate against a per-tenant `:contratos` overlay before the
9886    /// whole-edge dedup gate re-fires, a future `feira validate
9887    /// --contratos` per-caixa admission verb re-running the dedup check on
9888    /// demand, an M4 per-cluster contrato-cap resolver rejecting a
9889    /// cross-tenant duplicate-edge collision introduced by a fleet-local
9890    /// overlay the M4 CR materializer projects — now reaches this variant
9891    /// through one call rather than re-inlining the six-line pair-
9892    /// destructure + struct-literal block in lockstep with the existing
9893    /// wire-up.
9894    #[must_use]
9895    pub fn contrato_duplicate(contract: &WitContract, target: &WitTarget<'_>) -> Self {
9896        let (de, para, wit) = contract.edge_triple();
9897        Self::ContratoDuplicate {
9898            de,
9899            para,
9900            wit,
9901            target: target.label(),
9902        }
9903    }
9904
9905    /// Construct an [`AplicacaoError::MembroVersaoInvalid`] naming the
9906    /// offending `:membros :caixa` and its `:versao` requirement under
9907    /// the given `reason`. Folds the uniform `Self::MembroVersaoInvalid {
9908    /// caixa: caixa.to_string(), versao: versao.to_string(), reason:
9909    /// reason.into() }` three-slot struct-literal onto one substrate
9910    /// primitive so every wire-up on this variant reads through one
9911    /// dispatch, matching the peer
9912    /// [`crate::SupervisorError::child_versao_invalid`] (d2ef2ec) ctor's
9913    /// shape verbatim on the sibling `SupervisorError { caixa: String,
9914    /// versao: String, reason: String }` envelope's per-`:children :versao`
9915    /// axis. `reason` accepts both `&str` literals and `format!(…)`
9916    /// outputs through the `impl Into<String>` bound so the sole
9917    /// [`AplicacaoSpec::validate_membros`] wire-up's per-`:membros`
9918    /// requirement-cascade closure (routing the shared
9919    /// [`crate::render::require_valid_versao_requirement`]-delivered
9920    /// `reason` verbatim) picks the ctor up without a per-arm wrapper
9921    /// transformation on the caller-side `reason` axis. The
9922    /// [`Membro::nome`] / [`Membro::versao_requirement`] typed-accessor
9923    /// routing the sole wire-up already threads through remains verbatim
9924    /// — the ctor's two `&str` parameters accept the two accessors'
9925    /// returns as-is with no re-allocation at the call site.
9926    #[must_use]
9927    pub fn membro_versao_invalid(caixa: &str, versao: &str, reason: impl Into<String>) -> Self {
9928        Self::MembroVersaoInvalid {
9929            caixa: caixa.to_string(),
9930            versao: versao.to_string(),
9931            reason: reason.into(),
9932        }
9933    }
9934
9935    /// Construct an [`AplicacaoError::PlacementClusterDuplicate`] naming
9936    /// the offending `:placement :clusters` entry.
9937    ///
9938    /// Folds the uniform `Self::PlacementClusterDuplicate { cluster:
9939    /// cluster.to_string() }` one-field struct-literal onto one substrate
9940    /// primitive so every wire-up on this variant reads through one
9941    /// dispatch rather than the pre-lift three-line open-coded
9942    /// struct-literal block. The `cluster` slot threads verbatim from the
9943    /// caller-side `for c in p.clusters()` iteration at the sole in-crate
9944    /// wire-up site [`AplicacaoSpec::validate_placement_shape`], via the
9945    /// per-entry dedup closure passed to
9946    /// [`crate::render::insert_first_seen`] whose `FnOnce`-shaped ctor
9947    /// bracket accepts the free function pointer as-is.
9948    ///
9949    /// Sibling of the per-`:membros :caixa` / per-`:entrada :paths` /
9950    /// per-`:politicas <scalar>` single-slot ctor families
9951    /// ([`aplicacao_caixa_only_ctors!`] on `{ caixa: String }` at the
9952    /// peer per-membership envelope, [`aplicacao_path_only_ctors!`] on
9953    /// `{ path: String }` at the peer per-gateway envelope,
9954    /// [`aplicacao_policy_scalar_ctors!`] on `{ <field>: Copy-scalar }`
9955    /// at the peer per-`:politicas` cap-scalar envelope) on the same
9956    /// [`AplicacaoError`] type — extends the "one typed dispatch per
9957    /// substrate primitive on every single-slot per-M3-slot envelope"
9958    /// discipline onto the last unlifted `{ cluster: String }` one-slot
9959    /// per-`:placement :clusters` dedup-envelope inside
9960    /// [`AplicacaoSpec::validate_placement_shape`].
9961    ///
9962    /// Every future consumer that wants to construct this variant outside
9963    /// [`AplicacaoSpec::validate_placement_shape`] — a deferred
9964    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
9965    /// webhook re-checking a `:placement :clusters` overlay against a
9966    /// per-tenant cluster-topology snapshot, a future `feira validate
9967    /// --placement` per-caixa admission verb re-running the dedup check
9968    /// on demand, an M4 per-cluster placement resolver rejecting a
9969    /// duplicate cluster-name entry introduced by a fleet-local overlay
9970    /// the M4 CR materializer projects — now reaches this variant through
9971    /// one call rather than re-inlining the three-line struct-literal.
9972    #[must_use]
9973    pub fn placement_cluster_duplicate(cluster: &str) -> Self {
9974        Self::PlacementClusterDuplicate {
9975            cluster: cluster.to_string(),
9976        }
9977    }
9978
9979    /// Construct an [`AplicacaoError::PlacementWithoutClusters`] naming
9980    /// the offending `:placement :estrategia` scalar the empty `:clusters`
9981    /// list was declared against, projecting through the paired
9982    /// [`Placement::estrategia`] `Copy`-scalar accessor on the substrate
9983    /// primitive.
9984    ///
9985    /// Folds the uniform `Self::PlacementWithoutClusters { estrategia:
9986    /// placement.estrategia() }` one-field struct-literal onto one
9987    /// substrate primitive so every wire-up on this variant reads through
9988    /// one dispatch rather than the pre-lift three-line open-coded
9989    /// `AplicacaoError::PlacementWithoutClusters { estrategia:
9990    /// p.estrategia() }` block inside
9991    /// [`AplicacaoSpec::validate_placement`]. Same substrate-primitive-
9992    /// projection posture as the sibling
9993    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting through
9994    /// [`WitContract::source`] / [`WitContract::world_ref`] on the paired
9995    /// per-`:contratos` self-edge envelope) and the peer
9996    /// [`crate::UpgradeError::duplicate_from`] (7e52aec, projecting through
9997    /// [`crate::UpgradeFromEntry::prior_versao`] on the sibling
9998    /// per-`:upgrade-from :from` envelope) ctors — extended here onto the
9999    /// last unlifted `{ estrategia: PlacementStrategy }` one-slot
10000    /// per-`:placement` empty-clusters envelope inside
10001    /// [`AplicacaoSpec::validate_placement`].
10002    ///
10003    /// `#[must_use]` and `const fn` alike: the ctor threads the paired
10004    /// [`Placement::estrategia`] `Copy`-scalar return through one
10005    /// zero-runtime-work construction — no allocation, no owned-string
10006    /// materialization — so the pre-lift `Copy`-pass-through property the
10007    /// open-coded `p.estrategia()` field expression carried survives
10008    /// verbatim through the substrate primitive. The sibling
10009    /// [`AplicacaoError::placement_cluster_duplicate`] (92b1c92) ctor
10010    /// carries the paired `.to_string()`-owned-String allocation on the
10011    /// `{ cluster: String }` envelope; this ctor's `Copy`-scalar envelope
10012    /// preserves the zero-alloc posture at the substrate-primitive
10013    /// dispatch, matching the peer
10014    /// [`aplicacao_policy_scalar_ctors!`] (7ef425e, eight variants on
10015    /// `{ <scalar>: Copy }`) family's `const fn` posture on the sibling
10016    /// per-`:politicas` cap-scalar envelopes.
10017    ///
10018    /// Every future consumer that wants to construct this variant outside
10019    /// [`AplicacaoSpec::validate_placement`] — a deferred
10020    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10021    /// webhook re-checking a `:placement :clusters` overlay against a
10022    /// per-tenant cluster-topology snapshot when the overlay resolves to
10023    /// an empty list, a future `feira validate --placement` per-caixa
10024    /// admission verb re-running the empty-clusters check on demand, an
10025    /// M4 per-cluster placement resolver rejecting an empty cluster pool
10026    /// after a fleet-local overlay strips every declared cluster — now
10027    /// reaches this variant through one call rather than re-inlining the
10028    /// three-line struct-literal in lockstep with the one in-crate
10029    /// wire-up site.
10030    #[must_use]
10031    pub const fn placement_without_clusters(placement: &Placement) -> Self {
10032        Self::PlacementWithoutClusters {
10033            estrategia: placement.estrategia(),
10034        }
10035    }
10036
10037    /// Construct an [`AplicacaoError::ShardKeyOnNonSharded`] naming the
10038    /// offending `:placement :estrategia` scalar and the declared-but-
10039    /// inert `:shard-key` value the non-`Sharded` arm refused, projecting
10040    /// the strategy through the paired [`Placement::estrategia`]
10041    /// `Copy`-scalar accessor on the substrate primitive.
10042    ///
10043    /// Folds the uniform `Self::ShardKeyOnNonSharded { estrategia:
10044    /// placement.estrategia(), shard_key: shard_key.to_string() }`
10045    /// two-slot struct-literal onto one substrate primitive so every
10046    /// wire-up on this variant reads through one dispatch rather than
10047    /// the pre-lift four-line open-coded struct-literal block inside
10048    /// [`AplicacaoSpec::validate_placement`]'s
10049    /// `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
10050    /// arm. Same substrate-primitive-projection posture as the sibling
10051    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
10052    /// projecting through [`Placement::estrategia`] on the peer
10053    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
10054    /// empty-clusters envelope) and the peer
10055    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
10056    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
10057    /// the paired per-`:contratos` self-edge envelope) ctors — extended
10058    /// here onto the last unlifted `{ estrategia: PlacementStrategy,
10059    /// shard_key: String }` two-slot per-`:placement :shard-key`
10060    /// declared-but-inert envelope on the sibling non-`Sharded`-arm
10061    /// partition.
10062    ///
10063    /// The `shard_key: &str` parameter accepts both the `Some(k)`-bound
10064    /// `&str` from the sole in-crate wire-up site (narrowed from
10065    /// `Option<&str>` via [`Placement::shard_key`]) and any future
10066    /// `&String` deref from a downstream consumer that reaches for the
10067    /// slot through the paired accessor, materializing the owned
10068    /// [`String`] via one `.to_string()` at the substrate primitive so
10069    /// no per-arm `.to_string()` allocation lives at the caller. The
10070    /// `estrategia` slot threads through [`Placement::estrategia`]'s
10071    /// `Copy`-scalar return rather than accepting a bare
10072    /// [`PlacementStrategy`] argument, matching the peer
10073    /// [`AplicacaoError::placement_without_clusters`] discipline —
10074    /// carrying the [`Placement`] borrow through one accessor call at
10075    /// the substrate primitive is strictly stronger than accepting the
10076    /// scalar as a separate argument (a future caller that constructs
10077    /// the error against a candidate [`Placement`] whose
10078    /// [`Placement::estrategia`] value the caller re-derives from
10079    /// another source can silently disagree with the storage the
10080    /// [`Placement`] carries; the accessor-projected primitive cannot).
10081    ///
10082    /// Peer of the sibling per-`:placement` single-slot / two-slot ctor
10083    /// families on the same [`AplicacaoError`] type — same "one typed
10084    /// dispatch on the substrate primitive, projecting through the
10085    /// paired [`Placement`] accessors, thin projections at each
10086    /// consumer" discipline extended here onto the last unlifted
10087    /// per-`:placement :shard-key` non-`Sharded`-arm envelope inside
10088    /// [`AplicacaoSpec::validate_placement`].
10089    ///
10090    /// Every future consumer that wants to construct this variant
10091    /// outside [`AplicacaoSpec::validate_placement`] — a deferred
10092    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10093    /// webhook re-checking a `:placement (:estrategia Replicated
10094    /// :shard-key …)` overlay against a per-tenant cluster-topology
10095    /// snapshot, a future `feira validate --placement` per-caixa
10096    /// admission verb re-running the non-`Sharded`-arm refusal on
10097    /// demand, an M4 per-cluster placement resolver rejecting a
10098    /// declared-but-inert `:shard-key` introduced by a fleet-local
10099    /// overlay the M4 CR materializer projects — now reaches this
10100    /// variant through one call rather than re-inlining the four-line
10101    /// struct-literal in lockstep with the one in-crate wire-up site.
10102    #[must_use]
10103    pub fn shard_key_on_non_sharded(placement: &Placement, shard_key: &str) -> Self {
10104        Self::ShardKeyOnNonSharded {
10105            estrategia: placement.estrategia(),
10106            shard_key: shard_key.to_string(),
10107        }
10108    }
10109
10110    /// Construct an [`AplicacaoError::EntradaMemberMissing`] naming the
10111    /// offending `:entrada :para` value the membership lookup against the
10112    /// [`AplicacaoSpec::membro_names`] oracle refused, projecting the
10113    /// slot through the paired [`Entrada::destination`] byte-string
10114    /// accessor on the substrate primitive.
10115    ///
10116    /// Folds the uniform `Self::EntradaMemberMissing { para:
10117    /// entrada.destination().to_string() }` one-field struct-literal onto
10118    /// one substrate primitive so every wire-up on this variant reads
10119    /// through one dispatch rather than the pre-lift three-line
10120    /// open-coded `AplicacaoError::EntradaMemberMissing { para:
10121    /// e.destination().to_string() }` block inside
10122    /// [`AplicacaoSpec::validate_entrada`]. Same substrate-primitive-
10123    /// projection posture as the sibling
10124    /// [`AplicacaoError::placement_without_clusters`] (b0d24ba,
10125    /// projecting through [`Placement::estrategia`] on the peer
10126    /// `{ estrategia: PlacementStrategy }` one-slot per-`:placement`
10127    /// empty-clusters envelope) and the sibling
10128    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
10129    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
10130    /// the paired per-`:contratos` self-edge envelope) ctors — extended
10131    /// here onto the last unlifted `{ para: String }` one-slot
10132    /// per-`:entrada :para` phantom-reference envelope on the sibling
10133    /// per-`:entrada` slot.
10134    ///
10135    /// The `entrada: &Entrada` parameter threads verbatim from the
10136    /// caller-side `if let Some(e) = self.entrada() { … }` traversal at
10137    /// the sole in-crate wire-up site
10138    /// [`AplicacaoSpec::validate_entrada`], matching the sibling
10139    /// per-`:entrada` byte-string reads that already route through
10140    /// [`Entrada::destination`] one accessor call earlier in the same
10141    /// gate (`validate_entrada_para(e.destination())?;` +
10142    /// `if !names.contains(e.destination()) …`). Carrying the [`Entrada`]
10143    /// borrow through one accessor call at the substrate primitive is
10144    /// strictly stronger than accepting the bare `&str` as a separate
10145    /// argument — a future consumer that constructs the error against a
10146    /// candidate [`Entrada`] whose [`Entrada::destination`] value the
10147    /// caller re-derives from another source (a raw `e.para` field
10148    /// access that skipped the accessor, a stale snapshot of the
10149    /// pre-normalization storage) can silently disagree with the
10150    /// storage the [`Entrada`] carries; the accessor-projected primitive
10151    /// cannot. Matches the peer
10152    /// [`AplicacaoError::placement_without_clusters`] and
10153    /// [`AplicacaoError::shard_key_on_non_sharded`]
10154    /// [`Placement`]-borrow-projection discipline on the sibling
10155    /// per-`:placement` envelope, and matches the peer
10156    /// [`AplicacaoError::contrato_self_loop`] and
10157    /// [`AplicacaoError::contrato_endpoint_not_absolute`]
10158    /// [`WitContract`]-borrow-projection discipline on the sibling
10159    /// per-`:contratos` envelope.
10160    ///
10161    /// Every future consumer that wants to construct this variant
10162    /// outside [`AplicacaoSpec::validate_entrada`] — a deferred
10163    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10164    /// webhook re-checking a `:entrada :para` overlay against a
10165    /// per-tenant `:membros` snapshot after a fleet-local overlay
10166    /// renames a member, a future `feira validate --entrada` per-caixa
10167    /// admission verb re-running the phantom-reference lookup on
10168    /// demand, an M4 per-cluster Gateway API pre-emitter rejecting a
10169    /// `:entrada :para` whose target Servico was stripped from the
10170    /// cluster-local `:membros` overlay, a future authoring-surface
10171    /// widening the field into a `(String, Vec<Suggestion>)` pair
10172    /// carrying a "did-you-mean-<nearest-member>" hint — now reaches
10173    /// this variant through one call rather than re-inlining the
10174    /// three-line struct-literal in lockstep with the one in-crate
10175    /// wire-up site.
10176    #[must_use]
10177    pub fn entrada_member_missing(entrada: &Entrada) -> Self {
10178        Self::EntradaMemberMissing {
10179            para: entrada.destination().to_string(),
10180        }
10181    }
10182
10183    /// Construct an [`AplicacaoError::ContratoCycle`] naming the
10184    /// synchronous-`:contratos` cycle path the DFS-with-three-coloring
10185    /// sync-only-subgraph gate at
10186    /// [`AplicacaoSpec::detect_sync_cycles`] reconstructed from the
10187    /// gray-arm's back-edge target through the parent chain, folding the
10188    /// uniform `Self::ContratoCycle { cycle }` one-field struct-literal
10189    /// onto one substrate primitive so every wire-up on this variant
10190    /// reads through one dispatch rather than the pre-lift open-coded
10191    /// `AplicacaoError::ContratoCycle { cycle }` block at the sole
10192    /// in-crate wire-up site inside
10193    /// [`AplicacaoSpec::detect_sync_cycles`]'s gray-arm cycle-close
10194    /// return. Same substrate-primitive-projection posture as the
10195    /// sibling [`AplicacaoError::entrada_member_missing`] (deeae5c,
10196    /// projecting through [`Entrada::destination`] on the peer `{ para:
10197    /// String }` one-slot per-`:entrada :para` phantom-reference
10198    /// envelope) and [`AplicacaoError::placement_without_clusters`]
10199    /// (b0d24ba, projecting through [`Placement::estrategia`] on the
10200    /// sibling `{ estrategia: PlacementStrategy }` one-slot
10201    /// per-`:placement` empty-clusters envelope) ctors — extended here
10202    /// onto the last unlifted `{ cycle: Vec<String> }` one-slot
10203    /// per-`:contratos` cross-edge sync-cycle envelope on the same
10204    /// [`AplicacaoError`] type. Closes the last unlifted `AplicacaoError`
10205    /// struct-literal wire-up under
10206    /// [`AplicacaoSpec::detect_sync_cycles`].
10207    ///
10208    /// The `cycle: Vec<String>` parameter threads verbatim from the
10209    /// caller-side DFS traversal's reconstructed cycle path (built up by
10210    /// walking `parent` from the gray-back-edge's source node back to
10211    /// its target, reversing, then appending the target once more so the
10212    /// first and last elements coincide by construction and the
10213    /// `Display` rendering under the [`AplicacaoError::ContratoCycle`]
10214    /// `cycle.join(" → ")` formatter reads as a closed loop), matching
10215    /// the pre-lift open-coded body's field selection exactly. Taking
10216    /// the owned [`Vec<String>`] rather than a borrowed slice + collect
10217    /// on the ctor side keeps the pre-lift wire-up byte-identical (the
10218    /// caller already owns the reconstructed [`Vec<String>`] at the
10219    /// gray-arm return, so no per-arm re-allocation lands on the ctor
10220    /// path).
10221    ///
10222    /// Peer of the sibling per-`:contratos` single-slot / two-slot ctor
10223    /// families on the same [`AplicacaoError`] type — same "one typed
10224    /// dispatch on the substrate primitive, thin projections at each
10225    /// consumer" discipline extended here onto the last unlifted
10226    /// per-`:contratos` cross-edge cycle envelope inside
10227    /// [`AplicacaoSpec::detect_sync_cycles`].
10228    ///
10229    /// Every future consumer that wants to construct this variant
10230    /// outside [`AplicacaoSpec::detect_sync_cycles`] — a deferred
10231    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10232    /// webhook re-checking a per-tenant `:contratos` overlay's
10233    /// sync-cycle invariant after a fleet-local overlay adds or removes
10234    /// a synchronous edge, a future `feira validate --contratos`
10235    /// per-caixa admission verb re-running the cross-edge cycle detector
10236    /// on demand, the M4 per-edge policy resolver MESH-COMPOSITION §III.2
10237    /// #3 acknowledges (whose per-edge patch mutates one `:contratos`
10238    /// entry and needs to re-probe *just* the cycle invariant against
10239    /// the post-patch adjacency), a future authoring-surface widening
10240    /// the field into a `(Vec<String>, Vec<WitTarget>)` pair carrying
10241    /// the per-hop WIT shape for a richer "break here" hint — now
10242    /// reaches this variant through one call rather than re-inlining the
10243    /// open-coded struct-literal in lockstep with the one in-crate
10244    /// wire-up site.
10245    #[must_use]
10246    pub fn contrato_cycle(cycle: Vec<String>) -> Self {
10247        Self::ContratoCycle { cycle }
10248    }
10249
10250    /// Construct an [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
10251    /// naming the offending `:politicas :circuit-breaker :window` and
10252    /// the paired `:politicas :timeout` scalars under the first-firing
10253    /// cross-axis-violation gate at
10254    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
10255    /// `window` slot through the [`CircuitBreaker::window`] scalar
10256    /// accessor on the substrate primitive.
10257    ///
10258    /// Folds the uniform `{ window: cb.window(), timeout: t }`
10259    /// two-slot `Copy`-`Duration` struct-literal onto one substrate
10260    /// primitive so every wire-up on this variant reads through one
10261    /// dispatch rather than the pre-lift four-line struct-literal
10262    /// block. The `cb` borrow threads verbatim from the caller-side
10263    /// `if let (Some(t), Some(cb)) = (self.timeout(),
10264    /// self.circuit_breaker())` pair-destructure at the sole in-crate
10265    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
10266    /// window-below-timeout arm; `timeout` threads verbatim from the
10267    /// paired [`MeshPolicy::timeout`] accessor return already
10268    /// destructured out of the same `if let` pair. `const fn`
10269    /// preserves the pre-lift `Copy`-pass-through's zero-runtime-work
10270    /// property verbatim (both fields are [`Duration`], the
10271    /// [`CircuitBreaker::window`] accessor is itself `const fn`, and
10272    /// no `.to_string()` / `.into()` allocation lands on the ctor
10273    /// path).
10274    ///
10275    /// The `window` slot is projected through [`CircuitBreaker::window`]
10276    /// (not spelled out as a bare `Duration` parameter) so a future
10277    /// widening of the `:circuit-breaker :window` axis — a
10278    /// per-`:contratos`-edge `:circuit-breaker :window` override the
10279    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a promotion of
10280    /// the plain [`Duration`] window to a richer per-status-class
10281    /// window tuple once Envoy's `outlier_detection.interval` peers
10282    /// come into scope — reaches the diagnostic through one accessor
10283    /// swap rather than every wire-up in lockstep, matching the peer
10284    /// substrate-primitive-projection posture of
10285    /// [`AplicacaoError::contrato_self_loop`] (b30edfe, projecting
10286    /// through [`WitContract::source`] / [`WitContract::world_ref`] on
10287    /// the sibling `{ caixa: String, wit: String }` two-slot
10288    /// per-`:contratos` self-edge envelope),
10289    /// [`AplicacaoError::entrada_member_missing`] (deeae5c, projecting
10290    /// through [`Entrada::destination`] on the sibling `{ para: String }`
10291    /// one-slot per-`:entrada :para` phantom-reference envelope), and
10292    /// [`AplicacaoError::shard_key_on_non_sharded`] (14bafca, projecting
10293    /// through [`Placement::estrategia`] on the sibling `{ estrategia:
10294    /// PlacementStrategy, shard_key: String }` two-slot per-`:placement`
10295    /// envelope) ctors carry on the sibling `:contratos` / `:entrada`
10296    /// / `:placement` envelopes.
10297    ///
10298    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
10299    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
10300    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
10301    /// [`MeshPolicy::validate`] gate — extended here onto the
10302    /// first-firing cross-axis compound variant, whose multi-slot
10303    /// `{ window: Duration, timeout: Duration }` shape does not fit
10304    /// that macro's one-`Copy`-scalar-per-variant arity. The three
10305    /// remaining cross-axis variants
10306    /// ([`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] on
10307    /// the four-slot `{ rate, rl_window, max_failures, cb_window }`
10308    /// envelope, [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
10309    /// on the two-slot `{ retries, max_failures }` envelope, and
10310    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
10311    /// two-slot `{ retries, rate }` envelope) each carry a distinct
10312    /// substrate-primitive-projection shape and are folded on their
10313    /// own axis by their own per-variant ctors as those wire-ups are
10314    /// lifted.
10315    ///
10316    /// Every future consumer that wants to construct this variant
10317    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10318    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10319    /// webhook re-checking a per-tenant `:politicas` overlay's
10320    /// window-vs-timeout cross-axis invariant after a cluster-local
10321    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10322    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10323    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10324    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10325    /// projecting a per-tenant per-axis ceiling into the same
10326    /// diagnostic shape — now reaches this variant through one call
10327    /// rather than re-inlining the open-coded struct-literal in
10328    /// lockstep with the one in-crate wire-up site.
10329    #[must_use]
10330    pub const fn policy_breaker_window_below_timeout(
10331        cb: &CircuitBreaker,
10332        timeout: Duration,
10333    ) -> Self {
10334        Self::PolicyBreakerWindowBelowTimeout {
10335            window: cb.window(),
10336            timeout,
10337        }
10338    }
10339
10340    /// Construct an [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
10341    /// naming the `(:politicas :rate-limit, :politicas :circuit-breaker)`
10342    /// cross-axis pair whose token-bucket window structurally starves the
10343    /// breaker so `:max-failures` cannot be reached inside `:circuit-breaker
10344    /// :window`.
10345    ///
10346    /// Folds the uniform `{ rate: rl.rate(), rl_window: rl.window(),
10347    /// max_failures: cb.max_failures(), cb_window: cb.window() }`
10348    /// four-slot `Copy`-`(u32 | Duration)` struct-literal onto one substrate
10349    /// primitive so every wire-up on this variant reads through one dispatch
10350    /// rather than the pre-lift six-line struct-literal block. Both `rl` and
10351    /// `cb` borrows thread verbatim from the caller-side `if let (Some(rl),
10352    /// Some(cb)) = (self.rate_limit(), self.circuit_breaker())`
10353    /// pair-destructure at the sole in-crate wire-up site inside
10354    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-limit
10355    /// arm. `const fn` preserves the pre-lift `Copy`-pass-through's
10356    /// zero-runtime-work property verbatim (all four fields are `u32` /
10357    /// [`Duration`], every projected accessor is itself `const fn`, and no
10358    /// `.to_string()` / `.into()` allocation lands on the ctor path).
10359    ///
10360    /// Every slot is projected through its paired substrate-primitive
10361    /// accessor ([`RateLimit::rate`], [`RateLimit::window`],
10362    /// [`CircuitBreaker::max_failures`], [`CircuitBreaker::window`]) rather
10363    /// than spelled out as bare `u32` / [`Duration`] parameters so a future
10364    /// widening of either axis — a per-`:contratos`-edge `:rate-limit` or
10365    /// `:circuit-breaker` override the MESH-COMPOSITION §III.2 #3 roadmap
10366    /// acknowledges, a promotion of the plain scalar rate to a richer
10367    /// per-status-class token bucket once Envoy's per-descriptor
10368    /// `local_rate_limit` peers come into scope — reaches the diagnostic
10369    /// through one accessor swap rather than every wire-up in lockstep.
10370    /// Matches the peer substrate-primitive-projection posture of
10371    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
10372    /// projecting through [`CircuitBreaker::window`] on the sibling
10373    /// two-slot `{ window, timeout }` cross-axis
10374    /// `(:timeout, :circuit-breaker)` envelope) on the sibling
10375    /// first-firing cross-axis compound variant.
10376    ///
10377    /// Second cross-axis Policy* variant folded onto its own per-variant
10378    /// substrate primitive — extending the peer
10379    /// [`AplicacaoError::policy_breaker_window_below_timeout`] discipline
10380    /// onto the second-firing cross-axis compound variant, whose four-slot
10381    /// `{ rate, rl_window, max_failures, cb_window }` shape does not fit
10382    /// the sibling two-slot ctor's arity. The two remaining cross-axis
10383    /// variants ([`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
10384    /// on the two-slot `{ retries, max_failures }` envelope and
10385    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
10386    /// two-slot `{ retries, rate }` envelope) each carry a distinct
10387    /// substrate-primitive-projection shape and are folded on their own
10388    /// axis by their own per-variant ctors as those wire-ups are lifted.
10389    ///
10390    /// Every future consumer that wants to construct this variant outside
10391    /// [`MeshPolicy::first_cross_axis_violation`] — a deferred
10392    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10393    /// webhook re-checking a per-tenant `:politicas` overlay's
10394    /// starve-under-rate-limit cross-axis invariant after a cluster-local
10395    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10396    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10397    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10398    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10399    /// projecting a per-tenant per-axis ceiling into the same diagnostic
10400    /// shape — now reaches this variant through one call rather than
10401    /// re-inlining the open-coded struct-literal in lockstep with the one
10402    /// in-crate wire-up site.
10403    #[must_use]
10404    pub const fn policy_breaker_cannot_trip_under_rate_limit(
10405        rl: &RateLimit,
10406        cb: &CircuitBreaker,
10407    ) -> Self {
10408        Self::PolicyBreakerCannotTripUnderRateLimit {
10409            rate: rl.rate(),
10410            rl_window: rl.window(),
10411            max_failures: cb.max_failures(),
10412            cb_window: cb.window(),
10413        }
10414    }
10415
10416    /// Construct an
10417    /// [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
10418    /// naming the offending `:politicas :retries` and the paired
10419    /// `:politicas :circuit-breaker :max-failures` scalars under the
10420    /// third-firing cross-axis-violation gate at
10421    /// [`MeshPolicy::first_cross_axis_violation`], projecting the
10422    /// `max_failures` slot through the [`CircuitBreaker::max_failures`]
10423    /// scalar accessor on the substrate primitive.
10424    ///
10425    /// Folds the uniform `{ retries, max_failures: cb.max_failures() }`
10426    /// two-slot `Copy`-`u32` struct-literal onto one substrate
10427    /// primitive so every wire-up on this variant reads through one
10428    /// dispatch rather than the pre-lift four-line struct-literal
10429    /// block. The `cb` borrow threads verbatim from the caller-side
10430    /// `if let (Some(retries), Some(cb)) = (self.retries(),
10431    /// self.circuit_breaker())` pair-destructure at the sole in-crate
10432    /// wire-up site inside [`MeshPolicy::first_cross_axis_violation`]'s
10433    /// retries-saturate arm; `retries` threads verbatim from the paired
10434    /// [`MeshPolicy::retries`] accessor return already destructured out
10435    /// of the same `if let` pair. `const fn` preserves the pre-lift
10436    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
10437    /// fields are `u32`, the [`CircuitBreaker::max_failures`] accessor
10438    /// is itself `const fn`, and no `.to_string()` / `.into()`
10439    /// allocation lands on the ctor path).
10440    ///
10441    /// The `max_failures` slot is projected through
10442    /// [`CircuitBreaker::max_failures`] (not spelled out as a bare
10443    /// `u32` parameter) so a future widening of the
10444    /// `:circuit-breaker :max-failures` axis — a
10445    /// per-`:contratos`-edge `:circuit-breaker :max-failures` override
10446    /// the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-tenant
10447    /// `:max-failures` ceiling the M4 per-cluster `:politicas`-cap
10448    /// resolver projects, a promotion of the plain `u32` count to a
10449    /// richer per-status-class trip counter once Envoy's
10450    /// `outlier_detection.consecutive_5xx` peers come into scope —
10451    /// reaches the diagnostic through one accessor swap rather than
10452    /// every wire-up in lockstep, matching the peer
10453    /// substrate-primitive-projection posture of
10454    /// [`AplicacaoError::policy_breaker_window_below_timeout`]
10455    /// (9b30c07, projecting through [`CircuitBreaker::window`] on the
10456    /// sibling two-slot `{ window, timeout }` first cross-axis
10457    /// envelope) and
10458    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
10459    /// (6bb4e46, projecting through [`RateLimit::rate`] /
10460    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
10461    /// [`CircuitBreaker::window`] on the sibling four-slot second
10462    /// cross-axis envelope). `retries` remains a bare `u32` parameter,
10463    /// matching the sibling first-arm ctor's bare `timeout: Duration`
10464    /// parameter discipline: [`MeshPolicy::retries`] returns
10465    /// `Option<u32>` and the caller-side `if let` already destructures
10466    /// the inner `u32` out, so the ctor takes the destructured scalar
10467    /// verbatim rather than re-wrapping it into an accessor call.
10468    ///
10469    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
10470    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
10471    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
10472    /// [`MeshPolicy::validate`] gate — extended here onto the
10473    /// third-firing cross-axis compound variant, whose multi-slot
10474    /// `{ retries: u32, max_failures: u32 }` shape does not fit that
10475    /// macro's one-`Copy`-scalar-per-variant arity. The one remaining
10476    /// cross-axis variant
10477    /// ([`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] on the
10478    /// two-slot `{ retries, rate }` envelope) carries a distinct
10479    /// substrate-primitive-projection shape (projecting through
10480    /// [`RateLimit::rate`] rather than
10481    /// [`CircuitBreaker::max_failures`]) and is folded on its own axis
10482    /// by its own per-variant ctor as that wire-up is lifted in a
10483    /// follow-up run.
10484    ///
10485    /// Every future consumer that wants to construct this variant
10486    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10487    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10488    /// webhook re-checking a per-tenant `:politicas` overlay's
10489    /// retries-vs-max-failures cross-axis invariant after a
10490    /// cluster-local `:politicas` override the MESH-COMPOSITION §III.2
10491    /// #3 roadmap acknowledges resolves an *effective* per-edge
10492    /// [`MeshPolicy`], a future per-`:contratos`-edge `:politicas`
10493    /// override the M4 CR resolver projects, an M4 per-cluster
10494    /// `:politicas`-cap resolver projecting a per-tenant per-axis
10495    /// ceiling into the same diagnostic shape — now reaches this
10496    /// variant through one call rather than re-inlining the open-coded
10497    /// struct-literal in lockstep with the one in-crate wire-up site.
10498    #[must_use]
10499    pub const fn policy_breaker_trips_before_retries_exhausted(
10500        retries: u32,
10501        cb: &CircuitBreaker,
10502    ) -> Self {
10503        Self::PolicyBreakerTripsBeforeRetriesExhausted {
10504            retries,
10505            max_failures: cb.max_failures(),
10506        }
10507    }
10508
10509    /// Construct an
10510    /// [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] naming
10511    /// the offending `:politicas :retries` and the paired `:politicas
10512    /// :rate-limit` `:rate` scalars under the fourth-firing (and last-
10513    /// remaining) cross-axis-violation gate at
10514    /// [`MeshPolicy::first_cross_axis_violation`], projecting the `rate`
10515    /// slot through the [`RateLimit::rate`] scalar accessor on the
10516    /// substrate primitive.
10517    ///
10518    /// Folds the uniform `{ retries, rate: rl.rate() }` two-slot
10519    /// `Copy`-`u32` struct-literal onto one substrate primitive so every
10520    /// wire-up on this variant reads through one dispatch rather than
10521    /// the pre-lift four-line struct-literal block. The `rl` borrow
10522    /// threads verbatim from the caller-side `if let (Some(retries),
10523    /// Some(rl)) = (self.retries(), self.rate_limit())` pair-destructure
10524    /// at the sole in-crate wire-up site inside
10525    /// [`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
10526    /// limit arm; `retries` threads verbatim from the paired
10527    /// [`MeshPolicy::retries`] accessor return already destructured out
10528    /// of the same `if let` pair. `const fn` preserves the pre-lift
10529    /// `Copy`-pass-through's zero-runtime-work property verbatim (both
10530    /// fields are `u32`, the [`RateLimit::rate`] accessor is itself
10531    /// `const fn`, and no `.to_string()` / `.into()` allocation lands on
10532    /// the ctor path).
10533    ///
10534    /// The `rate` slot is projected through [`RateLimit::rate`] (not
10535    /// spelled out as a bare `u32` parameter) so a future widening of
10536    /// the `:rate-limit` `:rate` axis — a per-`:contratos`-edge
10537    /// `:rate-limit` `:rate` override the MESH-COMPOSITION §III.2 #3
10538    /// roadmap acknowledges, a per-tenant `:rate` ceiling the M4
10539    /// per-cluster `:politicas`-cap resolver projects, a promotion of
10540    /// the plain `u32` token capacity to a richer
10541    /// `{max_tokens, tokens_per_fill}` tuple once Envoy's
10542    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
10543    /// axis comes into scope — reaches the diagnostic through one
10544    /// accessor swap rather than every wire-up in lockstep, matching
10545    /// the peer substrate-primitive-projection posture of
10546    /// [`AplicacaoError::policy_breaker_window_below_timeout`] (9b30c07,
10547    /// projecting through [`CircuitBreaker::window`] on the sibling
10548    /// two-slot `{ window, timeout }` first cross-axis envelope),
10549    /// [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
10550    /// (6bb4e46, projecting through [`RateLimit::rate`] /
10551    /// [`RateLimit::window`] / [`CircuitBreaker::max_failures`] /
10552    /// [`CircuitBreaker::window`] on the sibling four-slot second
10553    /// cross-axis envelope), and
10554    /// [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
10555    /// (f54c539, projecting through [`CircuitBreaker::max_failures`] on
10556    /// the sibling two-slot `{ retries, max_failures }` third cross-axis
10557    /// envelope). `retries` remains a bare `u32` parameter, matching
10558    /// the sibling third-arm ctor's bare `retries: u32` parameter
10559    /// discipline: [`MeshPolicy::retries`] returns `Option<u32>` and the
10560    /// caller-side `if let` already destructures the inner `u32` out, so
10561    /// the ctor takes the destructured scalar verbatim rather than
10562    /// re-wrapping it into an accessor call.
10563    ///
10564    /// Peer of the sibling per-axis [`aplicacao_policy_scalar_ctors!`]
10565    /// (7ef425e) macro that folds the eight one-slot per-`:politicas`
10566    /// `{ <field>: Copy-scalar }` envelopes on the per-axis
10567    /// [`MeshPolicy::validate`] gate — extended here onto the
10568    /// fourth-firing (and final) cross-axis compound variant, whose
10569    /// multi-slot `{ retries: u32, rate: u32 }` shape does not fit that
10570    /// macro's one-`Copy`-scalar-per-variant arity. After this lift all
10571    /// four cross-axis [`MeshPolicy::first_cross_axis_violation`] arms
10572    /// read through one substrate-primitive ctor dispatch each; the
10573    /// per-envelope compound cross-axis Policy* family closes on this
10574    /// variant.
10575    ///
10576    /// Every future consumer that wants to construct this variant
10577    /// outside [`MeshPolicy::first_cross_axis_violation`] — a deferred
10578    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
10579    /// webhook re-checking a per-tenant `:politicas` overlay's
10580    /// retries-vs-rate cross-axis invariant after a cluster-local
10581    /// `:politicas` override the MESH-COMPOSITION §III.2 #3 roadmap
10582    /// acknowledges resolves an *effective* per-edge [`MeshPolicy`], a
10583    /// future per-`:contratos`-edge `:politicas` override the M4 CR
10584    /// resolver projects, an M4 per-cluster `:politicas`-cap resolver
10585    /// projecting a per-tenant per-axis ceiling into the same diagnostic
10586    /// shape — now reaches this variant through one call rather than
10587    /// re-inlining the open-coded struct-literal in lockstep with the
10588    /// one in-crate wire-up site.
10589    #[must_use]
10590    pub const fn policy_rate_limit_cannot_admit_retry_burst(retries: u32, rl: &RateLimit) -> Self {
10591        Self::PolicyRateLimitCannotAdmitRetryBurst {
10592            retries,
10593            rate: rl.rate(),
10594        }
10595    }
10596
10597    /// Construct an [`AplicacaoError::ContratoCaixaInvalid`] naming the
10598    /// offending `:contratos <slot>` (`:de` / `:para`) and the value
10599    /// that broke the shared DNS-1123-label floor under the given
10600    /// `reason`. Folds the uniform `Self::ContratoCaixaInvalid { slot,
10601    /// caixa: caixa.to_string(), reason: reason.into() }` three-slot
10602    /// struct-literal onto one substrate primitive so every wire-up on
10603    /// this variant reads through one dispatch rather than the pre-lift
10604    /// six-line struct-literal block inside
10605    /// [`validate_contrato_caixa`]'s
10606    /// [`crate::render::require_valid_dns_1123_label`]
10607    /// `|reason| …` closure.
10608    ///
10609    /// Sibling of the per-axis [`aplicacao_field_reason_ctors!`]
10610    /// (981060b) macro-generated ctor family
10611    /// ([`AplicacaoError::membro_caixa_invalid`],
10612    /// [`AplicacaoError::entrada_para_invalid`],
10613    /// [`AplicacaoError::entrada_host_invalid`],
10614    /// [`AplicacaoError::entrada_path_invalid`],
10615    /// [`AplicacaoError::placement_cluster_invalid`],
10616    /// [`AplicacaoError::placement_affinity_invalid`],
10617    /// [`AplicacaoError::shard_key_invalid`]) — extends the "one typed
10618    /// dispatch per substrate primitive on every `{ <field>: String,
10619    /// reason: String }` per-axis parser-shaped envelope" discipline
10620    /// onto the sole unlifted three-slot `{ slot: &'static str, caixa:
10621    /// String, reason: String }` sibling whose extra `slot: &'static
10622    /// str` axis-tag distinguishes the two-arm `:de` / `:para` cascade
10623    /// on the per-`:contratos`-edge value axis and so does not fit the
10624    /// two-slot macro's arity.
10625    ///
10626    /// `slot` carries the kebab-case `:de` / `:para` tag verbatim
10627    /// (`&'static str` is `Copy`, no allocation), matching the caller-
10628    /// side [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
10629    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
10630    /// sole in-crate wire-up threads through. `reason: impl
10631    /// Into<String>` accepts both `&str` literals and the shared
10632    /// [`crate::render::require_valid_dns_1123_label`]-delivered
10633    /// owned-`String` return verbatim so the closure picks the ctor up
10634    /// without a per-arm wrapper transformation, matching the peer
10635    /// [`aplicacao_field_reason_ctors!`] family's `reason: impl
10636    /// Into<String>` bound. `#[must_use]` fires a compile warning at
10637    /// any wire-up that mistakenly discards the constructed error
10638    /// rather than routing it through `return Err(…)` / `.map_err(…)`
10639    /// / a closure return.
10640    ///
10641    /// Every future consumer that wants to construct this variant
10642    /// outside the current in-crate wire-up (the deferred
10643    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
10644    /// per-`:contratos`-edge admission validator projecting the same
10645    /// diagnostic through the caller-facing `slot: &'static str` tag,
10646    /// a future `feira validate --contratos` per-caixa admission verb,
10647    /// an M4 per-`:contratos`-edge pre-emitter running the same
10648    /// DNS-1123-label floor against a caller-supplied `:de` / `:para`
10649    /// pair before hitting the apiserver-side selector, an M4
10650    /// per-cluster contrato-cap resolver rejecting a cross-tenant
10651    /// selector projection into the same diagnostic shape) — now
10652    /// reaches this variant through one call rather than re-inlining
10653    /// the six-line struct-literal block in lockstep with the one
10654    /// in-crate wire-up site.
10655    #[must_use]
10656    pub fn contrato_caixa_invalid(
10657        slot: &'static str,
10658        caixa: &str,
10659        reason: impl Into<String>,
10660    ) -> Self {
10661        Self::ContratoCaixaInvalid {
10662            slot,
10663            caixa: caixa.to_string(),
10664            reason: reason.into(),
10665        }
10666    }
10667
10668    /// Construct an [`AplicacaoError::ContratoCaixaEmpty`] naming the
10669    /// offending `:contratos <slot>` (`:de` / `:para`) at which the
10670    /// caixa-reference value is the empty string. Folds the uniform
10671    /// `Self::ContratoCaixaEmpty { slot }` one-slot struct-literal onto
10672    /// one substrate primitive so the sole in-crate closure passed to
10673    /// [`crate::render::require_valid_dns_1123_label`] at
10674    /// [`validate_contrato_caixa`] on this variant reads through one
10675    /// dispatch rather than the pre-lift open-coded block. The `slot`
10676    /// label threads verbatim from the caller-side
10677    /// [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
10678    /// [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] `const` strings the
10679    /// wire-up feeds through [`validate_contrato_caixa`]'s
10680    /// `slot: &'static str` parameter.
10681    ///
10682    /// Sibling of the paired three-slot [`Self::contrato_caixa_invalid`]
10683    /// substrate primitive on the same
10684    /// [`crate::render::require_valid_dns_1123_label`] two-closure
10685    /// cascade — the empty-arm and invalid-arm now both reach the
10686    /// `AplicacaoError` envelope through one substrate primitive per
10687    /// typed variant, closing the pair. Same shape discipline as the
10688    /// peer [`crate::behavior::BehaviorError::empty_path`] one-slot
10689    /// `{ slot: &'static str }` sibling on the `BehaviorError`
10690    /// envelope's four-arm sandboxed-lisp-path cascade
10691    /// ([`crate::render::require_sandboxed_lisp_path`]) — extended here
10692    /// onto the sibling `AplicacaoError` envelope's two-arm
10693    /// DNS-1123-label cascade at the `:contratos <slot>` per-edge axis.
10694    ///
10695    /// `slot` stays `&'static str` (not `&str`) — every `:contratos
10696    /// <slot>` tag comes from the [`crate::render::CONTRATO_AUTHOR_KEY_*`]
10697    /// `const` roster carrying program-lifetime storage, matching the
10698    /// enum-field type and the [`validate_contrato_caixa`] wire-up's
10699    /// per-axis dispatch. A runtime-borrowed `&str` would silently
10700    /// downgrade the label lifetime and let a caller stash a
10701    /// non-`'static` borrow into the returned error. `#[must_use]` fires
10702    /// a compile warning at any wire-up that mistakenly discards the
10703    /// constructed error rather than routing it through `return Err(…)`
10704    /// / `.map_err(…)` / a closure return. `pub const fn` matches the
10705    /// peer per-envelope one-slot `Copy`-scalar ctor family discipline
10706    /// (`aplicacao_placement_scalar_ctors!`, `layout_nome_only_ctors!`,
10707    /// `dep_nome_only_ctors!`) so the ctor is usable in `const` position
10708    /// at every wire-up site.
10709    ///
10710    /// Every future consumer that wants to construct this variant
10711    /// outside the current in-crate wire-up (the deferred
10712    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
10713    /// per-`:contratos`-edge admission validator projecting the same
10714    /// diagnostic through the caller-facing `slot: &'static str` tag,
10715    /// a future `feira validate --contratos` per-caixa admission verb,
10716    /// an M4 per-`:contratos`-edge pre-emitter running the same
10717    /// DNS-1123-label floor's empty-arm against a caller-supplied
10718    /// `:de` / `:para` pair before hitting the apiserver-side selector,
10719    /// a per-`Caixa` overlay resolver rejecting an author-supplied
10720    /// `:contratos` overlay's empty `:de` / `:para` against a
10721    /// cluster-local snapshot) — now reaches this variant through one
10722    /// call rather than re-inlining the open-coded closure block in
10723    /// lockstep with the one in-crate wire-up site.
10724    #[must_use]
10725    pub const fn contrato_caixa_empty(slot: &'static str) -> Self {
10726        Self::ContratoCaixaEmpty { slot }
10727    }
10728}
10729
10730// Fold the seven `AplicacaoError::{MembroCaixa, EntradaPara, EntradaHost,
10731// EntradaPath, PlacementCluster, PlacementAffinity, ShardKey}Invalid
10732// { <field>: <val>.to_string(), reason: <expr> }` wire-up sites onto one
10733// substrate-primitive family per typed variant — the paired
10734// `{ <field>: String, reason: String }` two-slot sibling on
10735// [`AplicacaoError`] of the peer four-slot [`contrato_target_ctors!`]
10736// (14b81d5, `{ de, para, wit, expected }` on `ContratoWrongTarget` /
10737// `ContratoMissingTarget`) and the peer two-slot
10738// [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }` on `EmptyWit` /
10739// `ContratoEndpointEmpty` / `ContratoSubjectEmpty` / `ContratoSlotEmpty`)
10740// on the sibling per-`:contratos` envelopes, plus the peer four-family
10741// `LayoutError` ctor set ([`layout_violation_ctors!`] 131ca0d — 16
10742// variants on `{ caixa, issue }`, [`layout_slot_kind_ctors!`] 0419438 —
10743// 4 variants on `{ caixa, kind, slots }`, [`LayoutError::missing_entry`]
10744// 1b09f9d — 1 variant on `{ kind, path }`, [`layout_nome_only_ctors!`]
10745// 3fe3dd7 — 6 variants on `<Variant>(String)`) each carry on the
10746// sibling layout-side envelope.
10747//
10748// Every one of the seven wire-up sites — six under the per-axis
10749// `validate_*` wrappers around [`crate::render::require_valid_dns_1123_label`]
10750// (`validate_membro_caixa` on `MembroCaixaInvalid`, `validate_entrada_para`
10751// on `EntradaParaInvalid`, `validate_placement_cluster` on
10752// `PlacementClusterInvalid`, `validate_placement_affinity` on
10753// `PlacementAffinityInvalid`) plus [`crate::render::is_gateway_api_http_path`]
10754// (`validate_entrada_path` on `EntradaPathInvalid`), and two under
10755// [`validate_placement_shard_key`] (the length-cap arm and the per-byte
10756// printable-ASCII arm on `ShardKeyInvalid`) — plus the fourteen wire-up
10757// sites at [`validate_entrada_host`] (17dd504 already folded onto the
10758// pre-macro standalone `entrada_host_invalid` ctor, now converged onto
10759// the macro-generated ctor of the same name), opened the identical
10760// four-line `AplicacaoError::<Variant>Invalid
10761// { <field>: <val>.to_string(), reason: <expr> }` struct-literal against
10762// the local `<field>: &str` argument — the exact "same block re-inlined
10763// at every consumer" shape the PRIME DIRECTIVE names as a bug, on the
10764// same altitude the peer three `AplicacaoError` constructor families
10765// and the four peer `LayoutError` constructor families each closed on
10766// their sibling envelopes.
10767//
10768// The macro below generates one `#[must_use]` inherent constructor per
10769// variant of shape `fn <ctor>(<field>: &str, reason: impl Into<String>)
10770// -> AplicacaoError`, collapsing every site onto one dispatch per arm:
10771// `return Err(AplicacaoError::<ctor>(<val>, <reason>));` /
10772// `|reason| AplicacaoError::<ctor>(<val>, reason)`, byte-equal to the
10773// pre-lift struct-literal on the same `(<field>, reason)` pair. The
10774// uniform two-field construction (`<field>: <val>.to_string()`,
10775// `reason: reason.into()`) is spelled once — inside the macro — rather
10776// than at every wire-up site. The `reason: impl Into<String>` bound
10777// accepts both `&str` literals (with or without a trailing
10778// `.to_string()` at the caller) and `format!(…)` outputs verbatim so no
10779// wire-up site changes its per-arm diagnostic shape at the lift.
10780// `#[must_use]` fires a compile warning at any wire-up that mistakenly
10781// discards the constructed error rather than routing it through
10782// `return Err(…)` / `.map_err(…)` / a closure return.
10783//
10784// Every future consumer that wants to construct one of these seven
10785// variants outside the current in-crate wire-up sites (the deferred
10786// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-slot
10787// admission validators, a future `feira validate --<axis>` per-caixa
10788// admission verb, a per-`Certificate` SAN pre-emitter for cert-manager
10789// on `:entrada :host`, an M4 typed placement-engine per-cluster /
10790// per-affinity / per-shard-key pre-emitter, an M4 typed Gateway API
10791// per-path pre-emitter) reaches the variant through one call rather
10792// than re-inlining the four-line struct-literal block in lockstep with
10793// the current in-crate wire-up sites.
10794macro_rules! aplicacao_field_reason_ctors {
10795    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
10796        impl AplicacaoError {
10797            $(
10798                #[doc = concat!(
10799                    "Construct an [`AplicacaoError::",
10800                    stringify!($variant),
10801                    "`] naming the offending `",
10802                    stringify!($field),
10803                    "` under the given `reason`. Folds the uniform ",
10804                    "`{ ",
10805                    stringify!($field),
10806                    ": ",
10807                    stringify!($field),
10808                    ".to_string(), reason: reason.into() }` two-slot ",
10809                    "construction onto one substrate primitive so every ",
10810                    "wire-up on this variant reads through one dispatch ",
10811                    "rather than the pre-lift four-line struct-literal ",
10812                    "block. `reason` accepts both `&str` literals and ",
10813                    "`format!(…)` outputs through the `impl Into<String>` ",
10814                    "bound."
10815                )]
10816                #[must_use]
10817                pub fn $ctor($field: &str, reason: impl Into<String>) -> Self {
10818                    Self::$variant {
10819                        $field: $field.to_string(),
10820                        reason: reason.into(),
10821                    }
10822                }
10823            )*
10824        }
10825    };
10826}
10827
10828aplicacao_field_reason_ctors! {
10829    membro_caixa_invalid => MembroCaixaInvalid { caixa },
10830    entrada_para_invalid => EntradaParaInvalid { para },
10831    entrada_host_invalid => EntradaHostInvalid { host },
10832    entrada_path_invalid => EntradaPathInvalid { path },
10833    placement_cluster_invalid => PlacementClusterInvalid { cluster },
10834    placement_affinity_invalid => PlacementAffinityInvalid { affinity },
10835    shard_key_invalid => ShardKeyInvalid { shard_key },
10836}
10837
10838// Fold the four `AplicacaoError::Contrato{Endpoint,Subject,Slot,Wit}Invalid
10839// { de, para, <field>: <val>.to_string(), reason }` wire-up sites at
10840// [`WitContract::target`] onto one substrate-primitive family per typed
10841// variant — the paired `{ de: String, para: String, <field>: String,
10842// reason: String }` four-slot sibling on [`AplicacaoError`] of the peer
10843// four-slot [`contrato_target_ctors!`] (14b81d5, `{ de, para, wit,
10844// expected }` on `ContratoWrongTarget` / `ContratoMissingTarget`), the
10845// peer two-slot [`contrato_empty_pair_ctors!`] (8580068, `{ de, para }`
10846// on `EmptyWit` / `ContratoEndpointEmpty` / `ContratoSubjectEmpty` /
10847// `ContratoSlotEmpty`), and the peer two-slot
10848// [`aplicacao_field_reason_ctors!`] (981060b, `{ <field>: String,
10849// reason: String }` on `MembroCaixaInvalid` / `EntradaParaInvalid` /
10850// `EntradaHostInvalid` / `EntradaPathInvalid` / `PlacementClusterInvalid`
10851// / `PlacementAffinityInvalid` / `ShardKeyInvalid`) each carry on the
10852// sibling `AplicacaoError` envelopes, plus the peer four-family
10853// `LayoutError` ctor set on the sibling layout-side envelope.
10854//
10855// Every one of the four wire-up sites — four per-`:contratos` value-
10856// shape gates inside [`WitContract::target`] (the world-ref prefix
10857// [`crate::render::is_wit_world_ref`] failure on `:wit`, the HTTP arm's
10858// [`crate::render::is_gateway_api_http_path`] failure on `:endpoint`,
10859// the pub-sub arm's [`crate::render::is_nats_subject`] failure on
10860// `:subject`, the store arm's [`crate::render::is_wasi_keyvalue_slot`]
10861// failure on `:slot`) — opened the identical five-line
10862// `let (de, para) = self.edge_pair();
10863// return Err(AplicacaoError::Contrato<Field>Invalid { de, para,
10864// <field>: <val>.to_string(), reason });` block against the local
10865// [`WitContract::edge_pair`] composite-projection accessor and the
10866// per-arm `<val>: &str` argument — the exact "same block re-inlined at
10867// every consumer" shape the PRIME DIRECTIVE names as a bug, on the same
10868// altitude the peer three `AplicacaoError` constructor families and the
10869// four peer `LayoutError` constructor families each closed on their
10870// sibling envelopes. Absorbing `ContratoWitInvalid` onto the same
10871// macro closes the last unlifted `{ de, para, <field>: String, reason:
10872// String }` four-slot envelope inside `impl WitContract`, so every
10873// per-`:contratos` value-shape diagnostic on [`AplicacaoError`] now
10874// reads through this one substrate primitive.
10875//
10876// The macro below generates one `#[must_use]` inherent constructor per
10877// variant of shape `fn <ctor>(edge: (String, String), <field>: &str,
10878// reason: impl Into<String>) -> AplicacaoError`, collapsing the four
10879// sites onto one dispatch per arm:
10880// `return Err(AplicacaoError::<ctor>(self.edge_pair(), <val>, reason));`,
10881// byte-equal to the pre-lift struct-literal on the same
10882// `(edge_pair, <val>, reason)` triple. The uniform four-field
10883// construction (`de, para` pair-destructure onto same-named fields +
10884// `<field>: <val>.to_string()` + `reason: reason.into()`) is spelled
10885// once — inside the macro — rather than at every wire-up site. The
10886// `reason: impl Into<String>` bound accepts both `&str` literals and
10887// `format!(…)` outputs verbatim so no wire-up site changes its per-arm
10888// diagnostic shape at the lift, matching the peer
10889// [`aplicacao_field_reason_ctors!`] bound on the sibling two-slot
10890// envelope. `#[must_use]` fires a compile warning at any wire-up that
10891// mistakenly discards the constructed error.
10892//
10893// Every future consumer that wants to construct one of these four
10894// variants outside [`WitContract::target`] (a deferred
10895// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-`:contratos`
10896// admission validator raising per-payload value-shape diagnostics on
10897// unrecognized `:wit` / `:endpoint` / `:subject` / `:slot` shapes, a
10898// future `feira validate --contratos` per-caixa admission verb, an M4
10899// typed WIT-registry-driven per-arm pre-emitter probing each declared
10900// `:endpoint` / `:subject` / `:slot` payload against a canonical
10901// per-arm shape gate, a per-`Certificate` SAN pre-emitter for
10902// cert-manager on the `:endpoint` axis, an M4 typed Cilium L7 rule
10903// pre-emitter probing each `:endpoint` against the same shared
10904// HTTPPathMatch grammar) reaches the variant through one call rather
10905// than re-inlining the five-line pair-destructure + struct-literal
10906// block in lockstep with the four in-crate wire-up sites.
10907macro_rules! contrato_pair_value_reason_ctors {
10908    ($($ctor:ident => $variant:ident { $field:ident }),* $(,)?) => {
10909        impl AplicacaoError {
10910            $(
10911                #[doc = concat!(
10912                    "Construct an [`AplicacaoError::",
10913                    stringify!($variant),
10914                    "`] naming the offending edge `(de, para)` pair, the ",
10915                    "per-payload `",
10916                    stringify!($field),
10917                    "` value, and the parser-shaped `reason`. Folds the ",
10918                    "uniform `{ de, para, ",
10919                    stringify!($field),
10920                    ": ",
10921                    stringify!($field),
10922                    ".to_string(), reason: reason.into() }` four-slot ",
10923                    "construction onto one substrate primitive so every ",
10924                    "wire-up on this variant reads through one dispatch ",
10925                    "rather than the pre-lift five-line pair-destructure ",
10926                    "+ struct-literal block. The `edge` pair threads ",
10927                    "verbatim from [`WitContract::edge_pair`] at the ",
10928                    "call site; `reason` accepts both `&str` literals ",
10929                    "and `format!(…)` outputs through the `impl ",
10930                    "Into<String>` bound."
10931                )]
10932                #[must_use]
10933                pub fn $ctor(edge: (String, String), $field: &str, reason: impl Into<String>) -> Self {
10934                    let (de, para) = edge;
10935                    Self::$variant {
10936                        de,
10937                        para,
10938                        $field: $field.to_string(),
10939                        reason: reason.into(),
10940                    }
10941                }
10942            )*
10943        }
10944    };
10945}
10946
10947contrato_pair_value_reason_ctors! {
10948    contrato_endpoint_invalid => ContratoEndpointInvalid { endpoint },
10949    contrato_subject_invalid => ContratoSubjectInvalid { subject },
10950    contrato_slot_invalid => ContratoSlotInvalid { slot },
10951    contrato_wit_invalid => ContratoWitInvalid { wit },
10952}
10953
10954// Fold the five `AplicacaoError::{ContratoMemberMissing, MembroVersaoEmpty,
10955// MembroDuplicate, MembroIsSelfAplicacao} { caixa: <&str>.to_string() }`
10956// caixa-only struct-variant wire-up sites at
10957// [`WitContract::require_endpoints_in`] (two sites, the `:contratos :de` and
10958// `:contratos :para` arms of `ContratoMemberMissing`),
10959// [`AplicacaoSpec::validate_membros`] (two sites, the empty-`:versao` arm of
10960// `MembroVersaoEmpty` and the per-`:membros` dedup arm of `MembroDuplicate`),
10961// and [`validate_no_self_membership`] (one site, the parent-`:nome`
10962// self-membership arm of `MembroIsSelfAplicacao`) onto one substrate primitive
10963// per typed variant — the sibling on the M3 mesh `AplicacaoError` envelope of
10964// the peer [`crate::supervisor::supervisor_caixa_only_ctors!`] macro (db09650,
10965// three variants on `{ caixa: String }` at
10966// [`crate::SupervisorSpec::validate_children`] and
10967// [`crate::supervisor::validate_no_self_supervision`]) on the sibling M2
10968// `SupervisorError` envelope, extending the same "one substrate primitive per
10969// typed variant on the single-slot `{ <ident>: String }` envelope shape" fold
10970// discipline onto the M3 mesh side. Peers on peer envelopes: the M2 sibling
10971// [`crate::behavior::behavior_slot_path_ctors!`] (67c31ec, 3 variants on
10972// `{ slot: &'static str, path: PathBuf }`) two-slot fold on the `:behavior`
10973// envelope; the M2 sibling [`crate::upgrade::upgrade_from_script_ctors!`]
10974// (8e67041, 3 variants on `{ from: String, script: PathBuf }`) and
10975// [`crate::upgrade::upgrade_script_only_ctors!`] (7468ca9, 3 variants on
10976// `{ script: PathBuf }`) two folds on the sibling `:upgrade-from` envelope;
10977// the sibling [`crate::dep::dep_nome_only_ctors!`] (792aa92, 5 variants on
10978// `{ nome: String }`), [`crate::dep::fonte_caminho_ctors!`] (f85f145, 11
10979// variants on `{ nome, caminho }`), and
10980// [`crate::dep::fonte_caminho_byte_ctors!`] (0e35793, 12 variants on
10981// `{ nome, caminho, byte }`) folds on the sibling `DepError` envelope; the
10982// peer three `AplicacaoError` sub-family folds already lifted here
10983// ([`contrato_target_ctors!`] 14b81d5, [`contrato_empty_pair_ctors!`] 8580068,
10984// [`aplicacao_field_reason_ctors!`] 981060b,
10985// [`contrato_pair_value_reason_ctors!`] 14e13f1); the peer four `LayoutError`
10986// families ([`crate::layout::layout_violation_ctors!`] 131ca0d,
10987// [`crate::layout::layout_slot_kind_ctors!`] 0419438,
10988// [`crate::LayoutError::missing_entry`] 1b09f9d,
10989// [`crate::layout::layout_nome_only_ctors!`] 3fe3dd7); and the three
10990// [`crate::limits::limits_codec_value_*_ctors!`] codec families (81c856c).
10991//
10992// Each of the five wire-up sites on this shape (two on `ContratoMemberMissing`
10993// at the per-`:contratos :de`/`:para` unknown-member arms, one on
10994// `MembroVersaoEmpty` at the per-`:membros` empty-semver-requirement arm, one
10995// on `MembroDuplicate` at the per-`:membros` dedup arm, one on
10996// `MembroIsSelfAplicacao` at the parent-`:nome` self-membership arm) opened
10997// the identical `AplicacaoError::<Variant> { caixa: <&str>.to_string() }`
10998// three-line struct-literal against a caller-side `&str` — the exact "same
10999// block re-inlined at every consumer" shape the PRIME DIRECTIVE names as a
11000// bug, on the same altitude the peer `SupervisorError` /
11001// `AplicacaoError` (three prior sub-families) / `DepError` / `LayoutError` /
11002// `UpgradeError` / `BehaviorError` / `LimitsError` families each closed on
11003// their sibling envelopes. The four variants share one `{ caixa: String }`
11004// shape, so the fold routes each wire-up site through one dispatch per typed
11005// variant.
11006//
11007// The macro below generates one `#[must_use]` inherent constructor per
11008// variant of shape `fn <ctor>(caixa: &str) -> AplicacaoError`, so every
11009// wire-up site collapses onto one dispatch:
11010// `AplicacaoError::<ctor>(<&str>)`, byte-equal to the pre-lift struct-literal
11011// on the same `&str` fixture. The uniform one-field construction
11012// (`caixa: caixa.to_string()`) is spelled once — inside the macro — rather
11013// than at every wire-up site. Every constructor is `#[must_use]` so a caller
11014// who mistakenly discards the constructed error trips a compile warning at
11015// the wire-up site.
11016//
11017// Every future consumer that wants to construct one of these four variants
11018// outside the current in-crate wire-up sites — a deferred
11019// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
11020// re-checking one added/renamed `:membros` entry against the sibling
11021// `:contratos` graph, a future `feira validate --membros` per-caixa admission
11022// verb re-checking each declared `:membros` entry's `:caixa` name against the
11023// same axes, a per-tenant per-`Aplicacao` overlay resolver rejecting a
11024// duplicate / self-referencing / unknown-membered `:contratos` entry against
11025// a cluster-local snapshot the M4 CR materializer projects — now reaches each
11026// variant through one call rather than re-inlining the three-line
11027// struct-literal in lockstep with the five in-crate wire-up sites.
11028macro_rules! aplicacao_caixa_only_ctors {
11029    ($($ctor:ident => $variant:ident),* $(,)?) => {
11030        impl AplicacaoError {
11031            $(
11032                #[doc = concat!(
11033                    "Construct an [`AplicacaoError::",
11034                    stringify!($variant),
11035                    "`] naming the offending `:membros :caixa` (or ",
11036                    "parent `:nome`, on the self-membership arm; or ",
11037                    "`:contratos :de`/`:para`, on the unknown-member ",
11038                    "arm). Folds the uniform `Self::",
11039                    stringify!($variant),
11040                    " { caixa: caixa.to_string() }` one-field ",
11041                    "struct-literal onto one substrate primitive so ",
11042                    "every wire-up on this variant reads through one ",
11043                    "dispatch rather than the pre-lift three-line ",
11044                    "open-coded struct-literal block."
11045                )]
11046                #[must_use]
11047                pub fn $ctor(caixa: &str) -> Self {
11048                    Self::$variant { caixa: caixa.to_string() }
11049                }
11050            )*
11051        }
11052    };
11053}
11054
11055aplicacao_caixa_only_ctors! {
11056    contrato_member_missing => ContratoMemberMissing,
11057    membro_versao_empty => MembroVersaoEmpty,
11058    membro_duplicate => MembroDuplicate,
11059    membro_is_self_aplicacao => MembroIsSelfAplicacao,
11060}
11061
11062// Fold the three `AplicacaoError::{EntradaPathNotAbsolute,
11063// EntradaPathDuplicate} { path: <val>.to_string() | <val>.clone() }` wire-up
11064// sites onto one substrate-primitive family per typed variant — the direct
11065// per-`:entrada :paths` value-shape sibling of the peer
11066// `aplicacao_caixa_only_ctors!` (d9f6867, `{ caixa: String }` on
11067// `ContratoMemberMissing` / `MembroVersaoEmpty` / `MembroDuplicate` /
11068// `MembroIsSelfAplicacao`) on the sibling per-`:membros :caixa` envelope, and
11069// per-`:entrada :para` sibling of the peer `contrato_empty_pair_ctors!`
11070// (8580068, `{ de, para }` on `EmptyWit` / `ContratoEndpointEmpty` /
11071// `ContratoSubjectEmpty` / `ContratoSlotEmpty`) on the per-`:contratos` edge
11072// envelope. Same shape family as the [`crate::dep::dep_nome_only_ctors!`]
11073// (792aa92, `{ nome: String }` on five `DepError` variants) fold on the peer
11074// `:deps` envelope — every single-`String`-slot error family in caixa-core
11075// now reaches through one substrate primitive per typed variant.
11076//
11077// The three wire-up sites — one under [`validate_entrada_path`]'s
11078// leading-slash grammar arm (`EntradaPathNotAbsolute` against
11079// `path: &str`), one under the per-`:entrada :paths` loop's identical
11080// arm (`EntradaPathNotAbsolute` against a `&String` head via `.clone()`),
11081// and one under the per-`:entrada :paths` loop's dedup arm
11082// (`EntradaPathDuplicate` against the same `&String` via
11083// [`crate::render::insert_first_seen`]'s ctor closure) — opened the identical
11084// `AplicacaoError::EntradaPath<Variant> { path: <val>.to_string() | .clone() }`
11085// three-line struct-literal against a caller-side `&str` / `&String`, the
11086// exact "same block re-inlined at every consumer" shape the PRIME DIRECTIVE
11087// names as a bug. Every one of the compile-time guarantees in
11088// MESH-COMPOSITION.md §III.3 (a `:entrada :paths` entry whose value doesn't
11089// start with `/` becomes a caixa-build error, not a Gateway API webhook
11090// rejection at `kubectl apply` time; a duplicated `:entrada :paths` entry
11091// becomes a caixa-build error, not a silent last-writer-wins render) now
11092// routes through one dispatch per typed variant at every emit site.
11093//
11094// The macro below generates one `#[must_use]` inherent constructor per
11095// variant of shape `fn <ctor>(path: &str) -> AplicacaoError`, collapsing
11096// every wire-up site onto one dispatch:
11097// `AplicacaoError::<ctor>(<path>)` (byte-equal to the pre-lift struct-literal
11098// on the same `&str` fixture) or the `&String` sites through
11099// `p.as_str()` (byte-equal on the same slice-view). The uniform one-field
11100// construction (`path: path.to_string()`) is spelled once — inside the
11101// macro — rather than at every wire-up site. Every ctor is `#[must_use]` so
11102// a caller who mistakenly discards the constructed error trips a compile
11103// warning at the wire-up site.
11104//
11105// Every future consumer that wants to construct one of these two variants
11106// outside the current in-crate wire-up sites — a deferred
11107// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook
11108// per-`:entrada :paths` re-check against a cluster-local Gateway API
11109// snapshot, a future `feira validate --entrada` per-caixa admission verb
11110// re-checking each declared `:paths` entry against the same axes, a
11111// per-tenant per-`Aplicacao` overlay resolver rejecting a
11112// duplicate / non-absolute `:paths` entry against a cluster-local Gateway
11113// snapshot the M4 CR materializer projects — now reaches each variant
11114// through one call rather than re-inlining the three-line struct-literal in
11115// lockstep with the three in-crate wire-up sites.
11116macro_rules! aplicacao_path_only_ctors {
11117    ($($ctor:ident => $variant:ident),* $(,)?) => {
11118        impl AplicacaoError {
11119            $(
11120                #[doc = concat!(
11121                    "Construct an [`AplicacaoError::",
11122                    stringify!($variant),
11123                    "`] naming the offending `:entrada :paths` entry. ",
11124                    "Folds the uniform `Self::",
11125                    stringify!($variant),
11126                    " { path: path.to_string() }` one-field ",
11127                    "struct-literal onto one substrate primitive so ",
11128                    "every wire-up on this variant reads through one ",
11129                    "dispatch rather than the pre-lift three-line ",
11130                    "open-coded struct-literal block."
11131                )]
11132                #[must_use]
11133                pub fn $ctor(path: &str) -> Self {
11134                    Self::$variant { path: path.to_string() }
11135                }
11136            )*
11137        }
11138    };
11139}
11140
11141aplicacao_path_only_ctors! {
11142    entrada_path_not_absolute => EntradaPathNotAbsolute,
11143    entrada_path_duplicate => EntradaPathDuplicate,
11144}
11145
11146// Fold the eight `AplicacaoError::Policy<Slot><Axis> { <field>: <val> }`
11147// one-slot `Copy`-scalar wire-up sites at [`MeshPolicy::validate`] onto one
11148// substrate-primitive family per typed variant — the per-`:politicas` copy-
11149// scalar `{ timeout | retries | max_failures | window | rate: Duration | u32 }`
11150// sibling of the peer per-`:membros :caixa` [`aplicacao_caixa_only_ctors!`]
11151// (d9f6867, `{ caixa: String }` on `ContratoMemberMissing` /
11152// `MembroVersaoEmpty` / `MembroDuplicate` / `MembroIsSelfAplicacao`) and the
11153// peer per-`:entrada :paths` [`aplicacao_path_only_ctors!`] (3ba8de6,
11154// `{ path: String }` on `EntradaPathNotAbsolute` / `EntradaPathDuplicate`) on
11155// the `String`-slot axis, and the peer per-`:politicas` cross-axis
11156// [`AplicacaoError::Policy*`] cascade [`MeshPolicy::first_cross_axis_violation`]
11157// carries at line 3064 on the same M3 mesh envelope.
11158//
11159// The eight wire-up sites inside [`MeshPolicy::validate`] at lines 3170-3218
11160// each opened the identical `|<slot>| AplicacaoError::Policy<Slot><Axis>
11161// { <slot> }` one-line struct-literal closure against the caller-side
11162// `<slot>: <ty>` argument that the shared
11163// [`crate::render::require_positive_bounded_u32`] /
11164// [`crate::render::require_positive_canonical_bounded_duration`] gate rebinds
11165// verbatim under the `impl FnOnce(u32) -> AplicacaoError` /
11166// `impl FnOnce(Duration) -> AplicacaoError` bracket-closure slots (plus one
11167// direct `return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical
11168// { window: rl.window() })` at the `:rate-limit :window` canonical-form arm
11169// on line 3211) — the exact "same one-line struct-literal re-inlined at every
11170// consumer" shape the PRIME DIRECTIVE names as a bug, on the last remaining
11171// per-`:politicas` per-axis `AplicacaoError` variant family that had not yet
11172// been folded onto a substrate primitive.
11173//
11174// The macro below generates one `#[must_use] pub const fn <ctor>(<field>: <ty>)
11175// -> AplicacaoError` per variant of shape `Self::<variant> { <field> }`,
11176// collapsing every wire-up onto either one direct dispatch
11177// (`return Err(AplicacaoError::<ctor>(<val>))`, byte-equal to the pre-lift
11178// struct-literal on the same `Copy`-`<ty>` fixture) or one bare function
11179// pointer at the `impl FnOnce(<ty>) -> AplicacaoError` bracket-closure slot
11180// (`AplicacaoError::<ctor>` in the position where every pre-lift site spelled
11181// `|<slot>| AplicacaoError::<Variant> { <slot> }`) — Rust's function-pointer-
11182// to-`FnOnce` coercion on any `fn(<ty>) -> AplicacaoError` inherent
11183// constructor with matching arity and signature. The `const fn` qualifier
11184// preserves the pre-lift `Copy`-pass-through's zero-runtime-work property
11185// verbatim (no `.to_string()` / `.into()` allocation, no branching); the
11186// per-variant `$field:ident` axis re-uses the enum's canonical field name so
11187// the generated ctor's parameter name matches every wire-up's local binding
11188// (`|timeout|` calls `policy_timeout_not_canonical(timeout)`, etc.), matching
11189// the peer [`aplicacao_field_reason_ctors!`] / [`aplicacao_caixa_only_ctors!`]
11190// / [`aplicacao_path_only_ctors!`] convention. `#[must_use]` fires a compile
11191// warning at any wire-up that mistakenly discards the constructed error, on
11192// the same footing as every sibling `AplicacaoError` / `DepError` /
11193// `SupervisorError` / `LayoutError` / `LimitsError` / `BehaviorError` /
11194// `UpgradeError` ctor macro (14b81d5 / 8580068 / 981060b / 14e13f1 / 81c856c
11195// / 8e67041 / 7468ca9 / 67c31ec / d2ef2ec / f85f145 / 0e35793 / 792aa92 /
11196// 6f5e0cd / 3fe3dd7 / 1b09f9d / 131ca0d / 0419438).
11197//
11198// Every future consumer that wants to construct one of these eight variants
11199// outside [`MeshPolicy::validate`] — a deferred
11200// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission webhook re-
11201// checking each `:politicas` axis against a cluster-local `:politicas` cap
11202// overlay, a future per-`:contratos`-edge `:politicas` override the
11203// MESH-COMPOSITION §III.2 #3 roadmap acknowledges resolving an *effective*
11204// per-edge [`MeshPolicy`] and emitting the same per-axis diagnostic on the
11205// same input as `feira build`, an M4 per-cluster `:politicas`-cap resolver
11206// projecting a per-tenant per-axis ceiling into the same diagnostic shape,
11207// a future `feira validate --politicas` per-caixa admission verb re-checking
11208// each declared per-axis value against the same bounds — now reaches each
11209// variant through one call rather than re-inlining the one-line struct-
11210// literal in lockstep with the seven `MeshPolicy::validate` wire-up sites,
11211// which is exactly the invariant every prior ctor-macro lift already closed
11212// on its sibling envelope. Closes the last remaining per-`:politicas`
11213// per-axis `AplicacaoError` variant family that had not yet been folded onto
11214// a substrate primitive; the compound cross-axis variants
11215// ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`] / `*RateLimit` /
11216// `*RetriesBurst`) each carry a distinct multi-slot field shape and are folded
11217// on a separate axis by [`MeshPolicy::first_cross_axis_violation`].
11218macro_rules! aplicacao_policy_scalar_ctors {
11219    ($($ctor:ident => $variant:ident { $field:ident: $ty:ty }),* $(,)?) => {
11220        impl AplicacaoError {
11221            $(
11222                #[doc = concat!(
11223                    "Construct an [`AplicacaoError::",
11224                    stringify!($variant),
11225                    "`] naming the offending per-`:politicas` `",
11226                    stringify!($field),
11227                    "` scalar. Folds the uniform `Self::",
11228                    stringify!($variant),
11229                    " { ",
11230                    stringify!($field),
11231                    " }` one-field `Copy`-pass-through struct-literal onto ",
11232                    "one substrate primitive so every per-axis wire-up on ",
11233                    "this variant reads through one dispatch — as a direct ",
11234                    "call (`AplicacaoError::",
11235                    stringify!($ctor),
11236                    "(<val>)`, byte-equal to the pre-lift struct-literal on ",
11237                    "the same `Copy`-`",
11238                    stringify!($ty),
11239                    "` fixture) or as a bare function pointer in the ",
11240                    "`impl FnOnce(",
11241                    stringify!($ty),
11242                    ") -> AplicacaoError` bracket-closure slot every ",
11243                    "`crate::render::require_positive_bounded_*` / ",
11244                    "`crate::render::require_positive_canonical_bounded_*` ",
11245                    "gate carries — rather than the pre-lift open-coded ",
11246                    "one-line closure over the same one-field struct-",
11247                    "literal. `const fn` preserves the `Copy`-pass-through's ",
11248                    "zero-runtime-work property verbatim."
11249                )]
11250                #[must_use]
11251                pub const fn $ctor($field: $ty) -> Self {
11252                    Self::$variant { $field }
11253                }
11254            )*
11255        }
11256    };
11257}
11258
11259aplicacao_policy_scalar_ctors! {
11260    policy_timeout_not_canonical => PolicyTimeoutNotCanonical { timeout: Duration },
11261    policy_timeout_exceeds_cap => PolicyTimeoutExceedsCap { timeout: Duration },
11262    policy_retries_exceeds_cap => PolicyRetriesExceedsCap { retries: u32 },
11263    policy_breaker_max_failures_exceeds_cap =>
11264        PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
11265    policy_breaker_window_not_canonical =>
11266        PolicyBreakerWindowNotCanonical { window: Duration },
11267    policy_breaker_window_exceeds_cap =>
11268        PolicyBreakerWindowExceedsCap { window: Duration },
11269    policy_rate_limit_exceeds_cap => PolicyRateLimitExceedsCap { rate: u32 },
11270    policy_rate_limit_window_not_canonical =>
11271        PolicyRateLimitWindowNotCanonical { window: Duration },
11272}
11273
11274#[cfg(test)]
11275mod tests {
11276    use super::*;
11277
11278    fn membro(name: &str, ver: &str) -> Membro {
11279        Membro {
11280            caixa: name.into(),
11281            versao: ver.into(),
11282        }
11283    }
11284
11285    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
11286        WitContract {
11287            de: de.into(),
11288            para: para.into(),
11289            wit: "wasi:http/proxy".into(),
11290            endpoint: Some(ep.into()),
11291            subject: None,
11292            slot: None,
11293        }
11294    }
11295
11296    fn three_member_spec() -> AplicacaoSpec {
11297        AplicacaoSpec {
11298            membros: vec![
11299                membro("catalog", "^0.1"),
11300                membro("cart", "^0.1"),
11301                membro("payment", "^0.2"),
11302            ],
11303            contratos: vec![
11304                contract_http("cart", "catalog", "/products/:id"),
11305                contract_http("cart", "payment", "/charge"),
11306            ],
11307            politicas: MeshPolicy {
11308                timeout: Some(Duration::from_secs(30)),
11309                retries: Some(3),
11310                mtls_required: Some(true),
11311                ..Default::default()
11312            },
11313            placement: Placement {
11314                estrategia: PlacementStrategy::Replicated,
11315                clusters: vec!["rio".into(), "mar".into()],
11316                affinity: Some("data-locality".into()),
11317                shard_key: None,
11318            },
11319            entrada: Some(Entrada {
11320                host: "checkout.quero.cloud".into(),
11321                para: "cart".into(),
11322                paths: vec!["/api/cart".into(), "/api/products".into()],
11323                port: 8080,
11324            }),
11325        }
11326    }
11327
11328    #[test]
11329    fn happy_path_validates() {
11330        three_member_spec().validate().unwrap();
11331    }
11332
11333    #[test]
11334    fn rejects_empty_membros() {
11335        let mut s = three_member_spec();
11336        s.membros = vec![];
11337        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
11338    }
11339
11340    #[test]
11341    fn rejects_empty_membro_caixa() {
11342        // A `:caixa ""` entry has no name to render into programs.yaml
11343        // and no caixa.lisp to resolve at lacre time.
11344        let mut s = three_member_spec();
11345        s.membros[1].caixa = String::new();
11346        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
11347    }
11348
11349    #[test]
11350    fn rejects_empty_membro_versao() {
11351        // A `:versao ""` entry can't pin a semver constraint, so the
11352        // lacre pipeline fails far from the source.
11353        let mut s = three_member_spec();
11354        s.membros[2].versao = String::new();
11355        let err = s.validate().unwrap_err();
11356        assert!(
11357            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
11358            "got {err:?}"
11359        );
11360    }
11361
11362    #[test]
11363    fn rejects_duplicate_membro_caixa() {
11364        // Two `:membros` entries with the same `:caixa` collapse to one
11365        // node in the membership HashSet, which masks `:contratos`
11366        // membership errors and produces duplicate programs.yaml entries.
11367        let mut s = three_member_spec();
11368        s.membros.push(membro("cart", "^0.2"));
11369        let err = s.validate().unwrap_err();
11370        assert!(
11371            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
11372            "got {err:?}"
11373        );
11374    }
11375
11376    #[test]
11377    fn rejects_invalid_membro_versao_requirement() {
11378        // The fail-before-pass-after pin: a non-empty but malformed
11379        // semver requirement (`"^bad-version"`) silently passed
11380        // `validate()` on every pre-gate codebase because the prior
11381        // shape only refused the empty string. The parse failure
11382        // surfaced far downstream at lacre-resolve time with a
11383        // `semver::Error` that didn't name which `:membros` entry
11384        // carried the typo. The new gate moves the check to caixa-build
11385        // time at the source caixa.lisp.
11386        let mut s = three_member_spec();
11387        s.membros[2].versao = "^bad-version".into();
11388        let err = s.validate().unwrap_err();
11389        assert!(
11390            matches!(
11391                err,
11392                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11393                    if caixa == "payment" && versao == "^bad-version"
11394            ),
11395            "got {err:?}"
11396        );
11397    }
11398
11399    #[test]
11400    fn rejects_membro_versao_with_double_caret_typo() {
11401        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
11402        // Cargo-shaped requirement on first glance but fails the parser
11403        // because semver doesn't accept stacked operators. Pin this
11404        // adjacent-shape footgun explicitly so a future relaxation that
11405        // accepts "looks-canonical-but-isn't" forms surfaces here.
11406        let mut s = three_member_spec();
11407        s.membros[0].versao = "^^0.1".into();
11408        let err = s.validate().unwrap_err();
11409        assert!(
11410            matches!(
11411                err,
11412                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11413                    if caixa == "catalog" && versao == "^^0.1"
11414            ),
11415            "got {err:?}"
11416        );
11417    }
11418
11419    #[test]
11420    fn rejects_membro_versao_with_v_prefixed_tag() {
11421        // `"v0.1"` is the canonical "git-tag-shape leaking into the
11422        // semver requirement slot" typo — an author copies the
11423        // publish-side git-tag string verbatim into `:versao`, but
11424        // Cargo's semver parser rejects the leading `v` (only digits +
11425        // canonical operators are valid in the major-version
11426        // position). The gate's diagnostic names which member entry
11427        // carried the v-prefix so the fix is one edit, not a grep
11428        // through every member's `:versao`. (Note: bare `x`-glob
11429        // shorthands like `^0.1.x` are *accepted* by the semver crate
11430        // as an `*` wildcard on the patch axis — they're a Cargo-side
11431        // valid shape, not a typo, so the gate intentionally lets them
11432        // through.)
11433        let mut s = three_member_spec();
11434        s.membros[1].versao = "v0.1".into();
11435        let err = s.validate().unwrap_err();
11436        assert!(
11437            matches!(
11438                err,
11439                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
11440                    if caixa == "cart" && versao == "v0.1"
11441            ),
11442            "got {err:?}"
11443        );
11444    }
11445
11446    #[test]
11447    fn accepts_canonical_membro_versao_forms() {
11448        // The four Cargo-shaped requirement forms `:deps :versao`
11449        // already accepts via `crate::parse_requirement` must pass the
11450        // membros gate without re-validating at the resolver layer.
11451        // Pin every leg so a future tightening of the canonical set
11452        // surfaces here as a test failure.
11453        for form in [
11454            "^0.1",      // caret — minor-range pin (the most common shape)
11455            "~0.1.2",    // tilde — patch-range pin
11456            "0.1.0",     // exact — single-version pin
11457            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
11458            ">=0.1, <2", // multi-range — comma-separated comparators
11459        ] {
11460            let mut s = three_member_spec();
11461            for m in &mut s.membros {
11462                m.versao = form.into();
11463            }
11464            s.validate()
11465                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
11466        }
11467    }
11468
11469    #[test]
11470    fn membro_versao_empty_takes_precedence_over_invalid() {
11471        // Order pin: the existing `MembroVersaoEmpty` diagnostic
11472        // (which doesn't try to parse) fires before the new
11473        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
11474        // `:versao` keeps its narrower error message — `parse_requirement`
11475        // would also reject `""`, but the empty-string arm is the more
11476        // self-locating diagnostic for the author.
11477        let mut s = three_member_spec();
11478        s.membros[1].versao = String::new();
11479        let err = s.validate().unwrap_err();
11480        assert!(
11481            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
11482            "got {err:?}"
11483        );
11484    }
11485
11486    #[test]
11487    fn membro_versao_invalid_fires_before_duplicate_check() {
11488        // Order pin: a malformed requirement on a non-duplicate entry
11489        // surfaces *its own* diagnostic (which names the offending
11490        // `:versao` string), even when a later entry would otherwise
11491        // collapse onto an earlier name. The per-entry shape gate runs
11492        // inline before the duplicate-key insert, parallel to
11493        // `membros_validation_runs_before_contratos_membership_check`
11494        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
11495        let mut s = three_member_spec();
11496        s.membros[0].versao = "^bad".into();
11497        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
11498        let err = s.validate().unwrap_err();
11499        assert!(
11500            matches!(
11501                err,
11502                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
11503            ),
11504            "got {err:?}"
11505        );
11506    }
11507
11508    #[test]
11509    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
11510        // The diagnostic-shape pin: the error names the offending
11511        // `:versao` value verbatim so the author can grep their
11512        // caixa.lisp without re-running the build, and carries a
11513        // non-empty `reason` from `semver::VersionReq::parse` so the
11514        // parser's own wording flows through to the diagnostic.
11515        let mut s = three_member_spec();
11516        s.membros[2].versao = "not-a-req".into();
11517        let err = s.validate().unwrap_err();
11518        let AplicacaoError::MembroVersaoInvalid {
11519            caixa,
11520            versao,
11521            reason,
11522        } = err
11523        else {
11524            panic!("expected MembroVersaoInvalid, got other variant");
11525        };
11526        assert_eq!(caixa, "payment");
11527        assert_eq!(versao, "not-a-req");
11528        assert!(
11529            !reason.is_empty(),
11530            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
11531        );
11532    }
11533
11534    #[test]
11535    fn membro_versao_invalid_runs_before_contratos_check() {
11536        // A malformed `:versao` on any member must surface its own
11537        // diagnostic (which names *which* member to fix) before any
11538        // `:contratos` membership lookup raises `ContratoMemberMissing`.
11539        // The `:contratos` gate runs after `validate_membros`, so this
11540        // is structurally guaranteed — pin it explicitly so a future
11541        // refactor that reorders the gates surfaces here.
11542        let mut s = three_member_spec();
11543        s.membros[1].versao = "^^0.1".into();
11544        // Add a contrato whose `:para` doesn't exist — would normally
11545        // raise ContratoMemberMissing at the membership lookup, but
11546        // the membros gate must fire first.
11547        s.contratos
11548            .push(contract_http("cart", "phantom", "/never-reached"));
11549        let err = s.validate().unwrap_err();
11550        assert!(
11551            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
11552            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
11553        );
11554    }
11555
11556    #[test]
11557    fn membros_validation_runs_before_contratos_membership_check() {
11558        // If `:membros` carries a duplicate, the membership-collapse
11559        // would silently accept a `:contratos :para "phantom"` so long
11560        // as some entry hashes to "phantom". Pinning order: the
11561        // duplicate-membros error fires first, regardless of whether
11562        // contratos reference real members.
11563        let mut s = three_member_spec();
11564        s.membros = vec![
11565            membro("cart", "^0.1"),
11566            membro("cart", "^0.2"),
11567            membro("catalog", "^0.1"),
11568            membro("payment", "^0.1"),
11569        ];
11570        let err = s.validate().unwrap_err();
11571        assert!(
11572            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
11573            "got {err:?}"
11574        );
11575    }
11576
11577    #[test]
11578    fn distinct_membros_validate() {
11579        // Pin the happy-path: every `:membros` entry has a non-empty
11580        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
11581        // The fixture already satisfies this; this test makes the
11582        // invariant explicit so a future refactor of the fixture can't
11583        // silently break the guarantee.
11584        three_member_spec().validate().unwrap();
11585    }
11586
11587    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
11588
11589    #[test]
11590    fn rejects_membro_caixa_with_uppercase() {
11591        // The canonical "I copied the Servico's display name verbatim"
11592        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
11593        // but author tools often round-trip a TitleCase or CamelCase
11594        // identifier from an ADR or a sketch. Pin the diagnostic names
11595        // the offending name and suggests the lower-cased fix in one
11596        // edit, mirroring the `rejects_entrada_host_with_uppercase`
11597        // gate's shape (c7d05ec).
11598        let mut s = three_member_spec();
11599        s.membros[1].caixa = "Cart".into();
11600        let err = s.validate().unwrap_err();
11601        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11602            panic!("expected MembroCaixaInvalid, got other variant");
11603        };
11604        assert_eq!(caixa, "Cart");
11605        assert!(
11606            reason.contains("uppercase"),
11607            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
11608        );
11609        assert!(
11610            reason.contains("\"cart\""),
11611            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
11612        );
11613    }
11614
11615    #[test]
11616    fn rejects_membro_caixa_with_underscore() {
11617        // The canonical "I'm thinking of a Python module / Postgres
11618        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
11619        // label schema. K8s rejects `metadata.name: my_cart` at admission
11620        // time with an opaque `field is invalid` (no source-citing
11621        // diagnostic). The gate moves it to caixa-build time.
11622        let mut s = three_member_spec();
11623        s.membros[0].caixa = "my_cart".into();
11624        let err = s.validate().unwrap_err();
11625        assert!(
11626            matches!(
11627                err,
11628                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
11629                    if caixa == "my_cart" && reason.contains('_')
11630            ),
11631            "got {err:?}"
11632        );
11633    }
11634
11635    #[test]
11636    fn rejects_membro_caixa_with_dot() {
11637        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
11638        // subdomain — even though K8s `metadata.name` itself accepts
11639        // dots (DNS-1123 subdomain rule), this string also lands as a
11640        // K8s Service name (DNS-1035 label — no dots) and as a label
11641        // value on identity-based Cilium selectors. The strictest floor
11642        // among the use sites wins. The "I want to namespace my member
11643        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
11644        let mut s = three_member_spec();
11645        s.membros[2].caixa = "team.cart".into();
11646        let err = s.validate().unwrap_err();
11647        assert!(
11648            matches!(
11649                err,
11650                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
11651                    if caixa == "team.cart" && reason.contains('.')
11652            ),
11653            "got {err:?}"
11654        );
11655    }
11656
11657    #[test]
11658    fn rejects_membro_caixa_with_leading_hyphen() {
11659        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
11660        // with an alphanumeric. The K8s apiserver rejects `-cart`
11661        // outright; the renderer would emit a `metadata.name: "-cart"`
11662        // that fails admission far from the source caixa.lisp.
11663        let mut s = three_member_spec();
11664        s.membros[0].caixa = "-cart".into();
11665        let err = s.validate().unwrap_err();
11666        assert!(
11667            matches!(
11668                err,
11669                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
11670                    if caixa == "-cart" && reason.contains("start and end")
11671            ),
11672            "got {err:?}"
11673        );
11674    }
11675
11676    #[test]
11677    fn rejects_membro_caixa_with_trailing_hyphen() {
11678        // The symmetric arm of the boundary rule. Pin separately so
11679        // both ends of the label are covered against a future relaxation
11680        // that only checks one boundary.
11681        let mut s = three_member_spec();
11682        s.membros[1].caixa = "cart-".into();
11683        let err = s.validate().unwrap_err();
11684        assert!(
11685            matches!(
11686                err,
11687                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11688                    if caixa == "cart-"
11689            ),
11690            "got {err:?}"
11691        );
11692    }
11693
11694    #[test]
11695    fn rejects_membro_caixa_with_unicode() {
11696        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
11697        // (`xn--…`) by the author before it reaches K8s. The byte-by-
11698        // byte ASCII validity check rejects multi-byte UTF-8 sequences
11699        // by the first byte that fails the `[a-z0-9-]` predicate.
11700        let mut s = three_member_spec();
11701        s.membros[2].caixa = "café".into();
11702        let err = s.validate().unwrap_err();
11703        assert!(
11704            matches!(
11705                err,
11706                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11707                    if caixa == "café"
11708            ),
11709            "got {err:?}"
11710        );
11711    }
11712
11713    #[test]
11714    fn rejects_membro_caixa_with_whitespace() {
11715        // Whitespace is the canonical "I pasted from a sketch / doc"
11716        // footgun. The apiserver rejects every `metadata.name` value
11717        // carrying whitespace; pin the gate fires at the right boundary.
11718        let mut s = three_member_spec();
11719        s.membros[0].caixa = "my cart".into();
11720        let err = s.validate().unwrap_err();
11721        assert!(
11722            matches!(
11723                err,
11724                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
11725                    if caixa == "my cart"
11726            ),
11727            "got {err:?}"
11728        );
11729    }
11730
11731    #[test]
11732    fn rejects_membro_caixa_too_long() {
11733        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
11734        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
11735        // exactly. The gate's reason names both the cap and the actual
11736        // length so the author can shorten in one edit.
11737        let mut s = three_member_spec();
11738        let too_long = "a".repeat(64);
11739        s.membros[1].caixa = too_long.clone();
11740        let err = s.validate().unwrap_err();
11741        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11742            panic!("expected MembroCaixaInvalid");
11743        };
11744        assert_eq!(caixa, too_long);
11745        assert!(
11746            reason.contains("63") && reason.contains("64"),
11747            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
11748        );
11749    }
11750
11751    #[test]
11752    fn membro_caixa_max_length_validates() {
11753        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
11754        // so a future tightening (e.g. dropping to 62) surfaces here as
11755        // a regression, mirroring `entrada_host_max_length_validates`
11756        // (c7d05ec).
11757        let mut s = three_member_spec();
11758        s.membros[2].caixa = "a".repeat(63);
11759        s.entrada.as_mut().unwrap().para = "a".repeat(63);
11760        // remove contratos referencing the renamed member; they'd
11761        // raise ContratoMemberMissing otherwise
11762        s.contratos
11763            .retain(|c| c.de != "payment" && c.para != "payment");
11764        s.validate().unwrap();
11765    }
11766
11767    #[test]
11768    fn accepts_canonical_membro_caixa_forms() {
11769        // The DNS-1123 label shapes a caixa author is realistically
11770        // going to write: single-word lowercase, hyphen-joined, ending
11771        // in a digit-suffixed version (`cart-v2`), starting with a
11772        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
11773        // DNS-1035 which requires a letter at position 0), single-
11774        // character (`a` — boundary). Pin every leg so a future
11775        // tightening that bans (e.g.) digit-start identifiers surfaces
11776        // here.
11777        for form in [
11778            "checkout",
11779            "cart",
11780            "cart-v2",
11781            "a",
11782            "c0",
11783            "3rd-party-shim",
11784            "x-1-2-3-4",
11785        ] {
11786            let mut s = three_member_spec();
11787            // Renaming a member also requires updating downstream refs;
11788            // drop everything else and rebuild a minimal spec around
11789            // just the one renamed member.
11790            s.membros = vec![membro(form, "^0.1")];
11791            s.contratos = vec![];
11792            s.entrada = None;
11793            s.validate()
11794                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
11795        }
11796    }
11797
11798    #[test]
11799    fn membro_caixa_empty_takes_precedence_over_invalid() {
11800        // Order pin: the existing `MembroCaixaEmpty` diagnostic
11801        // (which doesn't try to parse) fires before the new
11802        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
11803        // `:caixa` keeps its narrower error message — the new gate
11804        // would also reject `""`, but the empty-string arm is the more
11805        // self-locating diagnostic for the author. Mirrors the
11806        // `entrada_host_empty_takes_precedence_over_invalid` pin
11807        // (c7d05ec).
11808        let mut s = three_member_spec();
11809        s.membros[1].caixa = String::new();
11810        let err = s.validate().unwrap_err();
11811        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
11812    }
11813
11814    #[test]
11815    fn membro_caixa_invalid_fires_before_versao_check() {
11816        // Order pin: an invalid-shape `:caixa` surfaces *its own*
11817        // diagnostic (which names the offending caixa name), even when
11818        // the same entry's `:versao` is also empty/invalid. The shape
11819        // gate runs first because the diagnostic is more self-locating —
11820        // an empty/invalid `:versao` on an invalid-shape caixa name is
11821        // a downstream-fix-after-the-caixa-rename concern.
11822        let mut s = three_member_spec();
11823        s.membros[1].caixa = "Cart".into();
11824        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
11825        let err = s.validate().unwrap_err();
11826        assert!(
11827            matches!(
11828                err,
11829                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
11830            ),
11831            "got {err:?}"
11832        );
11833    }
11834
11835    #[test]
11836    fn membro_caixa_invalid_fires_before_duplicate_check() {
11837        // Order pin: a malformed-shape `:caixa` on an earlier entry
11838        // surfaces *its own* diagnostic, even when a later entry would
11839        // otherwise collapse onto a duplicate name. The per-entry shape
11840        // gate runs inline before the duplicate-key insert, parallel
11841        // to `membro_versao_invalid_fires_before_duplicate_check`.
11842        let mut s = three_member_spec();
11843        s.membros[0].caixa = "Catalog".into();
11844        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
11845        let err = s.validate().unwrap_err();
11846        assert!(
11847            matches!(
11848                err,
11849                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
11850            ),
11851            "got {err:?}"
11852        );
11853    }
11854
11855    #[test]
11856    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
11857        // The diagnostic-shape pin: the error names the offending
11858        // `:caixa` value verbatim so the author can grep their
11859        // caixa.lisp without re-running the build, and carries a
11860        // non-empty `reason` naming the specific violation. Same
11861        // shape every typed-shape gate enshrines (c7d05ec's
11862        // `entrada_host_diagnostic_carries_offending_host`,
11863        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
11864        let mut s = three_member_spec();
11865        s.membros[2].caixa = "BAD_NAME".into();
11866        let err = s.validate().unwrap_err();
11867        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
11868            panic!("expected MembroCaixaInvalid");
11869        };
11870        assert_eq!(caixa, "BAD_NAME");
11871        assert!(
11872            !reason.is_empty(),
11873            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
11874        );
11875    }
11876
11877    #[test]
11878    fn rejects_contrato_with_unknown_de() {
11879        let mut s = three_member_spec();
11880        s.contratos.push(contract_http("phantom", "catalog", "/x"));
11881        let err = s.validate().unwrap_err();
11882        assert!(
11883            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
11884        );
11885    }
11886
11887    #[test]
11888    fn rejects_contrato_with_unknown_para() {
11889        let mut s = three_member_spec();
11890        s.contratos.push(contract_http("cart", "phantom", "/x"));
11891        let err = s.validate().unwrap_err();
11892        assert!(
11893            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
11894        );
11895    }
11896
11897    #[test]
11898    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
11899        // The read-path pin: the phantom-`:de` refusal arm's
11900        // `ContratoMemberMissing.caixa` carrier must be observed through
11901        // the lifted [`WitContract::source`] accessor, not the raw
11902        // `.de.clone()` field-access `String`-carry. Peer of the sibling
11903        // per-`:contratos` self-loop arm's `.source().to_string()` /
11904        // `.world_ref().to_string()` `String`-carry sites the earlier
11905        // convergence lifted onto the same accessor pair. A future
11906        // silent detour that reintroduced the raw `.de.clone()` at the
11907        // wrap envelope while the shape-gate and membership lookup
11908        // routed through the accessor would surface here as a byte-equal
11909        // miss between the fired diagnostic's `caixa:` field and the
11910        // offending edge's `.source()` — pinning the accessor as the
11911        // sole read path across the phantom-name refusal arm's arg +
11912        // wrap-envelope emit surface.
11913        let mut s = three_member_spec();
11914        let phantom = contract_http("phantom", "catalog", "/x");
11915        s.contratos.push(phantom.clone());
11916        let err = s.validate().unwrap_err();
11917        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
11918            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
11919        };
11920        assert_eq!(
11921            caixa,
11922            phantom.source(),
11923            "ContratoMemberMissing.caixa on the phantom-:de arm must \
11924             byte-equal WitContract::source — the wrap envelope must \
11925             route through the lifted accessor rather than the raw \
11926             .de.clone() field-access String-carry"
11927        );
11928    }
11929
11930    #[test]
11931    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
11932        // The symmetric read-path pin on the `:para` phantom-name
11933        // refusal arm — same shape as the sibling `:de` pin above but
11934        // on the callee-Servico axis. Pins the wrap envelope's
11935        // `caixa:` field is observed through the lifted
11936        // [`WitContract::destination`] accessor, not the raw
11937        // `.para.clone()` field-access `String`-carry.
11938        let mut s = three_member_spec();
11939        let phantom = contract_http("cart", "phantom", "/x");
11940        s.contratos.push(phantom.clone());
11941        let err = s.validate().unwrap_err();
11942        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
11943            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
11944        };
11945        assert_eq!(
11946            caixa,
11947            phantom.destination(),
11948            "ContratoMemberMissing.caixa on the phantom-:para arm must \
11949             byte-equal WitContract::destination — the wrap envelope \
11950             must route through the lifted accessor rather than the raw \
11951             .para.clone() field-access String-carry"
11952        );
11953    }
11954
11955    #[test]
11956    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
11957        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
11958        // refusal arm — the `validate_contrato_caixa` arg must be
11959        // observed through the lifted [`WitContract::source`] accessor,
11960        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
11961        // value routes through the shared
11962        // [`crate::render::require_valid_dns_1123_label`] floor with the
11963        // accessor-projected value; the fired
11964        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
11965        // the offending edge's `.source()`, pinning that the arg + the
11966        // downstream `caixa: caixa.to_string()` wrap route through the
11967        // same accessor's read path.
11968        let mut s = three_member_spec();
11969        let malformed = contract_http("BAD_NAME", "catalog", "/x");
11970        s.contratos.push(malformed.clone());
11971        let err = s.validate().unwrap_err();
11972        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
11973            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
11974        };
11975        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
11976        assert_eq!(
11977            caixa,
11978            malformed.source(),
11979            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
11980             byte-equal WitContract::source — the shape-gate arg + wrap \
11981             envelope must route through the lifted accessor rather \
11982             than the raw &c.de &String-borrow"
11983        );
11984    }
11985
11986    #[test]
11987    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
11988        // Symmetric arm to the sibling `:de` malformed-shape pin above,
11989        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
11990        // route through the lifted [`WitContract::destination`]
11991        // accessor. `:para` runs after the `:de` shape gate in the
11992        // canonical edge-direction order, so the `:de` value must be
11993        // well-shaped for the `:para` gate to fire — the `cart` :de is
11994        // canonical.
11995        let mut s = three_member_spec();
11996        let malformed = contract_http("cart", "BAD_NAME", "/x");
11997        s.contratos.push(malformed.clone());
11998        let err = s.validate().unwrap_err();
11999        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
12000            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
12001        };
12002        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
12003        assert_eq!(
12004            caixa,
12005            malformed.destination(),
12006            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
12007             byte-equal WitContract::destination — the shape-gate arg + \
12008             wrap envelope must route through the lifted accessor \
12009             rather than the raw &c.para &String-borrow"
12010        );
12011    }
12012
12013    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
12014
12015    #[test]
12016    fn rejects_contrato_de_empty() {
12017        // `:de ""` previously fell through to `ContratoMemberMissing`
12018        // (with `caixa: ""`) because the validated `:membros :caixa`
12019        // set never contains the empty string. The narrower
12020        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
12021        // the offending slot.
12022        let mut s = three_member_spec();
12023        s.contratos.push(contract_http("", "catalog", "/x"));
12024        let err = s.validate().unwrap_err();
12025        assert_eq!(
12026            err,
12027            AplicacaoError::ContratoCaixaEmpty {
12028                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
12029            },
12030            "got {err:?}"
12031        );
12032    }
12033
12034    #[test]
12035    fn rejects_contrato_para_empty() {
12036        // Symmetric arm to `:de ""` — `:para ""` previously fell
12037        // through to `ContratoMemberMissing { caixa: "" }`.
12038        let mut s = three_member_spec();
12039        s.contratos.push(contract_http("cart", "", "/x"));
12040        let err = s.validate().unwrap_err();
12041        assert_eq!(
12042            err,
12043            AplicacaoError::ContratoCaixaEmpty {
12044                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
12045            },
12046            "got {err:?}"
12047        );
12048    }
12049
12050    #[test]
12051    fn rejects_contrato_de_with_uppercase() {
12052        // The canonical "I copied the Servico's TitleCase display
12053        // name from an ADR" typo. Until this gate landed `:de "Cart"`
12054        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
12055        // as "this caixa isn't in `:membros`" when the root cause is
12056        // "this `:de` value's shape can never legitimately match a
12057        // validated member (DNS-1123 labels are lowercase)". The
12058        // narrower diagnostic names the offending slot, the value
12059        // verbatim, and the parser-shaped reason.
12060        let mut s = three_member_spec();
12061        s.contratos.push(contract_http("Cart", "catalog", "/x"));
12062        let err = s.validate().unwrap_err();
12063        let AplicacaoError::ContratoCaixaInvalid {
12064            slot,
12065            caixa,
12066            reason,
12067        } = err
12068        else {
12069            panic!("expected ContratoCaixaInvalid, got other variant");
12070        };
12071        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
12072        assert_eq!(caixa, "Cart");
12073        assert!(
12074            reason.contains("uppercase"),
12075            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
12076        );
12077    }
12078
12079    #[test]
12080    fn rejects_contrato_para_with_underscore() {
12081        // The canonical "I'm thinking of a Python module" leak —
12082        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
12083        // Pin the `:para` axis surfaces the same diagnostic shape as
12084        // the `:de` axis on the underscore violation.
12085        let mut s = three_member_spec();
12086        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
12087        let err = s.validate().unwrap_err();
12088        assert!(
12089            matches!(
12090                err,
12091                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12092                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
12093            ),
12094            "got {err:?}"
12095        );
12096    }
12097
12098    #[test]
12099    fn rejects_contrato_de_with_dot() {
12100        // A `:contratos :de` value is a single DNS-1123 *label*, not
12101        // a subdomain — mirroring the `:membros :caixa` floor. The
12102        // strictest floor among the use sites wins.
12103        let mut s = three_member_spec();
12104        s.contratos
12105            .push(contract_http("team.cart", "catalog", "/x"));
12106        let err = s.validate().unwrap_err();
12107        assert!(
12108            matches!(
12109                err,
12110                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12111                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
12112            ),
12113            "got {err:?}"
12114        );
12115    }
12116
12117    #[test]
12118    fn rejects_contrato_para_with_unicode() {
12119        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12120        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
12121        // validity check rejects multi-byte UTF-8 by the first
12122        // non-`[a-z0-9-]` byte.
12123        let mut s = three_member_spec();
12124        s.contratos.push(contract_http("cart", "café", "/x"));
12125        let err = s.validate().unwrap_err();
12126        assert!(
12127            matches!(
12128                err,
12129                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
12130                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
12131            ),
12132            "got {err:?}"
12133        );
12134    }
12135
12136    #[test]
12137    fn rejects_contrato_de_with_leading_hyphen() {
12138        // DNS-1123 boundary rule: labels must start and end with an
12139        // alphanumeric. K8s rejects `-cart` outright; the narrower
12140        // shape diagnostic now names the violation at caixa-build
12141        // time rather than the misframed membership-lookup arm.
12142        let mut s = three_member_spec();
12143        s.contratos.push(contract_http("-cart", "catalog", "/x"));
12144        let err = s.validate().unwrap_err();
12145        assert!(
12146            matches!(
12147                err,
12148                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
12149                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
12150            ),
12151            "got {err:?}"
12152        );
12153    }
12154
12155    #[test]
12156    fn contrato_de_empty_takes_precedence_over_invalid() {
12157        // Order pin: the `ContratoCaixaEmpty` arm fires before the
12158        // `ContratoCaixaInvalid` parse-side arm — same empty-first
12159        // cascade `validate_membro_caixa` / `validate_placement_cluster`
12160        // / `validate_entrada_host` already establish on their peer
12161        // name axes. The empty string is a structurally distinct
12162        // authoring footgun (the author left the field blank, vs.
12163        // typed a malformed value), so it gets its own diagnostic.
12164        let mut s = three_member_spec();
12165        s.contratos.push(contract_http("", "catalog", "/x"));
12166        let err = s.validate().unwrap_err();
12167        assert_eq!(
12168            err,
12169            AplicacaoError::ContratoCaixaEmpty {
12170                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
12171            }
12172        );
12173    }
12174
12175    #[test]
12176    fn contrato_de_shape_fires_before_para_shape() {
12177        // Per-axis order pin: within one `:contratos` entry, the `:de`
12178        // shape gate fires before the `:para` shape gate — same
12179        // edge-direction order the existing `ContratoMemberMissing` /
12180        // `ContratoSelfLoop` / target-dispatch checks use, so the
12181        // diagnostic for a contract with both `:de` and `:para`
12182        // malformed is stable. Authors fixing the surfaced `:de`
12183        // first will see `:para`'s diagnostic on re-run.
12184        let mut s = three_member_spec();
12185        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
12186        let err = s.validate().unwrap_err();
12187        assert!(
12188            matches!(
12189                err,
12190                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
12191                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
12192            ),
12193            "got {err:?}"
12194        );
12195    }
12196
12197    #[test]
12198    fn contrato_shape_fires_before_membership_lookup() {
12199        // The load-bearing pin: an invalid-shape `:de` surfaces its
12200        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
12201        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
12202        // an invalid-shape `:de` could never legitimately match any
12203        // member — the prior `ContratoMemberMissing` diagnostic was
12204        // a structural impossibility framed as a graph-membership
12205        // failure. The shape gate now routes every such input through
12206        // the narrower self-locating diagnostic.
12207        let mut s = three_member_spec();
12208        s.contratos.push(contract_http("Cart", "catalog", "/x"));
12209        let err = s.validate().unwrap_err();
12210        assert!(
12211            matches!(
12212                err,
12213                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
12214            ),
12215            "got {err:?}"
12216        );
12217        // And the symmetric case: an invalid-shape `:para` surfaces
12218        // its own diagnostic too, even when `:de` is well-shaped.
12219        let mut s = three_member_spec();
12220        s.contratos.push(contract_http("cart", "Catalog", "/x"));
12221        let err = s.validate().unwrap_err();
12222        assert!(
12223            matches!(
12224                err,
12225                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
12226            ),
12227            "got {err:?}"
12228        );
12229    }
12230
12231    #[test]
12232    fn contrato_shape_fires_before_self_edge_check() {
12233        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
12234        // bugs: the shape violation (uppercase) and the self-edge
12235        // violation. The narrower per-axis shape diagnostic surfaces
12236        // first because fixing the shape may reveal that the author
12237        // also meant to point `:para` at a different member — the
12238        // self-edge framing is only useful once both endpoints have
12239        // valid shape.
12240        let mut s = three_member_spec();
12241        s.contratos.push(contract_http("Cart", "Cart", "/x"));
12242        let err = s.validate().unwrap_err();
12243        assert!(
12244            matches!(
12245                err,
12246                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
12247                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
12248            ),
12249            "got {err:?}"
12250        );
12251    }
12252
12253    #[test]
12254    fn contrato_well_shaped_phantom_still_raises_member_missing() {
12255        // Strict-improvement pin: a well-shaped `:de` that simply
12256        // isn't in `:membros` (a phantom reference — author meant
12257        // to add the member but didn't, or renamed and missed an
12258        // update) still surfaces `ContratoMemberMissing`, unchanged.
12259        // The shape gate only intercepts inputs that could never
12260        // legitimately match a validated member; legitimately-shaped
12261        // phantom references remain on the graph-membership axis.
12262        let mut s = three_member_spec();
12263        s.contratos
12264            .push(contract_http("phantom-shim", "catalog", "/x"));
12265        let err = s.validate().unwrap_err();
12266        assert!(
12267            matches!(
12268                err,
12269                AplicacaoError::ContratoMemberMissing { ref caixa }
12270                    if caixa == "phantom-shim"
12271            ),
12272            "got {err:?}"
12273        );
12274    }
12275
12276    #[test]
12277    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
12278        // The diagnostic-shape pin: the error names the offending
12279        // slot (`:de` or `:para`) verbatim and the offending value
12280        // verbatim plus a non-empty parser-shaped reason, so the
12281        // author can grep their caixa.lisp for `:de "<name>"` /
12282        // `:para "<name>"` and fix it in one edit. Same diagnostic
12283        // shape as `MembroCaixaInvalid` (3f9d7a0) and
12284        // `PlacementClusterInvalid` (6c8c00b).
12285        let mut s = three_member_spec();
12286        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
12287        let err = s.validate().unwrap_err();
12288        let AplicacaoError::ContratoCaixaInvalid {
12289            slot,
12290            caixa,
12291            reason,
12292        } = err
12293        else {
12294            panic!("expected ContratoCaixaInvalid, got {err:?}");
12295        };
12296        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
12297        assert_eq!(caixa, "BAD_NAME");
12298        assert!(
12299            !reason.is_empty(),
12300            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
12301        );
12302    }
12303
12304    #[test]
12305    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
12306        // Scalar-value pin: the two author-facing kebab-case labels the
12307        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
12308        // admits on the `:contratos` per-entry endpoint-shape axis,
12309        // one arm per typed sub-slot. Mirrors the peer scalar-value
12310        // pin the sibling top-level M2 / M3 / Supervisor
12311        // author-facing-label consts carry
12312        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
12313        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
12314        // slot itself), so every altitude of the typed-slot algebra
12315        // shares the same "one canonical byte-string per arm"
12316        // discipline. A future rebrand (`:de` → `:from` matching the
12317        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
12318        // sibling, `:para` → `:to` matching the same, or
12319        // `:de`/`:para` → `:source`/`:target` matching the WIT
12320        // world's `import`/`export` half-vocabulary) lands as an
12321        // edit to exactly one const, and every consumer that reaches
12322        // for the label picks it up at build time rather than at
12323        // runtime as a downstream `ContratoCaixaEmpty` /
12324        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
12325        // diagnostic mismatch far from the rename's commit.
12326        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
12327        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
12328    }
12329
12330    #[test]
12331    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
12332        // Production-through-const pin: the two per-axis labels the
12333        // per-`:contratos` entry endpoint-shape gate at
12334        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
12335        // argument to [`validate_contrato_caixa`] route through the
12336        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
12337        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
12338        // future rebrand that reaches the const but not the gate (or
12339        // vice versa) surfaces here at build time rather than at
12340        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
12341        // `slot: <stale-kebab-case>` diagnostic far from the rename's
12342        // commit. Mirror of the peer
12343        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
12344        // pin (882f498) on the sibling M3 top-level slot axis.
12345        let mut s = three_member_spec();
12346        s.contratos.push(contract_http("", "catalog", "/x"));
12347        assert_eq!(
12348            s.validate().unwrap_err(),
12349            AplicacaoError::ContratoCaixaEmpty {
12350                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
12351            }
12352        );
12353        let mut s = three_member_spec();
12354        s.contratos.push(contract_http("cart", "", "/x"));
12355        assert_eq!(
12356            s.validate().unwrap_err(),
12357            AplicacaoError::ContratoCaixaEmpty {
12358                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
12359            }
12360        );
12361    }
12362
12363    #[test]
12364    fn accepts_canonical_contrato_caixa_forms() {
12365        // The DNS-1123 label shapes a caixa author is realistically
12366        // going to write on a `:contratos :de` / `:para`. Pin every
12367        // leg so a future tightening that bans (e.g.) digit-start
12368        // identifiers surfaces here, mirroring
12369        // `accepts_canonical_membro_caixa_forms` on the peer name
12370        // axis.
12371        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
12372            let mut s = three_member_spec();
12373            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
12374            s.contratos = vec![contract_http("checkout", form, "/x")];
12375            s.entrada = None;
12376            s.validate().unwrap_or_else(|e| {
12377                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
12378            });
12379
12380            let mut s = three_member_spec();
12381            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
12382            s.contratos = vec![contract_http(form, "catalog", "/x")];
12383            s.entrada = None;
12384            s.validate().unwrap_or_else(|e| {
12385                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
12386            });
12387        }
12388    }
12389
12390    #[test]
12391    fn rejects_empty_wit() {
12392        let mut s = three_member_spec();
12393        s.contratos.push(WitContract {
12394            de: "cart".into(),
12395            para: "catalog".into(),
12396            wit: String::new(),
12397            endpoint: None,
12398            subject: None,
12399            slot: None,
12400        });
12401        let err = s.validate().unwrap_err();
12402        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
12403    }
12404
12405    #[test]
12406    fn rejects_entrada_to_unknown_member() {
12407        let mut s = three_member_spec();
12408        s.entrada.as_mut().unwrap().para = "phantom".into();
12409        assert!(matches!(
12410            s.validate().unwrap_err(),
12411            AplicacaoError::EntradaMemberMissing { .. }
12412        ));
12413    }
12414
12415    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
12416
12417    #[test]
12418    fn rejects_entrada_para_empty() {
12419        // `:para ""` previously fell through to
12420        // `EntradaMemberMissing { para: "" }` because the validated
12421        // `:membros :caixa` set never contains the empty string. The
12422        // narrower `EntradaParaEmpty` diagnostic now names the
12423        // offending slot directly — same empty-first cascade
12424        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
12425        // `ContratoCaixaEmpty` establish on the peer name axes.
12426        let mut s = three_member_spec();
12427        s.entrada.as_mut().unwrap().para = String::new();
12428        let err = s.validate().unwrap_err();
12429        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
12430    }
12431
12432    #[test]
12433    fn rejects_entrada_para_with_uppercase() {
12434        // The canonical "I copied the Servico's TitleCase display
12435        // name from an ADR" typo. Until this gate landed `:para "Cart"`
12436        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
12437        // as "this caixa isn't in `:membros`" when the root cause is
12438        // "this `:para` value's shape can never legitimately match a
12439        // validated member (DNS-1123 labels are lowercase)". The
12440        // narrower diagnostic names the value verbatim plus the
12441        // parser-shaped reason.
12442        let mut s = three_member_spec();
12443        s.entrada.as_mut().unwrap().para = "Cart".into();
12444        let err = s.validate().unwrap_err();
12445        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
12446            panic!("expected EntradaParaInvalid, got other variant");
12447        };
12448        assert_eq!(para, "Cart");
12449        assert!(
12450            reason.contains("uppercase"),
12451            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
12452        );
12453    }
12454
12455    #[test]
12456    fn rejects_entrada_para_with_underscore() {
12457        // The canonical "I'm thinking of a Python module" leak —
12458        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
12459        let mut s = three_member_spec();
12460        s.entrada.as_mut().unwrap().para = "my_cart".into();
12461        let err = s.validate().unwrap_err();
12462        assert!(
12463            matches!(
12464                err,
12465                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12466                    if para == "my_cart" && reason.contains('_')
12467            ),
12468            "got {err:?}"
12469        );
12470    }
12471
12472    #[test]
12473    fn rejects_entrada_para_with_dot() {
12474        // An `:entrada :para` value is a single DNS-1123 *label*, not
12475        // a subdomain — mirroring the `:membros :caixa` floor. The
12476        // strictest floor among the use sites wins.
12477        let mut s = three_member_spec();
12478        s.entrada.as_mut().unwrap().para = "team.cart".into();
12479        let err = s.validate().unwrap_err();
12480        assert!(
12481            matches!(
12482                err,
12483                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12484                    if para == "team.cart" && reason.contains('.')
12485            ),
12486            "got {err:?}"
12487        );
12488    }
12489
12490    #[test]
12491    fn rejects_entrada_para_with_unicode() {
12492        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
12493        // (`xn--…`) before it reaches K8s.
12494        let mut s = three_member_spec();
12495        s.entrada.as_mut().unwrap().para = "café".into();
12496        let err = s.validate().unwrap_err();
12497        assert!(
12498            matches!(
12499                err,
12500                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
12501            ),
12502            "got {err:?}"
12503        );
12504    }
12505
12506    #[test]
12507    fn rejects_entrada_para_with_leading_hyphen() {
12508        // DNS-1123 boundary rule: labels must start and end with an
12509        // alphanumeric. K8s rejects `-cart` outright.
12510        let mut s = three_member_spec();
12511        s.entrada.as_mut().unwrap().para = "-cart".into();
12512        let err = s.validate().unwrap_err();
12513        assert!(
12514            matches!(
12515                err,
12516                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12517                    if para == "-cart" && reason.contains("start and end")
12518            ),
12519            "got {err:?}"
12520        );
12521    }
12522
12523    #[test]
12524    fn rejects_entrada_para_with_trailing_hyphen() {
12525        // Symmetric boundary arm.
12526        let mut s = three_member_spec();
12527        s.entrada.as_mut().unwrap().para = "cart-".into();
12528        let err = s.validate().unwrap_err();
12529        assert!(
12530            matches!(
12531                err,
12532                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12533                    if para == "cart-" && reason.contains("start and end")
12534            ),
12535            "got {err:?}"
12536        );
12537    }
12538
12539    #[test]
12540    fn rejects_entrada_para_too_long() {
12541        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
12542        // bytes per label. K8s rejects longer names at admission on
12543        // every `metadata.name` axis.
12544        let mut s = three_member_spec();
12545        s.entrada.as_mut().unwrap().para = "a".repeat(64);
12546        let err = s.validate().unwrap_err();
12547        assert!(
12548            matches!(
12549                err,
12550                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
12551                    if para.len() == 64 && reason.contains("max length")
12552            ),
12553            "got {err:?}"
12554        );
12555    }
12556
12557    #[test]
12558    fn entrada_para_empty_takes_precedence_over_invalid() {
12559        // Order pin: the `EntradaParaEmpty` arm fires before the
12560        // `EntradaParaInvalid` parse-side arm — same empty-first
12561        // cascade `validate_membro_caixa` / `validate_placement_cluster`
12562        // / `validate_contrato_caixa` already establish.
12563        let mut s = three_member_spec();
12564        s.entrada.as_mut().unwrap().para = String::new();
12565        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
12566    }
12567
12568    #[test]
12569    fn entrada_para_shape_fires_before_membership_lookup() {
12570        // The load-bearing pin: an invalid-shape `:para` surfaces its
12571        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
12572        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
12573        // an invalid-shape `:para` could never legitimately match any
12574        // member — the prior `EntradaMemberMissing` diagnostic framed
12575        // a structural impossibility as a graph-membership failure.
12576        let mut s = three_member_spec();
12577        s.entrada.as_mut().unwrap().para = "Cart".into();
12578        let err = s.validate().unwrap_err();
12579        assert!(
12580            matches!(
12581                err,
12582                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
12583            ),
12584            "got {err:?}"
12585        );
12586    }
12587
12588    #[test]
12589    fn entrada_para_shape_fires_before_host_gate() {
12590        // Per-`:entrada` order pin: the `:para` shape gate fires
12591        // before the `:host` gate, mirroring the existing
12592        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
12593        // ordering where the member-lookup arm preceded the host gate.
12594        // The shape gate slots ahead of that, so a malformed `:para`
12595        // surfaces its own diagnostic even when `:host` is also wrong.
12596        let mut s = three_member_spec();
12597        let e = s.entrada.as_mut().unwrap();
12598        e.para = "Cart".into();
12599        e.host = "BAD HOST".into();
12600        let err = s.validate().unwrap_err();
12601        assert!(
12602            matches!(
12603                err,
12604                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
12605            ),
12606            "got {err:?}"
12607        );
12608    }
12609
12610    #[test]
12611    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
12612        // Strict-improvement pin: a well-shaped `:para` that simply
12613        // isn't in `:membros` (a phantom reference — author meant to
12614        // add the member but didn't, or renamed and missed an
12615        // update) still surfaces `EntradaMemberMissing`, unchanged.
12616        // The shape gate only intercepts inputs that could never
12617        // legitimately match a validated member.
12618        let mut s = three_member_spec();
12619        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
12620        let err = s.validate().unwrap_err();
12621        assert!(
12622            matches!(
12623                err,
12624                AplicacaoError::EntradaMemberMissing { ref para }
12625                    if para == "phantom-shim"
12626            ),
12627            "got {err:?}"
12628        );
12629    }
12630
12631    #[test]
12632    fn entrada_para_invalid_diagnostic_carries_offending_para() {
12633        // The diagnostic-shape pin: the error names the offending
12634        // `:para` value verbatim plus a non-empty parser-shaped
12635        // reason, so the author can grep their caixa.lisp for
12636        // `:para "<name>"` and fix it in one edit. Same diagnostic
12637        // shape as `MembroCaixaInvalid` (3f9d7a0),
12638        // `PlacementClusterInvalid` (6c8c00b), and
12639        // `ContratoCaixaInvalid` (8d5af6b).
12640        let mut s = three_member_spec();
12641        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
12642        let err = s.validate().unwrap_err();
12643        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
12644            panic!("expected EntradaParaInvalid, got {err:?}");
12645        };
12646        assert_eq!(para, "BAD_NAME");
12647        assert!(
12648            !reason.is_empty(),
12649            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
12650        );
12651    }
12652
12653    #[test]
12654    fn accepts_canonical_entrada_para_forms() {
12655        // Positive-control sweep covering the DNS-1123 label shapes a
12656        // caixa author is realistically going to write on `:entrada
12657        // :para`. Pin every leg so a future tightening that bans
12658        // (e.g.) digit-start identifiers surfaces here, mirroring
12659        // `accepts_canonical_membro_caixa_forms` and
12660        // `accepts_canonical_contrato_caixa_forms` on the peer name
12661        // axes.
12662        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
12663            let mut s = three_member_spec();
12664            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
12665            s.contratos = vec![contract_http(form, "catalog", "/x")];
12666            s.entrada = Some(Entrada {
12667                host: "checkout.quero.cloud".into(),
12668                para: form.into(),
12669                paths: vec!["/api".into()],
12670                port: 8080,
12671            });
12672            s.validate().unwrap_or_else(|e| {
12673                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
12674            });
12675        }
12676    }
12677
12678    #[test]
12679    fn rejects_replicated_without_clusters() {
12680        let mut s = three_member_spec();
12681        s.placement.clusters = vec![];
12682        assert!(matches!(
12683            s.validate().unwrap_err(),
12684            AplicacaoError::PlacementWithoutClusters { .. }
12685        ));
12686    }
12687
12688    #[test]
12689    fn rejects_sharded_without_key() {
12690        let mut s = three_member_spec();
12691        s.placement.estrategia = PlacementStrategy::Sharded;
12692        s.placement.shard_key = None;
12693        s.placement.clusters = vec!["rio".into()];
12694        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
12695    }
12696
12697    #[test]
12698    fn sharded_with_key_validates() {
12699        let mut s = three_member_spec();
12700        s.placement.estrategia = PlacementStrategy::Sharded;
12701        s.placement.shard_key = Some("$tenantId".into());
12702        s.validate().unwrap();
12703    }
12704
12705    #[test]
12706    fn round_trip_via_json_preserves_shape() {
12707        let s = three_member_spec();
12708        let json = serde_json::to_string(&s.membros).unwrap();
12709        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
12710        assert_eq!(back, s.membros);
12711
12712        let json = serde_json::to_string(&s.contratos).unwrap();
12713        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
12714        assert_eq!(back, s.contratos);
12715
12716        let json = serde_json::to_string(&s.placement).unwrap();
12717        let back: Placement = serde_json::from_str(&json).unwrap();
12718        assert_eq!(back, s.placement);
12719
12720        let json = serde_json::to_string(&s.entrada).unwrap();
12721        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
12722        assert_eq!(back, s.entrada);
12723    }
12724
12725    #[test]
12726    fn rate_limit_round_trip_seconds() {
12727        let policy = MeshPolicy {
12728            rate_limit: Some(RateLimit {
12729                rate: 100,
12730                window: Duration::from_secs(1),
12731            }),
12732            ..Default::default()
12733        };
12734        let json = serde_json::to_string(&policy).unwrap();
12735        assert!(json.contains("\"100/s\""));
12736        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
12737        assert_eq!(back.rate_limit.unwrap().rate, 100);
12738        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
12739    }
12740
12741    #[test]
12742    fn rate_limit_round_trip_minutes() {
12743        let policy = MeshPolicy {
12744            rate_limit: Some(RateLimit {
12745                rate: 5000,
12746                window: Duration::from_secs(60),
12747            }),
12748            ..Default::default()
12749        };
12750        let json = serde_json::to_string(&policy).unwrap();
12751        assert!(json.contains("\"5000/m\""));
12752    }
12753
12754    #[test]
12755    fn circuit_breaker_round_trip() {
12756        let policy = MeshPolicy {
12757            circuit_breaker: Some(CircuitBreaker {
12758                max_failures: 5,
12759                window: Duration::from_secs(60),
12760            }),
12761            ..Default::default()
12762        };
12763        let json = serde_json::to_string(&policy).unwrap();
12764        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
12765        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
12766        assert_eq!(
12767            back.circuit_breaker.unwrap().window,
12768            Duration::from_secs(60)
12769        );
12770    }
12771
12772    #[test]
12773    fn rejects_http_contrato_without_endpoint() {
12774        let mut s = three_member_spec();
12775        s.contratos.push(WitContract {
12776            de: "cart".into(),
12777            para: "catalog".into(),
12778            wit: "wasi:http/proxy".into(),
12779            endpoint: None,
12780            subject: None,
12781            slot: None,
12782        });
12783        let err = s.validate().unwrap_err();
12784        assert!(matches!(
12785            err,
12786            AplicacaoError::ContratoMissingTarget {
12787                expected: WitTarget::HTTP_FIELD_NAME,
12788                ..
12789            }
12790        ));
12791    }
12792
12793    #[test]
12794    fn rejects_http_contrato_with_subject() {
12795        let mut s = three_member_spec();
12796        s.contratos.push(WitContract {
12797            de: "cart".into(),
12798            para: "catalog".into(),
12799            wit: "wasi:http/proxy".into(),
12800            endpoint: Some("/x".into()),
12801            subject: Some("not.allowed.here".into()),
12802            slot: None,
12803        });
12804        let err = s.validate().unwrap_err();
12805        assert!(matches!(
12806            err,
12807            AplicacaoError::ContratoWrongTarget {
12808                expected: WitTarget::HTTP_FIELD_NAME,
12809                ..
12810            }
12811        ));
12812    }
12813
12814    #[test]
12815    fn rejects_pubsub_contrato_without_subject() {
12816        let mut s = three_member_spec();
12817        s.contratos.push(WitContract {
12818            de: "cart".into(),
12819            para: "catalog".into(),
12820            wit: "nats:pub-sub".into(),
12821            endpoint: None,
12822            subject: None,
12823            slot: None,
12824        });
12825        let err = s.validate().unwrap_err();
12826        assert!(matches!(
12827            err,
12828            AplicacaoError::ContratoMissingTarget {
12829                expected: WitTarget::PUBSUB_FIELD_NAME,
12830                ..
12831            }
12832        ));
12833    }
12834
12835    #[test]
12836    fn rejects_pubsub_contrato_with_endpoint() {
12837        let mut s = three_member_spec();
12838        s.contratos.push(WitContract {
12839            de: "cart".into(),
12840            para: "catalog".into(),
12841            wit: "kafka:topic".into(),
12842            endpoint: Some("/wrong".into()),
12843            subject: Some("topic.x".into()),
12844            slot: None,
12845        });
12846        let err = s.validate().unwrap_err();
12847        assert!(matches!(
12848            err,
12849            AplicacaoError::ContratoWrongTarget {
12850                expected: WitTarget::PUBSUB_FIELD_NAME,
12851                ..
12852            }
12853        ));
12854    }
12855
12856    #[test]
12857    fn rejects_store_contrato_without_slot() {
12858        let mut s = three_member_spec();
12859        s.contratos.push(WitContract {
12860            de: "cart".into(),
12861            para: "catalog".into(),
12862            wit: "wasi:keyvalue/store".into(),
12863            endpoint: None,
12864            subject: None,
12865            slot: None,
12866        });
12867        let err = s.validate().unwrap_err();
12868        assert!(matches!(
12869            err,
12870            AplicacaoError::ContratoMissingTarget {
12871                expected: WitTarget::STORE_FIELD_NAME,
12872                ..
12873            }
12874        ));
12875    }
12876
12877    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
12878
12879    #[test]
12880    fn rejects_http_contrato_with_empty_endpoint() {
12881        // `Some("")` for an HTTP endpoint passes the presence check
12882        // (target() previously returned WitTarget::Http { endpoint: "" })
12883        // but renders as a `path: ""` Cilium L7 rule that matches no
12884        // traffic. Same value-shape footgun closed for :entrada :paths
12885        // entries (eb3456d).
12886        let mut s = three_member_spec();
12887        s.contratos.push(WitContract {
12888            de: "cart".into(),
12889            para: "catalog".into(),
12890            wit: "wasi:http/proxy".into(),
12891            endpoint: Some(String::new()),
12892            subject: None,
12893            slot: None,
12894        });
12895        let err = s.validate().unwrap_err();
12896        assert!(
12897            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
12898                if de == "cart" && para == "catalog"),
12899            "got {err:?}"
12900        );
12901    }
12902
12903    #[test]
12904    fn rejects_http_contrato_with_relative_endpoint() {
12905        // Cilium L7 :path + Gateway API PathPrefix both require a
12906        // leading `/`. Same shape required of :entrada :paths
12907        // (eb3456d). Lifted into target() so every consumer of the
12908        // typed WitTarget view inherits the guarantee.
12909        let mut s = three_member_spec();
12910        s.contratos.push(WitContract {
12911            de: "cart".into(),
12912            para: "catalog".into(),
12913            wit: "wasi:http/proxy".into(),
12914            endpoint: Some("products/:id".into()),
12915            subject: None,
12916            slot: None,
12917        });
12918        let err = s.validate().unwrap_err();
12919        assert!(
12920            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
12921                if endpoint == "products/:id"),
12922            "got {err:?}"
12923        );
12924    }
12925
12926    #[test]
12927    fn rejects_pubsub_contrato_with_empty_subject() {
12928        // NATS / Kafka publish without a subject is a no-op subscribe;
12929        // never the author's intent. Same empty-string rejection as
12930        // :membros :caixa, :placement :clusters entries, :entrada
12931        // :paths entries — every value carried by every typed slot is
12932        // value-shape-checked at validate().
12933        let mut s = three_member_spec();
12934        s.contratos.push(WitContract {
12935            de: "cart".into(),
12936            para: "catalog".into(),
12937            wit: "nats:pub-sub".into(),
12938            endpoint: None,
12939            subject: Some(String::new()),
12940            slot: None,
12941        });
12942        let err = s.validate().unwrap_err();
12943        assert!(
12944            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
12945                if de == "cart" && para == "catalog"),
12946            "got {err:?}"
12947        );
12948    }
12949
12950    #[test]
12951    fn rejects_store_contrato_with_empty_slot() {
12952        // An empty slot template addresses the bucket root, defeating
12953        // the per-key isolation the slot exists for — a footgun on
12954        // `wasi:keyvalue/store` whose closest analog is the empty
12955        // shard-key rejected on :placement Sharded (c7c7799).
12956        let mut s = three_member_spec();
12957        s.contratos.push(WitContract {
12958            de: "cart".into(),
12959            para: "catalog".into(),
12960            wit: "wasi:keyvalue/store".into(),
12961            endpoint: None,
12962            subject: None,
12963            slot: Some(String::new()),
12964        });
12965        let err = s.validate().unwrap_err();
12966        assert!(
12967            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
12968                if de == "cart" && para == "catalog"),
12969            "got {err:?}"
12970        );
12971    }
12972
12973    #[test]
12974    fn http_contrato_root_endpoint_validates() {
12975        // Pin the boundary case: a single-`/` endpoint is the catch-all
12976        // form the Gateway HTTPRoute renderer falls back to when
12977        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
12978        // must remain a valid contrato endpoint too.
12979        let mut s = three_member_spec();
12980        s.contratos.push(contract_http("cart", "catalog", "/"));
12981        s.validate().unwrap();
12982    }
12983
12984    // ── :contratos :endpoint value-shape gate ────────────────────────────
12985    //
12986    // Mirrors the `:entrada :paths` value-shape suite on the peer
12987    // HTTP-path axis. Until this gate landed `WitContract::target()`
12988    // only refused the empty string + the missing-leading-`/` form
12989    // (c4213a4); a structurally invalid endpoint passed validate and
12990    // landed verbatim as a Cilium L7 `path:` rule
12991    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
12992    // traffic or was rejected at apply time by Cilium policy admission.
12993    // Every authoring footgun the K8s Gateway API webhook / Cilium
12994    // policy validator would catch on admission now becomes a caixa-
12995    // build-time `ContratoEndpointInvalid` with the offending
12996    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
12997    // shape as `EntradaPathInvalid` on the sibling axis; same shared
12998    // predicate (`crate::render::is_gateway_api_http_path`) ensures
12999    // drift between the two axes' rule enforcement is a build error
13000    // at the predicate.
13001
13002    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
13003        // Fresh spec per call so the would-be-duplicate edge
13004        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
13005        // `three_member_spec`'s pre-existing
13006        // `(cart, catalog, …, /products/:id)` entry — only the
13007        // endpoint payload differs.
13008        let mut s = three_member_spec();
13009        s.contratos.push(contract_http("cart", "catalog", ep));
13010        s.validate().unwrap_err()
13011    }
13012
13013    #[test]
13014    fn rejects_http_contrato_endpoint_with_query() {
13015        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
13016        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
13017        // rule the L7 matcher would never satisfy.
13018        let err = contrato_endpoint_err("/charge?token=X");
13019        assert!(
13020            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13021                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
13022            "got {err:?}"
13023        );
13024    }
13025
13026    #[test]
13027    fn rejects_http_contrato_endpoint_with_fragment() {
13028        let err = contrato_endpoint_err("/charge#frag");
13029        assert!(
13030            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13031                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
13032            "got {err:?}"
13033        );
13034    }
13035
13036    #[test]
13037    fn rejects_http_contrato_endpoint_with_whitespace() {
13038        let err = contrato_endpoint_err("/foo bar");
13039        assert!(
13040            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13041                if endpoint == "/foo bar" && reason.contains("whitespace")),
13042            "got {err:?}"
13043        );
13044    }
13045
13046    #[test]
13047    fn rejects_http_contrato_endpoint_with_control_char() {
13048        let err = contrato_endpoint_err("/api/\x01bar");
13049        assert!(
13050            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13051                if endpoint == "/api/\x01bar" && reason.contains("control character")),
13052            "got {err:?}"
13053        );
13054    }
13055
13056    #[test]
13057    fn rejects_http_contrato_endpoint_with_non_ascii() {
13058        let err = contrato_endpoint_err("/api/café");
13059        assert!(
13060            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13061                if endpoint == "/api/café" && reason.contains("non-ASCII")),
13062            "got {err:?}"
13063        );
13064    }
13065
13066    #[test]
13067    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
13068        let err = contrato_endpoint_err("/api//cart");
13069        assert!(
13070            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13071                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
13072            "got {err:?}"
13073        );
13074    }
13075
13076    #[test]
13077    fn rejects_http_contrato_endpoint_with_dot_segment() {
13078        let err = contrato_endpoint_err("/api/./cart");
13079        assert!(
13080            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13081                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
13082            "got {err:?}"
13083        );
13084    }
13085
13086    #[test]
13087    fn rejects_http_contrato_endpoint_with_parent_segment() {
13088        // Path-traversal in a contrato endpoint is the canonical
13089        // "L7 rule that the workload's HTTP server's path-resolution
13090        // logic interprets differently than the policy enforcer"
13091        // footgun. Rejected outright at validate time.
13092        let err = contrato_endpoint_err("/api/../etc");
13093        assert!(
13094            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13095                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
13096            "got {err:?}"
13097        );
13098    }
13099
13100    #[test]
13101    fn rejects_http_contrato_endpoint_too_long() {
13102        // 1025-byte endpoint — one over the Gateway API
13103        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
13104        // path matcher has no inherent length limit but the policy
13105        // CR itself rides through the K8s apiserver, which enforces
13106        // ConfigMap-shaped limits; sharing the Gateway API cap is the
13107        // conservative floor.
13108        let big = format!("/api/{}", "a".repeat(1020));
13109        assert_eq!(big.len(), 1025);
13110        let err = contrato_endpoint_err(&big);
13111        assert!(
13112            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
13113                if endpoint == &big && reason.contains("max length of 1024")),
13114            "got {err:?}"
13115        );
13116    }
13117
13118    #[test]
13119    fn http_contrato_endpoint_max_length_validates() {
13120        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
13121        // in the cap surfaces here and at
13122        // `rejects_http_contrato_endpoint_too_long` simultaneously,
13123        // mirroring `entrada_path_max_length_validates` on the peer
13124        // axis.
13125        let big = format!("/api/{}", "a".repeat(1019));
13126        assert_eq!(big.len(), 1024);
13127        let mut s = three_member_spec();
13128        s.contratos.push(contract_http("cart", "catalog", &big));
13129        s.validate().unwrap();
13130    }
13131
13132    #[test]
13133    fn http_contrato_endpoint_accepts_canonical_forms() {
13134        // Positive-set sweep: every canonical HTTP-path shape the
13135        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
13136        // plain paths, hidden-file-style `.config` segments distinct
13137        // from the `.` segment, digit-bearing segments, the canonical
13138        // route-template `:param` form, trailing-slash form,
13139        // percent-encoded segments, the `/foo..bar` interior-`..`-
13140        // substring forms that are NOT `..` segments) must remain a
13141        // valid contrato endpoint too. Drift between this list and
13142        // the entrada path positive sweep surfaces at the shared
13143        // `is_gateway_api_http_path` substrate-side suite — one
13144        // source of truth. Uses a fresh `(payment, catalog)` edge so
13145        // none of the swept endpoints collide with the pre-existing
13146        // `(cart, catalog, /products/:id)` / `(cart, payment,
13147        // /charge)` entries in `three_member_spec`.
13148        for ep in [
13149            "/",
13150            "/charge",
13151            "/v1/charge",
13152            "/api/.config",
13153            "/products/:id",
13154            "/api/cart/",
13155            "/api/caf%C3%A9",
13156            "/foo..bar",
13157            "/...",
13158        ] {
13159            let mut s = three_member_spec();
13160            s.contratos.push(contract_http("payment", "catalog", ep));
13161            s.validate()
13162                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
13163        }
13164    }
13165
13166    #[test]
13167    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
13168        // Ordering pin: `ContratoEndpointEmpty` is the more self-
13169        // locating diagnostic on `""` and must lead — the value-
13170        // shape gate is only reached after the empty-check fires.
13171        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
13172        // on the peer axis.
13173        let mut s = three_member_spec();
13174        s.contratos.push(WitContract {
13175            de: "cart".into(),
13176            para: "catalog".into(),
13177            wit: "wasi:http/proxy".into(),
13178            endpoint: Some(String::new()),
13179            subject: None,
13180            slot: None,
13181        });
13182        let err = s.validate().unwrap_err();
13183        assert!(
13184            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13185            "got {err:?}"
13186        );
13187    }
13188
13189    #[test]
13190    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
13191        // Ordering pin: an endpoint without a leading `/` surfaces the
13192        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
13193        // value-shape gate is only consulted on endpoints that already
13194        // satisfy the absolute-prefix invariant. Mirrors
13195        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
13196        let err = contrato_endpoint_err("bad path");
13197        assert!(
13198            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
13199                if endpoint == "bad path"),
13200            "got {err:?}"
13201        );
13202    }
13203
13204    #[test]
13205    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
13206        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
13207        // `:para` + a non-empty reason flow through verbatim so the
13208        // author can grep their caixa.lisp for the offending contrato
13209        // block and fix it in one edit. Same shape as
13210        // `entrada_path_diagnostic_carries_offending_path`.
13211        let err = contrato_endpoint_err("/api?q=1");
13212        match err {
13213            AplicacaoError::ContratoEndpointInvalid {
13214                de,
13215                para,
13216                endpoint,
13217                reason,
13218            } => {
13219                assert_eq!(de, "cart");
13220                assert_eq!(para, "catalog");
13221                assert_eq!(endpoint, "/api?q=1");
13222                assert!(!reason.is_empty(), "reason field must be non-empty");
13223            }
13224            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
13225        }
13226    }
13227
13228    #[test]
13229    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
13230        // The compounding theorem: every &str inside a WitTarget
13231        // returned by target() is non-empty (and absolute, for Http).
13232        // Renderers downstream of typed_view() can rely on this
13233        // without re-checking — the type system carries the proof.
13234        let http = contract_http("cart", "catalog", "/x");
13235        match http.target().unwrap() {
13236            WitTarget::Http { endpoint } => {
13237                assert!(!endpoint.is_empty());
13238                assert!(endpoint.starts_with('/'));
13239            }
13240            other => panic!("expected Http, got {other:?}"),
13241        }
13242        let nats = WitContract {
13243            de: "a".into(),
13244            para: "b".into(),
13245            wit: "nats:pub-sub".into(),
13246            endpoint: None,
13247            subject: Some("topic.x".into()),
13248            slot: None,
13249        };
13250        match nats.target().unwrap() {
13251            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
13252            other => panic!("expected PubSub, got {other:?}"),
13253        }
13254        let kv = WitContract {
13255            de: "a".into(),
13256            para: "b".into(),
13257            wit: "wasi:keyvalue/store".into(),
13258            endpoint: None,
13259            subject: None,
13260            slot: Some("checkout/$orderId".into()),
13261        };
13262        match kv.target().unwrap() {
13263            WitTarget::Store { slot } => assert!(!slot.is_empty()),
13264            other => panic!("expected Store, got {other:?}"),
13265        }
13266    }
13267
13268    #[test]
13269    fn target_diagnostic_names_offending_endpoint_value() {
13270        // When the malformed endpoint string is non-trivial, the
13271        // diagnostic carries the actual value back to the author —
13272        // not a generic "endpoint malformed" error.
13273        let bad = WitContract {
13274            de: "src".into(),
13275            para: "dst".into(),
13276            wit: "wasi:http/proxy".into(),
13277            endpoint: Some("api/v1/charge".into()),
13278            subject: None,
13279            slot: None,
13280        };
13281        match bad.target().unwrap_err() {
13282            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
13283                assert_eq!(de, "src");
13284                assert_eq!(para, "dst");
13285                assert_eq!(endpoint, "api/v1/charge");
13286            }
13287            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
13288        }
13289    }
13290
13291    #[test]
13292    fn rejects_unknown_wit_with_target_set() {
13293        let mut s = three_member_spec();
13294        s.contratos.push(WitContract {
13295            de: "cart".into(),
13296            para: "catalog".into(),
13297            wit: "custom:exchange".into(),
13298            endpoint: Some("/leaked".into()),
13299            subject: None,
13300            slot: None,
13301        });
13302        let err = s.validate().unwrap_err();
13303        assert!(matches!(
13304            err,
13305            AplicacaoError::ContratoWrongTarget {
13306                expected: WitTarget::CAPABILITY_EXPECTED,
13307                ..
13308            }
13309        ));
13310    }
13311
13312    #[test]
13313    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
13314        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
13315        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
13316        // fourth arm of the same "which payload field name goes in the
13317        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
13318        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13319        // consts cover on the peer HTTP / PubSub / Store arms
13320        // (`wit_target_field_name_pins_per_variant`). Until this lift
13321        // landed the byte-string sat twice — once inline in the
13322        // [`WitContract::target`] Capability-arm rejection at the
13323        // production dispatch, once in `rejects_unknown_wit_with_target_set`
13324        // pinning against the same literal — with no compile-time link
13325        // between them. Same "one canonical declaration, next to the
13326        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
13327        // lift established for the payload-less arm's human-readable
13328        // label axis; this test is the shape peer of
13329        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
13330        // pair (routes-through-const + scalar-value pin) on the
13331        // wrong-target diagnostic-scalar axis.
13332        //
13333        // Fail-before-pass-after was verified locally by mutating the
13334        // const declaration to `"capability"` — the scalar-value pin
13335        // below fires (`"capability" != "none"`) and the routes-through
13336        // assertion below still holds (production and const walk in
13337        // lockstep), which is the correct behavior: a rename on the
13338        // const drifts here first, not at a downstream consumer.
13339        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
13340
13341        let mut s = three_member_spec();
13342        s.contratos.push(WitContract {
13343            de: "cart".into(),
13344            para: "catalog".into(),
13345            wit: "custom:exchange".into(),
13346            endpoint: Some("/leaked".into()),
13347            subject: None,
13348            slot: None,
13349        });
13350        match s.validate().unwrap_err() {
13351            AplicacaoError::ContratoWrongTarget { expected, .. } => {
13352                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
13353            }
13354            other => panic!("expected ContratoWrongTarget, got {other:?}"),
13355        }
13356    }
13357
13358    #[test]
13359    fn unknown_wit_capability_only_validates() {
13360        let mut s = three_member_spec();
13361        s.contratos.push(WitContract {
13362            de: "cart".into(),
13363            para: "catalog".into(),
13364            // A WIT world we haven't yet shaped — accept it as a typed
13365            // capability edge so authors aren't blocked while the WIT
13366            // registry catches up. No payload field may be carried.
13367            wit: "custom:exchange".into(),
13368            endpoint: None,
13369            subject: None,
13370            slot: None,
13371        });
13372        s.validate().unwrap();
13373        let added = s.contratos.last().unwrap();
13374        assert_eq!(added.target().unwrap(), WitTarget::Capability);
13375    }
13376
13377    #[test]
13378    fn target_typed_view_round_trips_each_shape() {
13379        let http = contract_http("cart", "catalog", "/products/:id");
13380        assert_eq!(
13381            http.target().unwrap(),
13382            WitTarget::Http {
13383                endpoint: "/products/:id"
13384            }
13385        );
13386        let nats = WitContract {
13387            de: "a".into(),
13388            para: "b".into(),
13389            wit: "nats:pub-sub".into(),
13390            endpoint: None,
13391            subject: Some("topic.x".into()),
13392            slot: None,
13393        };
13394        assert_eq!(
13395            nats.target().unwrap(),
13396            WitTarget::PubSub { subject: "topic.x" }
13397        );
13398        let kv = WitContract {
13399            de: "a".into(),
13400            para: "b".into(),
13401            wit: "wasi:keyvalue/store".into(),
13402            endpoint: None,
13403            subject: None,
13404            slot: Some("checkout/$orderId".into()),
13405        };
13406        assert_eq!(
13407            kv.target().unwrap(),
13408            WitTarget::Store {
13409                slot: "checkout/$orderId"
13410            }
13411        );
13412    }
13413
13414    #[test]
13415    fn wit_contract_kind_predicates() {
13416        let http = contract_http("a", "b", "/x");
13417        assert!(http.is_http());
13418        assert!(!http.is_pubsub());
13419        assert!(!http.is_store());
13420        assert!(!http.is_capability());
13421
13422        let nats = WitContract {
13423            de: "a".into(),
13424            para: "b".into(),
13425            wit: "nats:pub-sub".into(),
13426            endpoint: None,
13427            subject: Some("topic.x".into()),
13428            slot: None,
13429        };
13430        assert!(nats.is_pubsub());
13431        assert!(!nats.is_http());
13432        assert!(!nats.is_capability());
13433
13434        let kv = WitContract {
13435            de: "a".into(),
13436            para: "b".into(),
13437            wit: "wasi:keyvalue/store".into(),
13438            endpoint: None,
13439            subject: None,
13440            slot: Some("checkout/$orderId".into()),
13441        };
13442        assert!(kv.is_store());
13443        assert!(!kv.is_http());
13444        assert!(!kv.is_capability());
13445
13446        // Fourth arm on the paired closed-set predicate family: the
13447        // payload-less capability edge that projects to the payload-
13448        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
13449        // Extends the 3-arm predicate sweep this test opened to cover
13450        // the closed 4-way partition [`WitContract::is_capability`]
13451        // closes on the pre-projection WIT-shape axis, matched with the
13452        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
13453        // 4-arm predicate set.
13454        let cap = WitContract {
13455            de: "a".into(),
13456            para: "b".into(),
13457            wit: "custom:capability-only".into(),
13458            endpoint: None,
13459            subject: None,
13460            slot: None,
13461        };
13462        assert!(cap.is_capability());
13463        assert!(!cap.is_http());
13464        assert!(!cap.is_pubsub());
13465        assert!(!cap.is_store());
13466    }
13467
13468    // ── :contratos :wit value-shape gate ─────────────────────────────────
13469    //
13470    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
13471    // dispatch-discriminator axis. Until this gate landed
13472    // `WitContract::target()` accepted any non-empty string and
13473    // silently demoted unrecognized shapes to a capability-only L4
13474    // edge — the canonical "I thought I had L7 HTTP routing, got
13475    // L4-only" footgun. Every authoring footgun the WIT registry's
13476    // own grammar rejects (uppercase, hyphen-for-colon typo,
13477    // whitespace, empty package, doubled `@`, …) now becomes a
13478    // caixa-build-time `ContratoWitInvalid` with the offending
13479    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
13480    // as `ContratoEndpointInvalid` on the sibling axis; same shared
13481    // predicate (`crate::render::is_wit_world_ref`) ensures drift
13482    // between any two axes' rule enforcement is a build error at the
13483    // predicate, not piecemeal across renderers.
13484
13485    fn contrato_wit_err(wit: &str) -> AplicacaoError {
13486        // Fresh spec per call so the new contract doesn't collide on
13487        // identity with `three_member_spec`'s pre-existing entries.
13488        // The new edge uses `(payment, catalog)` — a pair the fixture
13489        // doesn't already declare — with no payload field set, so the
13490        // wit-shape gate fires before any payload-shape arm.
13491        let mut s = three_member_spec();
13492        s.contratos.push(WitContract {
13493            de: "payment".into(),
13494            para: "catalog".into(),
13495            wit: wit.into(),
13496            endpoint: None,
13497            subject: None,
13498            slot: None,
13499        });
13500        s.validate().unwrap_err()
13501    }
13502
13503    #[test]
13504    fn rejects_wit_with_uppercase_namespace() {
13505        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
13506        // didn't match the lowercase `wasi:http/` prefix is_http() keys
13507        // off, so the dispatch fell through to the capability arm and
13508        // the contract silently rendered as an L4-only Cilium edge.
13509        // The new gate surfaces the uppercase typo at validate time
13510        // with the offending `:wit` named.
13511        let err = contrato_wit_err("WASI:http/proxy");
13512        assert!(
13513            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13514                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
13515            "got {err:?}"
13516        );
13517    }
13518
13519    #[test]
13520    fn rejects_wit_with_hyphen_for_colon_typo() {
13521        // The canonical "I forgot the `:` separator" typo — pre-gate
13522        // this passed as Capability silently, so the renderer emitted
13523        // an L4-only policy where the author expected L7 HTTP rules.
13524        let err = contrato_wit_err("wasi-http/proxy");
13525        assert!(
13526            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13527                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
13528            "got {err:?}"
13529        );
13530    }
13531
13532    #[test]
13533    fn rejects_wit_with_multiple_colons() {
13534        // Doubled `:` — the namespace/package split has nowhere to
13535        // anchor, so the dispatch silently demotes to Capability.
13536        let err = contrato_wit_err("wasi:http:proxy");
13537        assert!(
13538            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13539                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
13540            "got {err:?}"
13541        );
13542    }
13543
13544    #[test]
13545    fn rejects_wit_with_empty_package() {
13546        // `wasi:` — namespace alone with no package. Pre-gate this
13547        // failed neither the is_http nor is_pubsub nor is_store
13548        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
13549        // a bare `wasi:`), so it silently demoted to Capability.
13550        let err = contrato_wit_err("wasi:");
13551        assert!(
13552            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13553                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
13554            "got {err:?}"
13555        );
13556    }
13557
13558    #[test]
13559    fn rejects_wit_with_underscore() {
13560        // Underscore — WIT identifiers are kebab-case, same rule
13561        // DNS-1123 enforces on its peer axes. The diagnostic carries
13562        // the explicit "use `-` instead" remediation.
13563        let err = contrato_wit_err("wasi:http_proxy");
13564        assert!(
13565            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13566                if wit == "wasi:http_proxy" && reason.contains('_')),
13567            "got {err:?}"
13568        );
13569    }
13570
13571    #[test]
13572    fn rejects_wit_with_whitespace() {
13573        // Whitespace mid-token — the prefix check matches but the
13574        // package-and-onward parse silently demoted to Capability.
13575        let err = contrato_wit_err("wasi:http proxy");
13576        assert!(
13577            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13578                if wit == "wasi:http proxy" && reason.contains("whitespace")),
13579            "got {err:?}"
13580        );
13581    }
13582
13583    #[test]
13584    fn rejects_wit_with_non_ascii() {
13585        // Un-percent-encoded non-ASCII byte — the canonical "I copied
13586        // the package name from a doc with smart quotes / accented
13587        // characters" footgun.
13588        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
13589        assert!(
13590            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13591                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
13592            "got {err:?}"
13593        );
13594    }
13595
13596    #[test]
13597    fn rejects_wit_with_consecutive_hyphens() {
13598        // `pub--sub` — WIT identifiers join words with single hyphens.
13599        let err = contrato_wit_err("nats:pub--sub");
13600        assert!(
13601            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13602                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
13603            "got {err:?}"
13604        );
13605    }
13606
13607    #[test]
13608    fn rejects_wit_with_trailing_at_no_version() {
13609        // `wasi:http/proxy@` — the version-suffix author started to
13610        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
13611        // parser would reject this; surface it at validate time.
13612        let err = contrato_wit_err("wasi:http/proxy@");
13613        assert!(
13614            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13615                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
13616            "got {err:?}"
13617        );
13618    }
13619
13620    #[test]
13621    fn rejects_wit_too_long() {
13622        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
13623        // The legitimate-shape arms all pass (lowercase, single `:`,
13624        // kebab-case identifiers); only the cap arm fires. Surfaces
13625        // the paste-from-binary / accidental-multi-line-blob landing
13626        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
13627        // on the peer axis.
13628        let big = format!("wasi:{}", "a".repeat(124));
13629        assert_eq!(big.len(), 129);
13630        let err = contrato_wit_err(&big);
13631        assert!(
13632            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
13633                if wit == &big && reason.contains("max length of 128")),
13634            "got {err:?}"
13635        );
13636    }
13637
13638    #[test]
13639    fn wit_max_length_validates() {
13640        // 128-byte WIT reference — exactly the cap. Boundary pin:
13641        // drift in the cap surfaces here and at `rejects_wit_too_long`
13642        // simultaneously, mirroring
13643        // `http_contrato_endpoint_max_length_validates` on the peer
13644        // axis.
13645        let big = format!("wasi:{}", "a".repeat(123));
13646        assert_eq!(big.len(), 128);
13647        let mut s = three_member_spec();
13648        s.contratos.push(WitContract {
13649            de: "payment".into(),
13650            para: "catalog".into(),
13651            wit: big,
13652            endpoint: None,
13653            subject: None,
13654            slot: None,
13655        });
13656        s.validate().unwrap();
13657    }
13658
13659    #[test]
13660    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
13661        // Positive-set sweep through the AplicacaoSpec::validate
13662        // surface (rather than the substrate-side predicate directly)
13663        // — pins every shape the existing test fixtures + the
13664        // checkout-aplicacao example carry, so the gate's accept-set
13665        // matches the substrate's emit-set. Drift between this list
13666        // and `render::tests::wit_world_ref_accepts_canonical_forms`
13667        // surfaces at the substrate layer's positive sweep — one
13668        // source of truth for the rule.
13669        for wit in [
13670            "wasi:http/proxy",
13671            "wasi:keyvalue/store",
13672            "nats:pub-sub",
13673            "kafka:topic",
13674            "custom:exchange",
13675            "pleme:cap/audit",
13676            "wasi:http/proxy@0.2.0",
13677        ] {
13678            // Payload field paired to the dispatched WIT shape so the
13679            // shape-↔-target arm doesn't fire instead of the wit-shape
13680            // arm we're exercising. Routes off the same
13681            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
13682            // `wit_shape_is_store` free functions the production
13683            // `WitContract::is_http` / `is_pubsub` / `is_store`
13684            // methods delegate to (both consult the lifted
13685            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
13686            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
13687            // future prefix addition to the routing accept-set
13688            // reaches this test's payload-dispatch arm by
13689            // construction — no per-test-site drift can hide a
13690            // shape-→-target-slot mismatch that would silently
13691            // demote a canonical `:wit` value to the
13692            // `(None, None, None)` capability-only arm and let the
13693            // `AplicacaoSpec::validate` positive sweep pass on a
13694            // shape it should exercise as HTTP / pub-sub / store.
13695            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
13696                (Some("/x".into()), None, None)
13697            } else if wit_shape_is_pubsub(wit) {
13698                (None, Some("topic.x".into()), None)
13699            } else if wit_shape_is_store(wit) {
13700                (None, None, Some("bucket/$key".into()))
13701            } else {
13702                (None, None, None)
13703            };
13704            let mut s = three_member_spec();
13705            s.contratos.push(WitContract {
13706                de: "payment".into(),
13707                para: "catalog".into(),
13708                wit: wit.into(),
13709                endpoint,
13710                subject,
13711                slot,
13712            });
13713            s.validate()
13714                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
13715        }
13716    }
13717
13718    #[test]
13719    fn wit_shape_predicates_accept_canonical_prefix_set() {
13720        // Positive-set sweep pinning every prefix in
13721        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
13722        // WIT_STORE_SHAPE_PREFIXES against the three free-function
13723        // dispatch predicates. The six prefixes are the load-bearing
13724        // routing keys the substrate's WIT-shape dispatch consults
13725        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
13726        // key/value-store-slot admission); any drift between the
13727        // free-function accept-set and this list surfaces here
13728        // rather than at apply time as a silent
13729        // shape-→-capability-only demotion.
13730        assert!(wit_shape_is_http("wasi:http/proxy"));
13731        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
13732        assert!(wit_shape_is_http("http:incoming"));
13733
13734        assert!(wit_shape_is_pubsub("nats:pub-sub"));
13735        assert!(wit_shape_is_pubsub("kafka:topic"));
13736
13737        assert!(wit_shape_is_store("wasi:keyvalue/store"));
13738        assert!(wit_shape_is_store("kv:cache/session"));
13739    }
13740
13741    #[test]
13742    fn wit_shape_predicates_reject_uncanonical_forms() {
13743        // Negative-set pin: the six canonical prefixes are
13744        // lowercase-only (mirrors the `is_wit_world_ref` substrate
13745        // predicate's lowercase invariant — see its docstring on the
13746        // "I thought I had L7 HTTP routing, got L4-only" footgun).
13747        // The empty string, an uppercase-prefixed form, a hyphen-
13748        // instead-of-colon typo, and a bare kebab identifier all miss
13749        // every shape arm — reachable-by-construction only via the
13750        // `is_wit_world_ref` gate that admission-checks the `:wit`
13751        // value first, but pinned here so any future
13752        // free-function change (e.g. a case-insensitive
13753        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
13754        // this unit level.
13755        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
13756            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
13757            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
13758            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
13759        }
13760    }
13761
13762    #[test]
13763    fn wit_shape_predicates_partition_canonical_set() {
13764        // Every canonical prefix routes to exactly one shape arm —
13765        // the three prefix sets are pairwise disjoint. Pins the
13766        // routing property [`WitContract::target`] relies on: an
13767        // `is_http()` return of `true` guarantees `is_pubsub()` and
13768        // `is_store()` return `false`, so the shape-→-target-slot
13769        // dispatch (endpoint vs subject vs slot) is unambiguous.
13770        // Drift (e.g. a future `"kv:"` moved into the HTTP set
13771        // without removal from the store set) would silently route
13772        // one prefix to two arms and the first-matching-arm order
13773        // becomes load-bearing — this pin surfaces it as a build
13774        // error instead.
13775        for prefix in WIT_HTTP_SHAPE_PREFIXES {
13776            let sample = format!("{prefix}x");
13777            assert!(wit_shape_is_http(&sample));
13778            assert!(!wit_shape_is_pubsub(&sample));
13779            assert!(!wit_shape_is_store(&sample));
13780        }
13781        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
13782            let sample = format!("{prefix}x");
13783            assert!(!wit_shape_is_http(&sample));
13784            assert!(wit_shape_is_pubsub(&sample));
13785            assert!(!wit_shape_is_store(&sample));
13786        }
13787        for prefix in WIT_STORE_SHAPE_PREFIXES {
13788            let sample = format!("{prefix}x");
13789            assert!(!wit_shape_is_http(&sample));
13790            assert!(!wit_shape_is_pubsub(&sample));
13791            assert!(wit_shape_is_store(&sample));
13792        }
13793    }
13794
13795    #[test]
13796    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
13797        // Positive pin: [`wit_shape_matches`] is exactly the
13798        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
13799        // parameterized on the accept-set. Two-prefix accept-set,
13800        // one-prefix accept-set, and empty accept-set (which must
13801        // reject everything, including the empty string — an empty
13802        // `any()` fold returns `false`) all pinned so a future
13803        // reimplementation that swaps `starts_with` for `contains`,
13804        // `==`, or a case-folded comparator surfaces at unit-test
13805        // time.
13806        let two = &["wasi:http/", "http:"];
13807        assert!(wit_shape_matches("wasi:http/proxy", two));
13808        assert!(wit_shape_matches("http:incoming", two));
13809        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
13810
13811        let one = &["nats:"];
13812        assert!(wit_shape_matches("nats:pub-sub", one));
13813        assert!(!wit_shape_matches("kafka:topic", one));
13814
13815        // Empty accept-set matches nothing — the identity element
13816        // for the disjunctive `any()` fold across the prefix set.
13817        // Reachable via a future `wit_shape_is_<name>` const paired
13818        // to a still-empty prefix table on a nascent shape-arm draft.
13819        let empty: &[&str] = &[];
13820        assert!(!wit_shape_matches("wasi:http/proxy", empty));
13821        assert!(!wit_shape_matches("", empty));
13822
13823        // starts_with, not contains: a prefix embedded mid-string
13824        // never matches. Pins the routing invariant [`WitContract::target`]
13825        // relies on (an authored `:wit "custom:wasi:http/"` string
13826        // does not silently route through the HTTP arm just because
13827        // it happens to contain the canonical HTTP prefix).
13828        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
13829    }
13830
13831    #[test]
13832    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
13833        // Equivalence pin: each per-shape predicate is exactly
13834        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
13835        // every canonical prefix + the empty string + one negative
13836        // sample against every peer so a future predicate that grew
13837        // its own inline `iter().any(starts_with)` (rather than
13838        // delegating through the lifted combinator) drifts loudly here
13839        // — the peer-const table's contents must agree with the
13840        // predicate's accept-set by construction.
13841        let samples = [
13842            String::new(),
13843            "wasi:http/proxy".to_string(),
13844            "http:incoming".to_string(),
13845            "nats:pub-sub".to_string(),
13846            "kafka:topic".to_string(),
13847            "wasi:keyvalue/store".to_string(),
13848            "kv:cache/session".to_string(),
13849            "custom-shape".to_string(),
13850            "WASI:HTTP/proxy".to_string(),
13851        ];
13852        for wit in &samples {
13853            assert_eq!(
13854                wit_shape_is_http(wit),
13855                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
13856                "wit_shape_is_http drifted from combinator on {wit:?}",
13857            );
13858            assert_eq!(
13859                wit_shape_is_pubsub(wit),
13860                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
13861                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
13862            );
13863            assert_eq!(
13864                wit_shape_is_store(wit),
13865                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
13866                "wit_shape_is_store drifted from combinator on {wit:?}",
13867            );
13868        }
13869    }
13870
13871    #[test]
13872    fn wit_contract_shape_methods_delegate_to_free_functions() {
13873        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
13874        // `is_store` are `&self` conveniences on top of the free
13875        // functions — for every canonical prefix the method's return
13876        // matches its free-function peer. Sweeps the union of the
13877        // three prefix sets so a future method that grew its own
13878        // inline prefix logic (rather than delegating) drifts loudly
13879        // here on the first prefix the free function accepts and the
13880        // method doesn't.
13881        for shape_set in [
13882            WIT_HTTP_SHAPE_PREFIXES,
13883            WIT_PUBSUB_SHAPE_PREFIXES,
13884            WIT_STORE_SHAPE_PREFIXES,
13885        ] {
13886            for prefix in shape_set {
13887                let c = WitContract {
13888                    de: "cart".into(),
13889                    para: "catalog".into(),
13890                    wit: format!("{prefix}x"),
13891                    endpoint: None,
13892                    subject: None,
13893                    slot: None,
13894                };
13895                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
13896                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
13897                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
13898                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
13899            }
13900        }
13901        // Capability-arm delegation sweep: two representative
13902        // Capability-shaped `:wit` values (a bare non-prefix-matching
13903        // WIT world, the deliberately-shaped empty string
13904        // [`WitContract::is_capability`]'s docstring calls out as
13905        // syntactically Capability). Extends the free-function
13906        // delegation pin onto the fourth arm so a future
13907        // [`WitContract::is_capability`] rewrite that grew an inline
13908        // prefix-set scan (rather than delegating through
13909        // [`wit_shape_is_capability`]) drifts loudly here on the first
13910        // Capability-shaped sample.
13911        for wit in ["custom:capability-only", ""] {
13912            let c = WitContract {
13913                de: "cart".into(),
13914                para: "catalog".into(),
13915                wit: wit.into(),
13916                endpoint: None,
13917                subject: None,
13918                slot: None,
13919            };
13920            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
13921        }
13922    }
13923
13924    #[test]
13925    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
13926        // 4-way partition-witness pin on the raw `&str` axis: for every
13927        // canonical prefix in the three payload-arm accept-sets,
13928        // exactly one of the four [`wit_shape_is_http`] /
13929        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
13930        // [`wit_shape_is_capability`] free functions returns `true` and
13931        // the other three return `false` — the four-arm partition
13932        // witness that locks the free-function WIT-shape-classifier
13933        // family into a partition of the `:contratos :wit` axis
13934        // load-bearing. Peer of the sibling [`WitContract`]-surface
13935        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
13936        // partition pin — extends the discipline onto the raw `&str`
13937        // axis so any future arm addition (a hypothetical
13938        // `wasi:sockets/*` transport-layer shape, an `oci:*`
13939        // capability-import carrier per the sibling
13940        // [`wit_shape_matches`] docstring's trajectory bullet) that
13941        // landed on one of the payload-arm free functions without
13942        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
13943        // here as two arms returning `true` simultaneously at
13944        // caixa-core build time rather than a silent per-consumer
13945        // misclassification at renderer emit time.
13946        for shape_set in [
13947            WIT_HTTP_SHAPE_PREFIXES,
13948            WIT_PUBSUB_SHAPE_PREFIXES,
13949            WIT_STORE_SHAPE_PREFIXES,
13950        ] {
13951            for prefix in shape_set {
13952                let wit = format!("{prefix}x");
13953                let hits = [
13954                    wit_shape_is_http(&wit),
13955                    wit_shape_is_pubsub(&wit),
13956                    wit_shape_is_store(&wit),
13957                    wit_shape_is_capability(&wit),
13958                ]
13959                .iter()
13960                .filter(|&&b| b)
13961                .count();
13962                assert_eq!(
13963                    hits,
13964                    1,
13965                    "raw-&str WIT-shape 4-way predicate partition must \
13966                     admit exactly one arm per canonical prefix; got {hits} \
13967                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
13968                     is_capability={})",
13969                    wit_shape_is_http(&wit),
13970                    wit_shape_is_pubsub(&wit),
13971                    wit_shape_is_store(&wit),
13972                    wit_shape_is_capability(&wit),
13973                );
13974            }
13975        }
13976        // Capability-arm sweep on the raw `&str` axis: two
13977        // representative Capability-shaped `:wit` values (a bare non-
13978        // prefix-matching WIT world, the deliberately-shaped empty
13979        // string the pure classifier still admits per
13980        // [`wit_shape_is_capability`]'s docstring). Both must land on
13981        // the fourth arm exclusively so the partition witness holds
13982        // across the full 4-arm closure on the raw `&str` axis.
13983        for wit in ["custom:capability-only", ""] {
13984            let hits = [
13985                wit_shape_is_http(wit),
13986                wit_shape_is_pubsub(wit),
13987                wit_shape_is_store(wit),
13988                wit_shape_is_capability(wit),
13989            ]
13990            .iter()
13991            .filter(|&&b| b)
13992            .count();
13993            assert_eq!(
13994                hits, 1,
13995                "raw-&str WIT-shape 4-way predicate partition must \
13996                 admit exactly one arm on Capability-shaped wit={wit:?}"
13997            );
13998            assert!(
13999                wit_shape_is_capability(wit),
14000                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
14001            );
14002        }
14003    }
14004
14005    #[test]
14006    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
14007        // Composition-witness pin: [`wit_shape_is_capability`] is the
14008        // exact-inverse disjunction of the sibling payload-arm free-
14009        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
14010        // / [`wit_shape_is_store`]. A future reimplementation that
14011        // grew its own prefix-set scan (e.g. inlining a fourth
14012        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
14013        // not own today) rather than delegating to the sibling trio
14014        // would drift loudly here — the composition contract binds the
14015        // fourth-arm free-function predicate to the exact-inverse of
14016        // the three payload-arm free-function predicates, so any
14017        // rebrand of any prefix-set const flows through
14018        // [`wit_shape_is_capability`] by construction without a
14019        // coordinated per-consumer rewrite. Peer of the sibling
14020        // [`WitContract`]-surface
14021        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
14022        // composition pin — extends the discipline onto the raw
14023        // `&str` axis.
14024        let mut cases: Vec<String> = Vec::new();
14025        for shape_set in [
14026            WIT_HTTP_SHAPE_PREFIXES,
14027            WIT_PUBSUB_SHAPE_PREFIXES,
14028            WIT_STORE_SHAPE_PREFIXES,
14029        ] {
14030            for prefix in shape_set {
14031                cases.push(format!("{prefix}x"));
14032            }
14033        }
14034        cases.push("custom:capability-only".to_string());
14035        cases.push(String::new());
14036        for wit in cases {
14037            assert_eq!(
14038                wit_shape_is_capability(&wit),
14039                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
14040                "wit_shape_is_capability must equal \
14041                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
14042                 at wit={wit:?}"
14043            );
14044        }
14045    }
14046
14047    #[test]
14048    fn wit_shape_classifier_family_is_const_fn() {
14049        // Fail-before-pass-after pin on the 4-arm free-function WIT-
14050        // shape classifier family's `const`-eval posture. Each of the
14051        // four peer classifiers ([`wit_shape_is_http`] /
14052        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
14053        // [`wit_shape_is_capability`]) and the underlying combinator
14054        // [`wit_shape_matches`] must be `pub const fn` — any future
14055        // accidental downgrade to non-`const` fails the `const fn`
14056        // wrappers below at caixa-core build time with E0015
14057        // (`cannot call non-const function`), strictly stronger than
14058        // a runtime `assert!` and strictly stronger than the module-
14059        // scope `const _: () = assert!(…)` pins immediately after the
14060        // classifier declarations (those anchor specific accept-set
14061        // truth-table entries; this pin anchors the `const` posture
14062        // itself via `const fn` wrappers that are only well-formed
14063        // when the callee is itself `const fn`).
14064        //
14065        // Verified fail-before-pass-after by locally reverting
14066        // `pub const fn` → `pub fn` on each classifier and observing
14067        // E0015 at every corresponding wrapper call site (build
14068        // error, no test-time surface), then restoring `pub const fn`
14069        // and observing the pin pass at test time. Peer of the
14070        // sibling M3
14071        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
14072        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
14073        // M2
14074        // [`child_spec_restart_accessor_is_const_fn`] /
14075        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
14076        // and M3
14077        // [`placement_estrategia_accessor_is_const_fn`] /
14078        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
14079        // sibling `const`-eval-surface-pass axes.
14080        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
14081            wit_shape_matches(wit, prefixes)
14082        }
14083        const fn http_via_const_fn(wit: &str) -> bool {
14084            wit_shape_is_http(wit)
14085        }
14086        const fn pubsub_via_const_fn(wit: &str) -> bool {
14087            wit_shape_is_pubsub(wit)
14088        }
14089        const fn store_via_const_fn(wit: &str) -> bool {
14090            wit_shape_is_store(wit)
14091        }
14092        const fn capability_via_const_fn(wit: &str) -> bool {
14093            wit_shape_is_capability(wit)
14094        }
14095        // Sweep one canonical accept-set sample per arm plus the
14096        // payload-less/empty capability samples, asserting the
14097        // wrapper and direct dispatches agree byte-for-byte across
14098        // the closed 4-arm partition.
14099        let cases: [(&str, bool, bool, bool, bool); 6] = [
14100            ("wasi:http/proxy", true, false, false, false),
14101            ("http:incoming", true, false, false, false),
14102            ("nats:events", false, true, false, false),
14103            ("kafka:topic", false, true, false, false),
14104            ("wasi:keyvalue/store", false, false, true, false),
14105            ("kv:cache", false, false, true, false),
14106        ];
14107        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
14108            assert_eq!(
14109                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
14110                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
14111                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
14112            );
14113            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
14114            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
14115            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
14116            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
14117            assert_eq!(wit_shape_is_http(wit), is_http);
14118            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
14119            assert_eq!(wit_shape_is_store(wit), is_store);
14120        }
14121        // Payload-less capability arm (the 4th partition arm).
14122        let capability_samples: [&str; 3] =
14123            ["wasi:filesystem/preopens", "custom:capability-only", ""];
14124        for wit in capability_samples {
14125            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
14126            assert!(wit_shape_is_capability(wit));
14127            assert!(!wit_shape_is_http(wit));
14128            assert!(!wit_shape_is_pubsub(wit));
14129            assert!(!wit_shape_is_store(wit));
14130        }
14131    }
14132
14133    #[test]
14134    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
14135        // Composition-witness pin: [`wit_shape_matches`] agrees with
14136        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
14137        // dispatch (the prior non-`const` implementation) across
14138        // boundary lengths — empty `wit`, empty prefix, one-byte
14139        // slack, prefix longer than `wit`, one-byte trailing slack.
14140        // The rewrite to a byte-level manual starts_with loop (the
14141        // enabler for the `pub const fn` posture) must not change any
14142        // truth-table entry on the canonical accept-set — this pin
14143        // sweeps a targeted boundary corpus and asserts byte-for-byte
14144        // agreement, locking the const-fn rewrite's semantics against
14145        // the prior iterator body by construction.
14146        let prefixes = &["wasi:http/", "http:"][..];
14147        let cases: [(&str, bool); 12] = [
14148            ("wasi:http/proxy", true),
14149            ("wasi:http/", true), // exact-length match on prefix
14150            ("wasi:http", false), // one byte short
14151            ("http:", true),
14152            ("http:incoming", true),
14153            ("http", false), // one byte short
14154            ("", false),
14155            ("wasi:https/proxy", false),
14156            ("nats:events", false),
14157            ("HTTPS:", false), // uppercase — no case-fold in classifier
14158            ("wasi:HTTP/proxy", false),
14159            ("wasi:http", false),
14160        ];
14161        for (wit, expected) in cases {
14162            assert_eq!(
14163                wit_shape_matches(wit, prefixes),
14164                expected,
14165                "wit_shape_matches disagrees with reference at wit={wit:?}",
14166            );
14167            // Byte-equal to the iterator body it replaced.
14168            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
14169            assert_eq!(
14170                wit_shape_matches(wit, prefixes),
14171                via_iter,
14172                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
14173            );
14174        }
14175        // Empty prefix set → always false regardless of `wit`.
14176        let empty: &[&str] = &[];
14177        assert!(!wit_shape_matches("", empty));
14178        assert!(!wit_shape_matches("wasi:http/proxy", empty));
14179        // Empty prefix inside a non-empty set → always true (every
14180        // string starts with the empty string, matching the
14181        // iterator body's semantics on `str::starts_with("")`).
14182        let contains_empty: &[&str] = &["nats:", ""];
14183        assert!(wit_shape_matches("", contains_empty));
14184        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
14185    }
14186
14187    #[test]
14188    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
14189        // 4-way partition-witness pin: for every canonical prefix in
14190        // the payload-arm accept-sets, exactly one of the four
14191        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
14192        // [`WitContract::is_store`] / [`WitContract::is_capability`]
14193        // predicates returns `true` and the other three return `false`
14194        // — the four-arm partition witness that locks the substrate's
14195        // WIT-shape-space closure on the pre-projection axis load-
14196        // bearing. A future arm addition (a hypothetical fourth
14197        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
14198        // shape) that landed on one of the payload-arm predicates
14199        // without shrinking [`WitContract::is_capability`]'s accept-set
14200        // would surface here as two arms returning `true` simultaneously
14201        // — a partition-witness break the pin catches at caixa-core
14202        // build time rather than a silent per-consumer misclassification
14203        // at renderer emit time. Peer of the sibling `WitTarget`-side
14204        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
14205        // partition-witness pin on the post-projection payload-scalar
14206        // arm-set — extends the discipline onto the pre-projection
14207        // 4-arm shape-space.
14208        for shape_set in [
14209            WIT_HTTP_SHAPE_PREFIXES,
14210            WIT_PUBSUB_SHAPE_PREFIXES,
14211            WIT_STORE_SHAPE_PREFIXES,
14212        ] {
14213            for prefix in shape_set {
14214                let c = WitContract {
14215                    de: "cart".into(),
14216                    para: "catalog".into(),
14217                    wit: format!("{prefix}x"),
14218                    endpoint: None,
14219                    subject: None,
14220                    slot: None,
14221                };
14222                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
14223                    .iter()
14224                    .filter(|&&b| b)
14225                    .count();
14226                assert_eq!(
14227                    hits,
14228                    1,
14229                    "WitContract WIT-shape 4-way predicate partition must \
14230                     admit exactly one arm per canonical prefix; got {hits} \
14231                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
14232                     is_capability={})",
14233                    c.wit,
14234                    c.is_http(),
14235                    c.is_pubsub(),
14236                    c.is_store(),
14237                    c.is_capability(),
14238                );
14239            }
14240        }
14241        // Capability-arm sweep: two representative capability shapes
14242        // (a bare WIT world outside the three payload-arm prefix sets,
14243        // and the deliberately-shaped empty string that
14244        // [`crate::render::is_wit_world_ref`] rejects at
14245        // [`WitContract::target`] time but which the pure classifier
14246        // still admits — see the method docstring's "purely syntactic
14247        // classification" note). Both must land on the fourth arm
14248        // exclusively, so the partition witness holds across the full
14249        // 4-arm closure.
14250        for wit in ["custom:capability-only", ""] {
14251            let c = WitContract {
14252                de: "cart".into(),
14253                para: "catalog".into(),
14254                wit: wit.into(),
14255                endpoint: None,
14256                subject: None,
14257                slot: None,
14258            };
14259            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
14260                .iter()
14261                .filter(|&&b| b)
14262                .count();
14263            assert_eq!(
14264                hits, 1,
14265                "WitContract WIT-shape 4-way predicate partition must \
14266                 admit exactly one arm on Capability-shaped wit={wit:?}"
14267            );
14268            assert!(
14269                c.is_capability(),
14270                "wit={wit:?} must project onto the Capability arm"
14271            );
14272        }
14273    }
14274
14275    #[test]
14276    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
14277        // Composition-witness pin: [`WitContract::is_capability`] is the
14278        // exact-inverse disjunction of the sibling payload-arm predicate
14279        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
14280        // [`WitContract::is_store`]. A future reimplementation that
14281        // grew its own prefix-set scan (e.g. inlining a fourth
14282        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
14283        // own today) rather than delegating to the sibling trio would
14284        // drift loudly here — the composition contract binds the
14285        // fourth-arm predicate to the exact-inverse of the three
14286        // payload-arm predicates, so any rebrand of any prefix-set const
14287        // flows through this method by construction without a
14288        // coordinated per-consumer rewrite. Sweeps the union of the
14289        // three payload-arm prefix sets plus two Capability-shaped
14290        // shapes (a bare non-prefix-matching WIT world, the deliberately-
14291        // empty string the pure classifier still admits per the method
14292        // docstring's "purely syntactic classification" note).
14293        let mut cases: Vec<String> = Vec::new();
14294        for shape_set in [
14295            WIT_HTTP_SHAPE_PREFIXES,
14296            WIT_PUBSUB_SHAPE_PREFIXES,
14297            WIT_STORE_SHAPE_PREFIXES,
14298        ] {
14299            for prefix in shape_set {
14300                cases.push(format!("{prefix}x"));
14301            }
14302        }
14303        cases.push("custom:capability-only".to_string());
14304        cases.push(String::new());
14305        for wit in cases {
14306            let c = WitContract {
14307                de: "cart".into(),
14308                para: "catalog".into(),
14309                wit: wit.clone(),
14310                endpoint: None,
14311                subject: None,
14312                slot: None,
14313            };
14314            assert_eq!(
14315                c.is_capability(),
14316                !c.is_http() && !c.is_pubsub() && !c.is_store(),
14317                "WitContract::is_capability must equal \
14318                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
14319            );
14320        }
14321    }
14322
14323    #[test]
14324    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
14325        // Cross-projection-witness pin: whenever [`WitContract::target`]
14326        // succeeds, the pre-projection [`WitContract::is_capability`]
14327        // classification agrees with the post-projection
14328        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
14329        // predicate — the 4-arm typed partition on the substrate's
14330        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
14331        // partition on the pre-projection axis line up by construction.
14332        // A future divergence between the two axes (a peer
14333        // [`WitTarget`] variant addition that landed on the typed-view
14334        // surface without a peer prefix-set + [`WitContract`] predicate
14335        // extension, or vice versa) would surface here at caixa-core
14336        // build time rather than a silent per-consumer split at renderer
14337        // emit time. Peer of the sibling pre-/post-projection
14338        // agreement pins the payload-carrier trio
14339        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
14340        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
14341        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
14342        // post-projection — b11bb49 trio lift) already carry across the
14343        // three payload arms — this pin closes the pair on the fourth
14344        // payload-less arm.
14345        let http = WitContract {
14346            de: "cart".into(),
14347            para: "catalog".into(),
14348            wit: "wasi:http/proxy".into(),
14349            endpoint: Some("/x".into()),
14350            subject: None,
14351            slot: None,
14352        };
14353        assert!(!http.is_capability());
14354        assert!(!http.target().unwrap().is_capability());
14355
14356        let nats = WitContract {
14357            de: "cart".into(),
14358            para: "catalog".into(),
14359            wit: "nats:pub-sub".into(),
14360            endpoint: None,
14361            subject: Some("events.x".into()),
14362            slot: None,
14363        };
14364        assert!(!nats.is_capability());
14365        assert!(!nats.target().unwrap().is_capability());
14366
14367        let kv = WitContract {
14368            de: "cart".into(),
14369            para: "catalog".into(),
14370            wit: "wasi:keyvalue/store".into(),
14371            endpoint: None,
14372            subject: None,
14373            slot: Some("checkout/$orderId".into()),
14374        };
14375        assert!(!kv.is_capability());
14376        assert!(!kv.target().unwrap().is_capability());
14377
14378        let cap = WitContract {
14379            de: "cart".into(),
14380            para: "catalog".into(),
14381            wit: "custom:capability-only".into(),
14382            endpoint: None,
14383            subject: None,
14384            slot: None,
14385        };
14386        assert!(cap.is_capability());
14387        assert!(cap.target().unwrap().is_capability());
14388    }
14389
14390    #[test]
14391    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
14392        // Fail-before-pass-after pin on the [`WitContract`] pre-
14393        // projection accessor family's `const`-eval-surface posture.
14394        // Each of the three per-`:contratos` byte-string scalar
14395        // accessors ([`WitContract::source`] / [`WitContract::destination`]
14396        // / [`WitContract::world_ref`], each projecting through
14397        // `String::as_str` — const-stable since Rust 1.87, well within
14398        // the workspace MSRV) and each of the four peer WIT-shape
14399        // predicates ([`WitContract::is_http`] /
14400        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
14401        // [`WitContract::is_capability`], each composing
14402        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
14403        // free-function classifier family the sibling
14404        // [`wit_shape_classifier_family_is_const_fn`] pin already
14405        // anchors on the raw `&str → bool` axis) must be `pub const fn`
14406        // — any future accidental downgrade to non-`const` fails the
14407        // `const fn` wrappers below at caixa-core build time with E0015
14408        // (`cannot call non-const function`), strictly stronger than a
14409        // runtime `assert!` and strictly stronger than a
14410        // module-scope `const _: () = assert!(…)` pin (which cannot be
14411        // formed on a `&WitContract` fixture because the type's
14412        // `String` / `Option<String>` carriers rule out `const`-context
14413        // construction; the `const fn` wrapper is the load-bearing
14414        // shape that side-steps the destructor-in-const restriction on
14415        // the value axis while still pinning the `const`-fn posture on
14416        // the callee).
14417        //
14418        // Peer of the sibling free-function classifier pin
14419        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
14420        // raw `&str → bool` axis — this pin extends the same
14421        // `const`-eval-surface discipline onto the peer method surface
14422        // that composes through those free-function classifiers, and
14423        // simultaneously onto the underlying per-`:contratos`
14424        // byte-string scalar-accessor trio each predicate reads
14425        // through. Sibling of the peer M3
14426        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
14427        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
14428        // M2
14429        // [`child_spec_restart_accessor_is_const_fn`] /
14430        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
14431        // and M3
14432        // [`placement_estrategia_accessor_is_const_fn`] /
14433        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
14434        // sibling `const`-eval-surface-pass axes.
14435        const fn source_via_const_fn(c: &WitContract) -> &str {
14436            c.source()
14437        }
14438        const fn destination_via_const_fn(c: &WitContract) -> &str {
14439            c.destination()
14440        }
14441        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
14442            c.world_ref()
14443        }
14444        const fn is_http_via_const_fn(c: &WitContract) -> bool {
14445            c.is_http()
14446        }
14447        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
14448            c.is_pubsub()
14449        }
14450        const fn is_store_via_const_fn(c: &WitContract) -> bool {
14451            c.is_store()
14452        }
14453        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
14454            c.is_capability()
14455        }
14456        // Sweep one canonical accept-set sample per WIT-shape arm plus
14457        // a payload-less capability sample, asserting the wrapper and
14458        // direct dispatches agree byte-for-byte across the closed
14459        // 4-arm partition on both the scalar-accessor trio and the
14460        // WIT-shape-predicate family.
14461        for (wit, is_http, is_pubsub, is_store, is_capability) in [
14462            ("wasi:http/proxy", true, false, false, false),
14463            ("http:incoming", true, false, false, false),
14464            ("nats:events", false, true, false, false),
14465            ("kafka:topic", false, true, false, false),
14466            ("wasi:keyvalue/store", false, false, true, false),
14467            ("kv:cache", false, false, true, false),
14468            ("custom:capability-only", false, false, false, true),
14469            ("", false, false, false, true),
14470        ] {
14471            let c = WitContract {
14472                de: "cart".into(),
14473                para: "catalog".into(),
14474                wit: wit.into(),
14475                endpoint: None,
14476                subject: None,
14477                slot: None,
14478            };
14479            assert_eq!(source_via_const_fn(&c), c.source());
14480            assert_eq!(destination_via_const_fn(&c), c.destination());
14481            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
14482            assert_eq!(is_http_via_const_fn(&c), c.is_http());
14483            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
14484            assert_eq!(is_store_via_const_fn(&c), c.is_store());
14485            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
14486            assert_eq!(c.source(), "cart");
14487            assert_eq!(c.destination(), "catalog");
14488            assert_eq!(c.world_ref(), wit);
14489            assert_eq!(c.is_http(), is_http);
14490            assert_eq!(c.is_pubsub(), is_pubsub);
14491            assert_eq!(c.is_store(), is_store);
14492            assert_eq!(c.is_capability(), is_capability);
14493        }
14494    }
14495
14496    #[test]
14497    fn wit_contract_identity_projection_accessor_is_const_fn() {
14498        // Fail-before-pass-after pin on the [`WitContract::identity`]
14499        // six-arm composite-projection accessor's `const`-eval-surface
14500        // posture. The accessor projects the typed edge's six identity
14501        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
14502        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
14503        // every callee is itself `pub const fn` ([`WitContract::source`]
14504        // / [`WitContract::destination`] / [`WitContract::world_ref`]
14505        // through `String::as_str`, const-stable since Rust 1.87;
14506        // [`WitContract::endpoint`] / [`WitContract::subject`] /
14507        // [`WitContract::slot`] through the sibling `match &self
14508        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
14509        // 0650f64 closed the const-eval surface on) and the tuple
14510        // constructor from borrowed-reference / `Option`-of-borrowed-
14511        // reference arms is trivially const. Any future accidental
14512        // downgrade fails the `identity_via_const_fn` wrapper at
14513        // caixa-core build time with E0015 (`cannot call non-const
14514        // method`), strictly stronger than a runtime `assert!` and
14515        // strictly stronger than a module-scope `const _: () =
14516        // assert!(…)` pin (which cannot be formed on a `&WitContract`
14517        // fixture because the type's `String` / `Option<String>`
14518        // carriers rule out `const`-context value construction; the
14519        // `const fn` wrapper is the load-bearing shape that side-steps
14520        // the destructor-in-const restriction on the value axis while
14521        // still pinning the `const`-fn posture on the callee — mirror
14522        // of the sibling
14523        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14524        // pin's discipline verbatim on the peer scalar-accessor
14525        // surface).
14526        //
14527        // Peer of the sibling
14528        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14529        // (279823b) pin on the six per-`:contratos` scalar-accessor
14530        // callees this composite-projection reads through — where that
14531        // pin anchors the const-eval surface at the six individual
14532        // scalar-accessor arms, this pin extends the same posture onto
14533        // the composite six-tuple projection every consumer that dedups
14534        // typed edges on the [`ContratoIdentity`] axis keys off (the
14535        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
14536        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
14537        // materializer's per-edge identity-based admission webhook; a
14538        // future L7 policy-emitter that shards CNPs by identity-tuple
14539        // rather than by name). Same fail-before-pass-after wrapper
14540        // discipline as the peer M2 / M3 accessor-family pins on the
14541        // sibling `const`-eval-surface passes.
14542        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
14543            c.identity()
14544        }
14545        // Sweep one canonical WIT-shape sample per payload-carrier arm
14546        // plus a payload-less capability sample so the pin exercises
14547        // both `Some(_)`-carrying and `None`-carrying arms on all three
14548        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
14549        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
14550        // with the direct method call on every arm of the closed WIT-
14551        // shape partition.
14552        for (wit, endpoint, subject, slot) in [
14553            ("wasi:http/proxy", Some("/checkout"), None, None),
14554            ("http:incoming", Some("/api"), None, None),
14555            ("nats:events", None, Some("orders.placed"), None),
14556            ("kafka:topic", None, Some("orders.stream"), None),
14557            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
14558            ("kv:cache", None, None, Some("session/{token}")),
14559            ("custom:capability-only", None, None, None),
14560        ] {
14561            let c = WitContract {
14562                de: "cart".into(),
14563                para: "catalog".into(),
14564                wit: wit.into(),
14565                endpoint: endpoint.map(str::to_string),
14566                subject: subject.map(str::to_string),
14567                slot: slot.map(str::to_string),
14568            };
14569            assert_eq!(identity_via_const_fn(&c), c.identity());
14570            assert_eq!(
14571                c.identity(),
14572                ("cart", "catalog", wit, endpoint, subject, slot,),
14573            );
14574        }
14575    }
14576
14577    #[test]
14578    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
14579        // Fail-before-pass-after pin on the four M3 mesh-slot
14580        // `String → &str` scalar accessors ([`Membro::nome`] /
14581        // [`Membro::versao_requirement`] on the per-`:membros` axis,
14582        // [`Entrada::hostname`] / [`Entrada::destination`] on the
14583        // per-`:entrada` axis) — each projects the typed slot's
14584        // [`String`] storage through the `pub const fn`
14585        // [`String::as_str`] (const-stable since Rust 1.87, well
14586        // within the workspace MSRV) and any future accidental
14587        // downgrade to non-`const` fails the corresponding
14588        // `<name>_via_const_fn` wrapper at caixa-core build time with
14589        // E0015 (`cannot call non-const method`), strictly stronger
14590        // than a runtime `assert!` and strictly stronger than a
14591        // module-scope `const _: () = assert!(…)` pin (which cannot
14592        // be formed on `&Membro` / `&Entrada` fixtures because the
14593        // types' `String` carriers rule out `const`-context value
14594        // construction; the `const fn` wrapper is the load-bearing
14595        // shape that side-steps the destructor-in-const restriction
14596        // on the value axis while still pinning the `const`-fn
14597        // posture on the callee — mirror of the sibling
14598        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14599        // (279823b) pin on the per-`:contratos` axis). Peer of the
14600        // sibling per-M2/M3/universal-axis `String → &str` accessor
14601        // family pins on the sibling `const`-eval-surface passes
14602        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
14603        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
14604        // typed-newtype wrapper,
14605        // [`crate::supervisor::ChildSpec::nome`] /
14606        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
14607        // M2 supervisor-tree axis,
14608        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
14609        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
14610        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
14611        // axis, and the sibling per-`:contratos`
14612        // [`WitContract::source`] / [`WitContract::destination`] /
14613        // [`WitContract::world_ref`] trio at 279823b).
14614        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
14615            m.nome()
14616        }
14617        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
14618            m.versao_requirement()
14619        }
14620        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
14621            e.hostname()
14622        }
14623        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
14624            e.destination()
14625        }
14626        for (caixa, versao) in [
14627            ("cart", "^0.1"),
14628            ("catalog-v2", "~0.2.3"),
14629            ("checkout", "*"),
14630        ] {
14631            let m = Membro {
14632                caixa: caixa.into(),
14633                versao: versao.into(),
14634            };
14635            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
14636            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
14637            assert_eq!(m.nome(), caixa);
14638            assert_eq!(m.versao_requirement(), versao);
14639        }
14640        for (host, para) in [
14641            ("cart.example.com", "cart"),
14642            ("api.checkout.io", "checkout"),
14643        ] {
14644            let e = Entrada {
14645                host: host.into(),
14646                para: para.into(),
14647                paths: vec![],
14648                port: DEFAULT_SERVICO_PORT,
14649            };
14650            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
14651            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
14652            assert_eq!(e.hostname(), host);
14653            assert_eq!(e.destination(), para);
14654        }
14655    }
14656
14657    #[test]
14658    fn m3_option_string_scalar_accessor_family_is_const_fn() {
14659        // Fail-before-pass-after pin on the five M3 mesh-slot
14660        // `Option<String> → Option<&str>` scalar accessors
14661        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
14662        // [`WitContract::slot`] on the per-`:contratos` HTTP /
14663        // pub-sub / key-value payload-carrier trio,
14664        // [`Placement::shard_key`] / [`Placement::affinity`] on the
14665        // per-`:placement` Akka-sharding-key + Adaptive-compression-
14666        // hint pair). Each accessor destructures the typed slot's
14667        // `Option<String>` storage through the `match &self.<field> {
14668        // Some(s) => Some(s.as_str()), None => None }` shape —
14669        // routing through [`String::as_str`] (const-stable since Rust
14670        // 1.87, well within the workspace MSRV) rather than the
14671        // non-const [`Option::as_deref`] the pre-lift bodies carried
14672        // — and any future accidental downgrade to non-`const` fails
14673        // the corresponding `<name>_via_const_fn` wrapper at
14674        // caixa-core build time with E0015 (`cannot call non-const
14675        // method`), strictly stronger than a runtime `assert!` and
14676        // strictly stronger than a module-scope `const _: () =
14677        // assert!(…)` pin (which cannot be formed on `&WitContract`
14678        // / `&Placement` fixtures because the types' `String` /
14679        // `Option<String>` carriers rule out `const`-context value
14680        // construction; the `const fn` wrapper is the load-bearing
14681        // shape that side-steps the destructor-in-const restriction
14682        // on the value axis while still pinning the `const`-fn
14683        // posture on the callee — mirror of the sibling
14684        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
14685        // (279823b) and
14686        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
14687        // (29c5d7e) pins on the peer `String → &str` axes at the same
14688        // structs).
14689        //
14690        // Peer of the sibling per-`Caixa` `Option<String> →
14691        // Option<&str>` accessor family pin
14692        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
14693        // on the top-level manifest's optional universal-axis surface
14694        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
14695        // `:restart-window`).
14696        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
14697            w.endpoint()
14698        }
14699        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
14700            w.subject()
14701        }
14702        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
14703            w.slot()
14704        }
14705        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
14706            p.shard_key()
14707        }
14708        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
14709            p.affinity()
14710        }
14711        // Sweep every closed shape-arm partition on the
14712        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
14713        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
14714        // pair None), key-value (`:slot` Some, sibling pair None),
14715        // and Capability (all three None) so each accessor's
14716        // Some/None arm carries a pin through the const dispatch.
14717        for (wit, endpoint, subject, slot) in [
14718            ("wasi:http/proxy", Some("/api"), None, None),
14719            ("nats:pub-sub", None, Some("orders.paid"), None),
14720            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
14721            ("custom:capability-only", None, None, None),
14722        ] {
14723            let c = WitContract {
14724                de: "cart".into(),
14725                para: "catalog".into(),
14726                wit: wit.into(),
14727                endpoint: endpoint.map(str::to_string),
14728                subject: subject.map(str::to_string),
14729                slot: slot.map(str::to_string),
14730            };
14731            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
14732            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
14733            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
14734            assert_eq!(c.endpoint(), endpoint);
14735            assert_eq!(c.subject(), subject);
14736            assert_eq!(c.slot(), slot);
14737        }
14738        // Sweep both `Some`/`None` arms on each per-`:placement`
14739        // optional-scalar so the shard-key + affinity pair carries a
14740        // const-dispatch pin on both arms.
14741        for (shard_key, affinity) in [
14742            (Some("tenantId"), Some("data-locality")),
14743            (Some("$tenantId"), None),
14744            (None, Some("low-latency")),
14745            (None, None),
14746        ] {
14747            let p = Placement {
14748                estrategia: PlacementStrategy::default(),
14749                clusters: vec![],
14750                affinity: affinity.map(str::to_string),
14751                shard_key: shard_key.map(str::to_string),
14752            };
14753            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
14754            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
14755            assert_eq!(p.shard_key(), shard_key);
14756            assert_eq!(p.affinity(), affinity);
14757        }
14758    }
14759
14760    #[test]
14761    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
14762        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
14763        // composite `Vec → &[String]` slice-return accessors on
14764        // [`Placement::clusters`] and [`Entrada::paths`]. Each
14765        // destructures the typed slot's `Vec<String>` storage through
14766        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
14767        // 1.66, well within the workspace MSRV) — any future accidental
14768        // downgrade to non-`const` fails the corresponding
14769        // `<name>_via_const_fn` wrapper at caixa-core build time with
14770        // E0015 (`cannot call non-const method`), strictly stronger
14771        // than a runtime `assert!`. Sibling of the peer
14772        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
14773        // pin on the outer-`AplicacaoSpec` reference-return family
14774        // (`:membros` / `:contratos` slice-return + `:politicas` /
14775        // `:placement` / `:entrada` composite-reference), and of the
14776        // peer M2 slice-return axis pins
14777        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
14778        // (on `SupervisorSpec::children`) and
14779        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
14780        // (on `UpgradeFromEntry::instructions`). Together the four
14781        // pins close the last unlifted reference-return accessor
14782        // family across the substrate primitive.
14783        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
14784            p.clusters()
14785        }
14786        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
14787            e.paths()
14788        }
14789        // Sweep both the empty-Vec (no author-declared entries) and
14790        // the populated-Vec arms on every slice-return accessor so
14791        // each carries a const-dispatch pin on both arms.
14792        let p_empty = Placement {
14793            estrategia: PlacementStrategy::default(),
14794            clusters: vec![],
14795            affinity: None,
14796            shard_key: None,
14797        };
14798        let p_full = Placement {
14799            estrategia: PlacementStrategy::default(),
14800            clusters: vec!["prod-a".into(), "prod-b".into()],
14801            affinity: None,
14802            shard_key: None,
14803        };
14804        assert_eq!(
14805            placement_clusters_via_const_fn(&p_empty),
14806            p_empty.clusters()
14807        );
14808        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
14809        assert!(p_empty.clusters().is_empty());
14810        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
14811        let e_empty = Entrada {
14812            host: "web.example.com".into(),
14813            para: "web".into(),
14814            paths: vec![],
14815            port: DEFAULT_SERVICO_PORT,
14816        };
14817        let e_full = Entrada {
14818            host: "web.example.com".into(),
14819            para: "web".into(),
14820            paths: vec!["/api".into(), "/health".into()],
14821            port: DEFAULT_SERVICO_PORT,
14822        };
14823        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
14824        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
14825        assert!(e_empty.paths().is_empty());
14826        assert_eq!(e_full.paths(), &["/api", "/health"]);
14827    }
14828
14829    #[test]
14830    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
14831        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
14832        // reference-return accessors — the two `Vec → &[T]` slice-
14833        // return accessors on [`AplicacaoSpec::membros`] and
14834        // [`AplicacaoSpec::contratos`] (each routes through the
14835        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
14836        // 1.66), the two `&Composite` composite-reference accessors
14837        // on [`AplicacaoSpec::politicas`] and
14838        // [`AplicacaoSpec::placement`] (each routes through a raw
14839        // `&self.<field>` borrow, trivially const), and the one
14840        // `Option<&Composite>` optional-composite-reference accessor
14841        // on [`AplicacaoSpec::entrada`] (routes through the
14842        // `pub const fn` [`Option::as_ref`], const-stable since Rust
14843        // 1.83). Any future accidental downgrade to non-`const` fails
14844        // the corresponding `<name>_via_const_fn` wrapper at caixa-
14845        // core build time with E0015 (`cannot call non-const
14846        // method`), strictly stronger than a runtime `assert!`.
14847        // Sibling of the peer inner-composite pin
14848        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
14849        // on the `Placement::clusters` + `Entrada::paths` slice-
14850        // return pair, and of the peer M2 axis pins on
14851        // [`crate::supervisor::SupervisorSpec::children`] and
14852        // [`crate::upgrade::UpgradeFromEntry::instructions`].
14853        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
14854            s.membros()
14855        }
14856        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
14857            s.contratos()
14858        }
14859        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
14860            s.politicas()
14861        }
14862        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
14863            s.placement()
14864        }
14865        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
14866            s.entrada()
14867        }
14868        // Construct both a minimal "no :entrada" (internal-only
14869        // mesh) and a full "with :entrada" (external-gateway)
14870        // fixture so the family pins both the `None`-arm (author-
14871        // omitted `:entrada`) and the `Some`-arm (author-declared
14872        // `:entrada`) on the optional-composite axis.
14873        let membro = Membro {
14874            caixa: "web".into(),
14875            versao: "^0.1".into(),
14876        };
14877        let entrada_full = Entrada {
14878            host: "web.example.com".into(),
14879            para: "web".into(),
14880            paths: vec!["/api".into()],
14881            port: DEFAULT_SERVICO_PORT,
14882        };
14883        let internal_only = AplicacaoSpec {
14884            membros: vec![membro.clone()],
14885            contratos: vec![],
14886            politicas: MeshPolicy::default(),
14887            placement: Placement::default(),
14888            entrada: None,
14889        };
14890        let with_entrada = AplicacaoSpec {
14891            membros: vec![membro],
14892            contratos: vec![],
14893            politicas: MeshPolicy::default(),
14894            placement: Placement::default(),
14895            entrada: Some(entrada_full),
14896        };
14897        assert_eq!(
14898            aplicacao_membros_via_const_fn(&internal_only),
14899            internal_only.membros()
14900        );
14901        assert_eq!(
14902            aplicacao_membros_via_const_fn(&with_entrada),
14903            with_entrada.membros()
14904        );
14905        assert_eq!(
14906            aplicacao_contratos_via_const_fn(&internal_only),
14907            internal_only.contratos()
14908        );
14909        assert!(std::ptr::eq(
14910            aplicacao_politicas_via_const_fn(&internal_only),
14911            internal_only.politicas(),
14912        ));
14913        assert!(std::ptr::eq(
14914            aplicacao_placement_via_const_fn(&internal_only),
14915            internal_only.placement(),
14916        ));
14917        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
14918        match (
14919            aplicacao_entrada_via_const_fn(&with_entrada),
14920            with_entrada.entrada(),
14921        ) {
14922            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
14923            _ => panic!(
14924                "aplicacao_entrada_via_const_fn must agree with \
14925                 AplicacaoSpec::entrada on the Some-arm reference"
14926            ),
14927        }
14928    }
14929
14930    #[test]
14931    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
14932        // Load-bearing contract pin: on every canonical
14933        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
14934        // [`WitContract::target_projected`] returns byte-equal to
14935        // [`WitContract::target`]`().unwrap()` — the post-validation
14936        // projection accessor is a thin panicking wrapper over the
14937        // pre-validation validator, no extra work in the projection
14938        // path. Any future divergence (a validator-side normalization
14939        // the projection doesn't route through, an accessor-side
14940        // caching layer the validator doesn't populate) would surface
14941        // here at caixa-core build time rather than a silent per-consumer
14942        // split at renderer emit time. Sweeps the closed 4-arm
14943        // [`WitTarget`] partition ([`WitTarget::Http`] /
14944        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
14945        // [`WitTarget::Capability`]) so every arm carries a byte-equality
14946        // pin on the two-accessor pair.
14947        for (wit, endpoint, subject, slot) in [
14948            ("wasi:http/proxy", Some("/x"), None, None),
14949            ("nats:pub-sub", None, Some("events.x"), None),
14950            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
14951            ("custom:capability-only", None, None, None),
14952        ] {
14953            let c = WitContract {
14954                de: "cart".into(),
14955                para: "catalog".into(),
14956                wit: wit.into(),
14957                endpoint: endpoint.map(str::to_string),
14958                subject: subject.map(str::to_string),
14959                slot: slot.map(str::to_string),
14960            };
14961            assert_eq!(
14962                c.target_projected(),
14963                c.target().unwrap(),
14964                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
14965            );
14966        }
14967    }
14968
14969    #[test]
14970    #[should_panic(expected = "validated by typed_view")]
14971    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
14972        // Panic-path pin: [`WitContract::target_projected`] threads the
14973        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
14974        // through its expect-panic when called on a contract whose
14975        // (`:wit`, payload) shape has not been crossed by
14976        // [`AplicacaoSpec::validate`] — a contract with a structurally-
14977        // invalid `:wit` (hyphen-for-colon typo) that would surface
14978        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
14979        // A future rebrand on the panic-message axis would land at one
14980        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
14981        // and this pin's [`should_panic(expected = …)`] literal would
14982        // migrate alongside — the pin catches drift between the const
14983        // and the accessor's `expect(…)` call by construction.
14984        let c = WitContract {
14985            de: "cart".into(),
14986            para: "catalog".into(),
14987            // Hyphen-for-colon typo: `WitContract::target` returns
14988            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
14989            // driving the [`WitContract::target_projected`] expect-panic.
14990            wit: "wasi-http/proxy".into(),
14991            endpoint: Some("/x".into()),
14992            subject: None,
14993            slot: None,
14994        };
14995        let _ = c.target_projected();
14996    }
14997
14998    #[test]
14999    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
15000        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
15001        // carries the exact byte-string the two prior open-coded
15002        // `.target().expect("validated by typed_view")` production
15003        // consumers threaded through inline before this lift converged
15004        // them onto [`WitContract::target_projected`] — the caixa-mesh
15005        // per-`(:de, :para)` CNP L7 introspection branch at
15006        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
15007        // graph` per-`:contratos` payload-column printer at
15008        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
15009        // byte-string load-bearing so a well-meaning const-side rebrand
15010        // that didn't carry a matched pin migration would surface here
15011        // at caixa-core build time rather than a silent per-consumer
15012        // panic-message drift at cluster-apply time. Peer of the
15013        // sibling [`WitTarget::CAPABILITY_LABEL`] /
15014        // [`WitTarget::CAPABILITY_EXPECTED`] /
15015        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
15016        // the paired payload-less-arm scalar-const family.
15017        assert_eq!(
15018            WitContract::PROJECTED_INVARIANT_MSG,
15019            "validated by typed_view"
15020        );
15021    }
15022
15023    #[test]
15024    fn empty_wit_takes_precedence_over_invalid() {
15025        // Ordering pin: `EmptyWit` is the more self-locating
15026        // diagnostic on `""` and must lead — the value-shape gate is
15027        // only reached after the empty-check fires. Mirrors
15028        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
15029        // the peer payload axis.
15030        let mut s = three_member_spec();
15031        s.contratos.push(WitContract {
15032            de: "payment".into(),
15033            para: "catalog".into(),
15034            wit: String::new(),
15035            endpoint: None,
15036            subject: None,
15037            slot: None,
15038        });
15039        let err = s.validate().unwrap_err();
15040        assert!(
15041            matches!(err, AplicacaoError::EmptyWit { .. }),
15042            "got {err:?}"
15043        );
15044    }
15045
15046    #[test]
15047    fn wit_invalid_fires_before_payload_shape_arm() {
15048        // Ordering pin: a malformed `:wit` surfaces *its own*
15049        // diagnostic (which names the offending wit verbatim) before
15050        // any payload-field check — a contrato whose wit is
15051        // structurally invalid AND carries a wrong target field
15052        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
15053        // because the dispatch on the wit is what decides which
15054        // payload field is "right" in the first place. Without this
15055        // ordering, the author would see "wrong target field" for a
15056        // wit that hasn't even been parsed, which doesn't name the
15057        // root cause.
15058        let mut s = three_member_spec();
15059        s.contratos.push(WitContract {
15060            de: "payment".into(),
15061            para: "catalog".into(),
15062            // Hyphen-for-colon typo + endpoint set: pre-gate this
15063            // raised `ContratoWrongTarget { expected: "none" }` (the
15064            // Capability arm rejecting the endpoint), masking the
15065            // real authoring mistake (the wit isn't `wasi:http/proxy`).
15066            wit: "wasi-http/proxy".into(),
15067            endpoint: Some("/x".into()),
15068            subject: None,
15069            slot: None,
15070        });
15071        let err = s.validate().unwrap_err();
15072        assert!(
15073            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
15074                if wit == "wasi-http/proxy"),
15075            "got {err:?}"
15076        );
15077    }
15078
15079    #[test]
15080    fn wit_invalid_diagnostic_carries_offending_wit() {
15081        // Diagnostic-shape pin — the offending `:wit` + `:de` +
15082        // `:para` + a non-empty reason flow through verbatim so the
15083        // author can grep their caixa.lisp for the offending contrato
15084        // block and fix it in one edit. Same shape as
15085        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
15086        let err = contrato_wit_err("WASI:HTTP/proxy");
15087        match err {
15088            AplicacaoError::ContratoWitInvalid {
15089                de,
15090                para,
15091                wit,
15092                reason,
15093            } => {
15094                assert_eq!(de, "payment");
15095                assert_eq!(para, "catalog");
15096                assert_eq!(wit, "WASI:HTTP/proxy");
15097                assert!(!reason.is_empty(), "reason field must be non-empty");
15098            }
15099            other => panic!("expected ContratoWitInvalid, got {other:?}"),
15100        }
15101    }
15102
15103    // ── :contratos :subject value-shape gate ─────────────────────────────
15104    //
15105    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
15106    // suites on the peer payload axes. Until this gate landed
15107    // `WitContract::target()` only refused the empty string; a
15108    // structurally invalid subject silently passed validate and the
15109    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
15110    // Subject'` on publish / subscribe, or as a silent message drop,
15111    // far from the source caixa.lisp. Every authoring footgun the
15112    // NATS server's subject parser would catch on admission now
15113    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
15114    // offending `:subject` + `:de` + `:para` named verbatim. Same
15115    // diagnostic shape as `ContratoEndpointInvalid` /
15116    // `ContratoWitInvalid` on the peer payload axes; same shared
15117    // predicate (`crate::render::is_nats_subject`) ensures drift
15118    // between any two axes' rule enforcement is a build error at the
15119    // predicate, not piecemeal across renderers.
15120
15121    fn contrato_subject_err(subject: &str) -> AplicacaoError {
15122        // Fresh spec per call so the new contract doesn't collide on
15123        // identity with `three_member_spec`'s pre-existing entries.
15124        // The new edge uses `(payment, catalog)` — a pair the fixture
15125        // doesn't already declare — with `:wit "nats:pub-sub"` and the
15126        // varying `:subject`, so the subject-shape gate fires cleanly
15127        // after the wit-shape gate (which `"nats:pub-sub"` passes).
15128        let mut s = three_member_spec();
15129        s.contratos.push(WitContract {
15130            de: "payment".into(),
15131            para: "catalog".into(),
15132            wit: "nats:pub-sub".into(),
15133            endpoint: None,
15134            subject: Some(subject.into()),
15135            slot: None,
15136        });
15137        s.validate().unwrap_err()
15138    }
15139
15140    #[test]
15141    fn rejects_pubsub_contrato_subject_with_whitespace() {
15142        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
15143        // landed at the NATS server as a malformed subject the parser
15144        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
15145        // source caixa.lisp.
15146        let err = contrato_subject_err("foo bar");
15147        assert!(
15148            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15149                if subject == "foo bar" && reason.contains("whitespace")),
15150            "got {err:?}"
15151        );
15152    }
15153
15154    #[test]
15155    fn rejects_pubsub_contrato_subject_with_control_char() {
15156        let err = contrato_subject_err("foo\x01bar");
15157        assert!(
15158            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15159                if subject == "foo\x01bar" && reason.contains("control character")),
15160            "got {err:?}"
15161        );
15162    }
15163
15164    #[test]
15165    fn rejects_pubsub_contrato_subject_with_non_ascii() {
15166        // Un-percent-encoded non-ASCII byte — the canonical "I copied
15167        // the subject from a doc with smart quotes / accented
15168        // characters" footgun.
15169        let err = contrato_subject_err("foo.caf\u{e9}");
15170        assert!(
15171            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15172                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
15173            "got {err:?}"
15174        );
15175    }
15176
15177    #[test]
15178    fn rejects_pubsub_contrato_subject_with_leading_dot() {
15179        // Empty leading token — NATS rejects.
15180        let err = contrato_subject_err(".foo");
15181        assert!(
15182            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15183                if subject == ".foo" && reason.contains("must not start with `.`")),
15184            "got {err:?}"
15185        );
15186    }
15187
15188    #[test]
15189    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
15190        // Empty trailing token — NATS rejects. The remediation
15191        // (use `>` instead) is in the reason string.
15192        let err = contrato_subject_err("foo.");
15193        assert!(
15194            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15195                if subject == "foo." && reason.contains("must not end with `.`")),
15196            "got {err:?}"
15197        );
15198    }
15199
15200    #[test]
15201    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
15202        // The canonical "I forgot to fill in the middle segment"
15203        // typo — `"foo..bar"`. NATS rejects empty tokens.
15204        let err = contrato_subject_err("foo..bar");
15205        assert!(
15206            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15207                if subject == "foo..bar" && reason.contains("consecutive `.`")),
15208            "got {err:?}"
15209        );
15210    }
15211
15212    #[test]
15213    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
15214        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
15215        // as the final segment. Pre-gate this passed as a typed edge
15216        // and surfaced at runtime as a NATS subscribe rejection.
15217        let err = contrato_subject_err("foo.>.bar");
15218        assert!(
15219            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15220                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
15221            "got {err:?}"
15222        );
15223    }
15224
15225    #[test]
15226    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
15227        // `foo*.bar` — NATS wildcards are standalone tokens. The
15228        // remediation is in the reason string.
15229        let err = contrato_subject_err("foo*.bar");
15230        assert!(
15231            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15232                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
15233            "got {err:?}"
15234        );
15235    }
15236
15237    #[test]
15238    fn rejects_pubsub_contrato_subject_with_invalid_char() {
15239        // `foo,bar` — comma is not a valid NATS subject character.
15240        // Pinned separately from the wildcard arms so the invalid-
15241        // character diagnostic is in force.
15242        let err = contrato_subject_err("foo,bar");
15243        assert!(
15244            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15245                if subject == "foo,bar" && reason.contains("invalid character")),
15246            "got {err:?}"
15247        );
15248    }
15249
15250    #[test]
15251    fn rejects_pubsub_contrato_subject_too_long() {
15252        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
15253        // The legitimate-shape arms all pass (one all-`a` token, no
15254        // `.`, no wildcards); only the cap arm fires. Surfaces the
15255        // paste-from-binary / accidental-multi-line-blob landing
15256        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
15257        // on the peer axis.
15258        let big = "a".repeat(257);
15259        assert_eq!(big.len(), 257);
15260        let err = contrato_subject_err(&big);
15261        assert!(
15262            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
15263                if subject == &big && reason.contains("max length of 256")),
15264            "got {err:?}"
15265        );
15266    }
15267
15268    #[test]
15269    fn pubsub_contrato_subject_max_length_validates() {
15270        // 256-byte subject — exactly the cap. Boundary pin: drift in
15271        // the cap surfaces here and at
15272        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
15273        // mirroring `http_contrato_endpoint_max_length_validates` and
15274        // `wit_max_length_validates` on the peer axes.
15275        let big = "a".repeat(256);
15276        assert_eq!(big.len(), 256);
15277        let mut s = three_member_spec();
15278        s.contratos.push(WitContract {
15279            de: "payment".into(),
15280            para: "catalog".into(),
15281            wit: "nats:pub-sub".into(),
15282            endpoint: None,
15283            subject: Some(big),
15284            slot: None,
15285        });
15286        s.validate().unwrap();
15287    }
15288
15289    #[test]
15290    fn pubsub_contrato_subject_accepts_canonical_forms() {
15291        // Positive-set sweep: every canonical NATS subject shape the
15292        // substrate-side `is_nats_subject` predicate accepts (the
15293        // multi-dot `events.order.charged`, the snake_case / kebab-
15294        // case / mixed-case tokens, the digit-bearing tokens, the
15295        // single-token wildcard `*` at every segment position, and
15296        // the trailing `>` multi-token wildcard) must remain a valid
15297        // contrato subject too. Drift between this list and the
15298        // substrate-side `nats_subject_accepts_canonical_forms` sweep
15299        // surfaces at the shared predicate — one source of truth.
15300        // Uses a fresh `(payment, catalog)` edge so none of the swept
15301        // subjects collide with the pre-existing entries in
15302        // `three_member_spec`.
15303        for subject in [
15304            "checkout.events.charge.failed",
15305            "rio.events.order.charged",
15306            "orders",
15307            "orders.123",
15308            "snake_case.token",
15309            "kebab-case.token",
15310            "MixedCase.Token",
15311            "orders.*.charged",
15312            "*.events.*",
15313            "orders.>",
15314        ] {
15315            let mut s = three_member_spec();
15316            s.contratos.push(WitContract {
15317                de: "payment".into(),
15318                para: "catalog".into(),
15319                wit: "nats:pub-sub".into(),
15320                endpoint: None,
15321                subject: Some(subject.into()),
15322                slot: None,
15323            });
15324            s.validate()
15325                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
15326        }
15327    }
15328
15329    #[test]
15330    fn contrato_subject_empty_takes_precedence_over_invalid() {
15331        // Ordering pin: `ContratoSubjectEmpty` is the more self-
15332        // locating diagnostic on `""` and must lead — the value-shape
15333        // gate is only reached after the empty-check fires. Mirrors
15334        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
15335        // the peer payload axis.
15336        let mut s = three_member_spec();
15337        s.contratos.push(WitContract {
15338            de: "payment".into(),
15339            para: "catalog".into(),
15340            wit: "nats:pub-sub".into(),
15341            endpoint: None,
15342            subject: Some(String::new()),
15343            slot: None,
15344        });
15345        let err = s.validate().unwrap_err();
15346        assert!(
15347            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
15348            "got {err:?}"
15349        );
15350    }
15351
15352    #[test]
15353    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
15354        // Diagnostic-shape pin — the offending `:subject` + `:de` +
15355        // `:para` + a non-empty reason flow through verbatim so the
15356        // author can grep their caixa.lisp for the offending contrato
15357        // block and fix it in one edit. Same shape as
15358        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
15359        // and `wit_invalid_diagnostic_carries_offending_wit`.
15360        let err = contrato_subject_err("foo..bar");
15361        match err {
15362            AplicacaoError::ContratoSubjectInvalid {
15363                de,
15364                para,
15365                subject,
15366                reason,
15367            } => {
15368                assert_eq!(de, "payment");
15369                assert_eq!(para, "catalog");
15370                assert_eq!(subject, "foo..bar");
15371                assert!(!reason.is_empty(), "reason field must be non-empty");
15372            }
15373            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
15374        }
15375    }
15376
15377    #[test]
15378    fn target_view_pubsub_subject_passes_through_to_typed_view() {
15379        // The compounding theorem on the pub-sub axis: every
15380        // `WitTarget::PubSub { subject }` returned by `target()` carries
15381        // a NATS-server-accepted subject. Renderers downstream of
15382        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
15383        // NATS Stream/Consumer CR emitter, the future `feira app graph`
15384        // view's subject labeller) can rely on this without re-checking
15385        // — the type system carries the proof. Mirrors
15386        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
15387        // on the peer axes.
15388        let nats = WitContract {
15389            de: "a".into(),
15390            para: "b".into(),
15391            wit: "nats:pub-sub".into(),
15392            endpoint: None,
15393            subject: Some("orders.events.*.charged".into()),
15394            slot: None,
15395        };
15396        match nats.target().unwrap() {
15397            WitTarget::PubSub { subject } => {
15398                assert_eq!(subject, "orders.events.*.charged");
15399            }
15400            other => panic!("expected PubSub, got {other:?}"),
15401        }
15402    }
15403
15404    // ── :contratos :slot value-shape gate ────────────────────────────────
15405    //
15406    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
15407    // (63e18a0) value-shape suites on the peer payload axes. Until this
15408    // gate landed `WitContract::target()` only refused the empty string
15409    // for the Store arm; a structurally invalid slot (raw whitespace,
15410    // control character, non-ASCII byte, paste-from-binary multi-line
15411    // blob) silently passed validate and surfaced at runtime as a
15412    // per-backend kv write rejection or a silent next-read corruption,
15413    // far from the source caixa.lisp with no field naming which
15414    // `:contratos` edge carried the typo. Every authoring footgun the
15415    // kv backend intersection-floor would catch on write now becomes a
15416    // caixa-build-time `ContratoSlotInvalid` with the offending
15417    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
15418    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
15419    // peer payload axes; same shared predicate
15420    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
15421    // any two axes' rule enforcement is a build error at the
15422    // predicate, not piecemeal across renderers. Closes the typed
15423    // payload-axis value-shape trajectory across all three legs of the
15424    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
15425
15426    fn contrato_slot_err(slot: &str) -> AplicacaoError {
15427        // Fresh spec per call so the new contract doesn't collide on
15428        // identity with `three_member_spec`'s pre-existing entries
15429        // and doesn't close a synchronous cycle the cycle detector
15430        // would reject before the slot-shape gate fires. The new edge
15431        // uses `(payment, catalog)` — a pair the fixture doesn't
15432        // already declare in either direction (the fixture carries
15433        // `cart -> catalog` and `cart -> payment`, so `payment ->
15434        // catalog` doesn't form a cycle on the sync subgraph) — with
15435        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
15436        // slot-shape gate fires cleanly after the wit-shape gate
15437        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
15438        // peer `contrato_subject_err` helper uses (63e18a0).
15439        let mut s = three_member_spec();
15440        s.contratos.push(WitContract {
15441            de: "payment".into(),
15442            para: "catalog".into(),
15443            wit: "wasi:keyvalue/store".into(),
15444            endpoint: None,
15445            subject: None,
15446            slot: Some(slot.into()),
15447        });
15448        s.validate().unwrap_err()
15449    }
15450
15451    #[test]
15452    fn rejects_store_contrato_slot_with_whitespace() {
15453        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
15454        // silently landed at the kv backend with whitespace whose
15455        // runtime behavior varies unpredictably across backends (etcd
15456        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
15457        // rejects on write). Now caught at the source caixa.lisp.
15458        let err = contrato_slot_err("check out/$order");
15459        assert!(
15460            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15461                if slot == "check out/$order" && reason.contains("whitespace")),
15462            "got {err:?}"
15463        );
15464    }
15465
15466    #[test]
15467    fn rejects_store_contrato_slot_with_tab() {
15468        // Tab byte arm-pinned separately from the space arm so a
15469        // future relaxation that admits one but not the other surfaces
15470        // here.
15471        let err = contrato_slot_err("check\tout");
15472        assert!(
15473            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15474                if slot == "check\tout" && reason.contains("whitespace")),
15475            "got {err:?}"
15476        );
15477    }
15478
15479    #[test]
15480    fn rejects_store_contrato_slot_with_control_char() {
15481        // SOH (0x01) — distinct from the whitespace arm. Redis admits
15482        // and corrupts on RESP protocol framing; DynamoDB rejects on
15483        // write.
15484        let err = contrato_slot_err("checkout/\x01order");
15485        assert!(
15486            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15487                if slot == "checkout/\x01order" && reason.contains("control character")),
15488            "got {err:?}"
15489        );
15490    }
15491
15492    #[test]
15493    fn rejects_store_contrato_slot_with_newline() {
15494        // Embedded newline — the canonical "the paste-from-binary slug
15495        // spans multiple lines" footgun. Distinct from the whitespace
15496        // arm because `\n` is a control character (0x0A).
15497        let err = contrato_slot_err("checkout\norder");
15498        assert!(
15499            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15500                if slot == "checkout\norder" && reason.contains("control character")),
15501            "got {err:?}"
15502        );
15503    }
15504
15505    #[test]
15506    fn rejects_store_contrato_slot_with_non_ascii() {
15507        // Un-percent-encoded non-ASCII byte — the canonical "I copied
15508        // the slot from a doc with accented characters" footgun. Each
15509        // kv backend re-encodes non-ASCII differently (etcd preserves
15510        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
15511        // rejects), so the typed slot's value set is the intersection-
15512        // floor every backend admits identically (printable ASCII).
15513        let err = contrato_slot_err("ch\u{e9}ckout/$order");
15514        assert!(
15515            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15516                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
15517            "got {err:?}"
15518        );
15519    }
15520
15521    #[test]
15522    fn rejects_store_contrato_slot_too_long() {
15523        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
15524        // legitimate-shape arms all pass (a single all-`a` token, no
15525        // separators); only the cap arm fires. Surfaces the paste-
15526        // from-binary / accidental-multi-line-blob landing footgun.
15527        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
15528        // `rejects_http_contrato_endpoint_too_long` on the peer
15529        // payload axes.
15530        let big = "a".repeat(513);
15531        assert_eq!(big.len(), 513);
15532        let err = contrato_slot_err(&big);
15533        assert!(
15534            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
15535                if slot == &big && reason.contains("max length of 512")),
15536            "got {err:?}"
15537        );
15538    }
15539
15540    #[test]
15541    fn store_contrato_slot_max_length_validates() {
15542        // 512-byte slot — exactly the cap. Boundary pin: drift in the
15543        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
15544        // simultaneously, mirroring
15545        // `pubsub_contrato_subject_max_length_validates` and
15546        // `http_contrato_endpoint_max_length_validates` on the peer
15547        // payload axes.
15548        let big = "a".repeat(512);
15549        assert_eq!(big.len(), 512);
15550        let mut s = three_member_spec();
15551        s.contratos.push(WitContract {
15552            de: "payment".into(),
15553            para: "catalog".into(),
15554            wit: "wasi:keyvalue/store".into(),
15555            endpoint: None,
15556            subject: None,
15557            slot: Some(big),
15558        });
15559        s.validate().unwrap();
15560    }
15561
15562    #[test]
15563    fn store_contrato_slot_accepts_canonical_forms() {
15564        // Positive-set sweep: every canonical kv slot template the
15565        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
15566        // (single-token identifiers, path-namespaced `$`-templates,
15567        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
15568        // snake_case / kebab-case / MixedCase tokens, digit-bearing
15569        // tokens, percent-encoded fragments) must remain valid
15570        // contrato slots too. Drift between this list and the
15571        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
15572        // surfaces at the shared predicate — one source of truth.
15573        // Uses a fresh `(payment, catalog)` edge so none of the swept
15574        // slots collide with the pre-existing entries in
15575        // `three_member_spec`.
15576        for slot in [
15577            "checkout",
15578            "checkout/$orderId",
15579            "users:{tenant}/{id}",
15580            "session.<sid>",
15581            "session.tokens.<sid>",
15582            "snake_case_key",
15583            "kebab-case-key",
15584            "MixedCase",
15585            "shard0",
15586            "v2/key",
15587            "users/caf%C3%A9",
15588        ] {
15589            let mut s = three_member_spec();
15590            s.contratos.push(WitContract {
15591                de: "payment".into(),
15592                para: "catalog".into(),
15593                wit: "wasi:keyvalue/store".into(),
15594                endpoint: None,
15595                subject: None,
15596                slot: Some(slot.into()),
15597            });
15598            s.validate()
15599                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
15600        }
15601    }
15602
15603    #[test]
15604    fn contrato_slot_empty_takes_precedence_over_invalid() {
15605        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
15606        // diagnostic on `""` and must lead — the value-shape gate is
15607        // only reached after the empty-check fires. Mirrors
15608        // `contrato_subject_empty_takes_precedence_over_invalid` and
15609        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
15610        // the peer payload axes.
15611        let mut s = three_member_spec();
15612        s.contratos.push(WitContract {
15613            de: "payment".into(),
15614            para: "catalog".into(),
15615            wit: "wasi:keyvalue/store".into(),
15616            endpoint: None,
15617            subject: None,
15618            slot: Some(String::new()),
15619        });
15620        let err = s.validate().unwrap_err();
15621        assert!(
15622            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
15623            "got {err:?}"
15624        );
15625    }
15626
15627    #[test]
15628    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
15629        // Diagnostic-shape pin — the offending `:slot` + `:de` +
15630        // `:para` + a non-empty reason flow through verbatim so the
15631        // author can grep their caixa.lisp for the offending contrato
15632        // block and fix it in one edit. Same shape as
15633        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
15634        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
15635        // on the peer payload axes.
15636        let err = contrato_slot_err("check out/$order");
15637        match err {
15638            AplicacaoError::ContratoSlotInvalid {
15639                de,
15640                para,
15641                slot,
15642                reason,
15643            } => {
15644                assert_eq!(de, "payment");
15645                assert_eq!(para, "catalog");
15646                assert_eq!(slot, "check out/$order");
15647                assert!(!reason.is_empty(), "reason field must be non-empty");
15648            }
15649            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
15650        }
15651    }
15652
15653    #[test]
15654    fn target_view_store_slot_passes_through_to_typed_view() {
15655        // The compounding theorem on the store axis: every
15656        // `WitTarget::Store { slot }` returned by `target()` carries a
15657        // kv-backend-accepted slot template. Renderers downstream of
15658        // `typed_view()` (the future per-Servico `:capabilities
15659        // wasi:keyvalue/store` axis emitter, the future `feira app
15660        // graph` view's slot labeller, the future kv-provider CR
15661        // materializer) can rely on this without re-checking — the
15662        // type system carries the proof. Mirrors
15663        // `target_view_pubsub_subject_passes_through_to_typed_view` on
15664        // the peer payload axis.
15665        let store = WitContract {
15666            de: "a".into(),
15667            para: "b".into(),
15668            wit: "wasi:keyvalue/store".into(),
15669            endpoint: None,
15670            subject: None,
15671            slot: Some("checkout/$orderId".into()),
15672        };
15673        match store.target().unwrap() {
15674            WitTarget::Store { slot } => {
15675                assert_eq!(slot, "checkout/$orderId");
15676            }
15677            other => panic!("expected Store, got {other:?}"),
15678        }
15679    }
15680
15681    #[test]
15682    fn rejects_self_loop_in_synchronous_contratos() {
15683        // A synchronous self-edge (`cart → cart` over HTTP) is now
15684        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
15685        // "this edge is degenerate" diagnostic — rather than incidentally
15686        // by the cycle detector framing it as a `["cart", "cart"]`
15687        // multi-node deadlock.
15688        let mut s = three_member_spec();
15689        s.contratos.push(contract_http("cart", "cart", "/loop"));
15690        let err = s.validate().unwrap_err();
15691        match err {
15692            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
15693                assert_eq!(caixa, "cart");
15694                assert_eq!(wit, "wasi:http/proxy");
15695            }
15696            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15697        }
15698    }
15699
15700    #[test]
15701    fn rejects_self_loop_in_pubsub_contratos() {
15702        // The cycle detector excludes pub-sub edges (acyclic by
15703        // construction), so before the explicit gate a `nats:pub-sub`
15704        // self-edge silently validated and rendered a self-allow CNP.
15705        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
15706        let mut s = three_member_spec();
15707        s.contratos.push(WitContract {
15708            de: "payment".into(),
15709            para: "payment".into(),
15710            wit: "nats:pub-sub".into(),
15711            endpoint: None,
15712            subject: Some("rio.events.payment".into()),
15713            slot: None,
15714        });
15715        let err = s.validate().unwrap_err();
15716        match err {
15717            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
15718                assert_eq!(caixa, "payment");
15719                assert_eq!(wit, "nats:pub-sub");
15720            }
15721            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15722        }
15723    }
15724
15725    #[test]
15726    fn self_loop_fires_before_payload_shape_check() {
15727        // The structural "this edge can't exist" error precedes the
15728        // narrower payload-shape diagnostics: a self-edge carrying an
15729        // otherwise-malformed endpoint still reports ContratoSelfLoop,
15730        // not ContratoEndpointInvalid.
15731        let mut s = three_member_spec();
15732        s.contratos.push(WitContract {
15733            de: "cart".into(),
15734            para: "cart".into(),
15735            wit: "wasi:http/proxy".into(),
15736            endpoint: Some("not-absolute".into()),
15737            subject: None,
15738            slot: None,
15739        });
15740        match s.validate().unwrap_err() {
15741            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
15742            other => panic!("expected ContratoSelfLoop, got {other:?}"),
15743        }
15744    }
15745
15746    #[test]
15747    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
15748        // A self-edge naming a non-member reports the more fundamental
15749        // ContratoMemberMissing first (the member doesn't exist), so the
15750        // self-loop gate is reached only once both endpoints resolve.
15751        let mut s = three_member_spec();
15752        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
15753        match s.validate().unwrap_err() {
15754            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
15755            other => panic!("expected ContratoMemberMissing, got {other:?}"),
15756        }
15757    }
15758
15759    #[test]
15760    fn rejects_two_node_synchronous_cycle() {
15761        let mut s = three_member_spec();
15762        // existing edges: cart → catalog, cart → payment
15763        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
15764        s.contratos
15765            .push(contract_http("catalog", "cart", "/refresh"));
15766        let err = s.validate().unwrap_err();
15767        match err {
15768            AplicacaoError::ContratoCycle { cycle } => {
15769                // Cycle traversal should mention both endpoints, with
15770                // the back-edge target appearing as both first and last
15771                // element to close the loop.
15772                assert!(cycle.len() >= 3);
15773                assert_eq!(cycle.first(), cycle.last());
15774                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
15775                assert!(body.contains("cart"));
15776                assert!(body.contains("catalog"));
15777            }
15778            other => panic!("expected ContratoCycle, got {other:?}"),
15779        }
15780    }
15781
15782    #[test]
15783    fn rejects_three_node_synchronous_cycle() {
15784        let mut s = three_member_spec();
15785        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
15786        s.contratos = vec![
15787            contract_http("catalog", "cart", "/x"),
15788            contract_http("cart", "payment", "/y"),
15789            contract_http("payment", "catalog", "/z"),
15790        ];
15791        let err = s.validate().unwrap_err();
15792        match err {
15793            AplicacaoError::ContratoCycle { cycle } => {
15794                assert_eq!(cycle.first(), cycle.last());
15795                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
15796                assert_eq!(body.len(), 3);
15797                assert!(body.contains("cart"));
15798                assert!(body.contains("catalog"));
15799                assert!(body.contains("payment"));
15800            }
15801            other => panic!("expected ContratoCycle, got {other:?}"),
15802        }
15803    }
15804
15805    #[test]
15806    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
15807        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
15808        // "acyclic by construction" — so a cycle whose closing edge
15809        // is pub-sub should NOT raise ContratoCycle.
15810        let mut s = three_member_spec();
15811        s.contratos = vec![
15812            contract_http("catalog", "cart", "/x"),
15813            contract_http("cart", "payment", "/y"),
15814            // Closing edge is pub-sub — async; not a sync deadlock.
15815            WitContract {
15816                de: "payment".into(),
15817                para: "catalog".into(),
15818                wit: "nats:pub-sub".into(),
15819                endpoint: None,
15820                subject: Some("checkout.events.charge.completed".into()),
15821                slot: None,
15822            },
15823        ];
15824        s.validate().expect("pub-sub edge breaks the sync cycle");
15825    }
15826
15827    #[test]
15828    fn store_edge_counts_as_synchronous_for_cycle_detection() {
15829        // wasi:keyvalue/store is request/response; a cycle through one
15830        // *is* a sync deadlock, just like HTTP.
15831        let mut s = three_member_spec();
15832        s.contratos = vec![
15833            contract_http("catalog", "cart", "/x"),
15834            WitContract {
15835                de: "cart".into(),
15836                para: "catalog".into(),
15837                wit: "wasi:keyvalue/store".into(),
15838                endpoint: None,
15839                subject: None,
15840                slot: Some("session/$id".into()),
15841            },
15842        ];
15843        let err = s.validate().unwrap_err();
15844        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
15845    }
15846
15847    #[test]
15848    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
15849        // Capability-only edges (unknown WIT shape, no payload) default
15850        // to synchronous — safer; authors with truly async capability
15851        // semantics can model them as pub-sub explicitly.
15852        let mut s = three_member_spec();
15853        s.contratos = vec![
15854            contract_http("catalog", "cart", "/x"),
15855            WitContract {
15856                de: "cart".into(),
15857                para: "catalog".into(),
15858                wit: "custom:exchange".into(),
15859                endpoint: None,
15860                subject: None,
15861                slot: None,
15862            },
15863        ];
15864        let err = s.validate().unwrap_err();
15865        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
15866    }
15867
15868    #[test]
15869    fn long_acyclic_chain_validates() {
15870        // A long sync chain (no back-edges) must validate even when
15871        // every node is reachable from the first.
15872        let mut s = three_member_spec();
15873        s.membros = vec![
15874            membro("a", "^0.1"),
15875            membro("b", "^0.1"),
15876            membro("c", "^0.1"),
15877            membro("d", "^0.1"),
15878            membro("e", "^0.1"),
15879        ];
15880        s.contratos = vec![
15881            contract_http("a", "b", "/1"),
15882            contract_http("b", "c", "/2"),
15883            contract_http("c", "d", "/3"),
15884            contract_http("d", "e", "/4"),
15885        ];
15886        s.entrada.as_mut().unwrap().para = "a".into();
15887        s.validate().unwrap();
15888    }
15889
15890    #[test]
15891    fn diamond_acyclic_validates() {
15892        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
15893        let mut s = three_member_spec();
15894        s.membros = vec![
15895            membro("a", "^0.1"),
15896            membro("b", "^0.1"),
15897            membro("c", "^0.1"),
15898            membro("d", "^0.1"),
15899        ];
15900        s.contratos = vec![
15901            contract_http("a", "b", "/1"),
15902            contract_http("a", "c", "/2"),
15903            contract_http("b", "d", "/3"),
15904            contract_http("c", "d", "/4"),
15905        ];
15906        s.entrada.as_mut().unwrap().para = "a".into();
15907        s.validate().unwrap();
15908    }
15909
15910    // ── duplicate-`:contratos` build-error gate ──────────────────────────
15911
15912    #[test]
15913    fn rejects_duplicate_http_contrato() {
15914        // Fail-before-pass-after pin: the fixture's `cart → catalog`
15915        // HTTP edge appears once. Push an identical entry — same
15916        // (de, para, wit, endpoint) — and validate() must reject it.
15917        // Until this gate landed the typed surface accepted the
15918        // duplicate silently and caixa-mesh's `cilium_network_policies`
15919        // emitted two ``CiliumNetworkPolicy`` objects with identical
15920        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
15921        // admission rejects on `kubectl apply` far from the source.
15922        let mut s = three_member_spec();
15923        s.contratos
15924            .push(contract_http("cart", "catalog", "/products/:id"));
15925        let err = s.validate().unwrap_err();
15926        assert!(
15927            matches!(
15928                err,
15929                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15930                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
15931            ),
15932            "got {err:?}"
15933        );
15934    }
15935
15936    #[test]
15937    fn rejects_duplicate_pubsub_contrato() {
15938        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
15939        // edges with identical (de, para, subject) are degenerate;
15940        // pin that the typed surface refuses both at validate time.
15941        let mut s = three_member_spec();
15942        let pubsub = WitContract {
15943            de: "payment".into(),
15944            para: "cart".into(),
15945            wit: "nats:pub-sub".into(),
15946            endpoint: None,
15947            subject: Some("checkout.events.charge.failed".into()),
15948            slot: None,
15949        };
15950        s.contratos.push(pubsub.clone());
15951        s.contratos.push(pubsub);
15952        let err = s.validate().unwrap_err();
15953        assert!(
15954            matches!(
15955                err,
15956                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15957                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
15958            ),
15959            "got {err:?}"
15960        );
15961    }
15962
15963    #[test]
15964    fn rejects_duplicate_store_contrato() {
15965        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
15966        // edges with identical (de, para, slot) collapse to one mesh-
15967        // policy edge; pin the build error.
15968        let mut s = three_member_spec();
15969        let store = WitContract {
15970            de: "cart".into(),
15971            para: "payment".into(),
15972            wit: "wasi:keyvalue/store".into(),
15973            endpoint: None,
15974            subject: None,
15975            slot: Some("checkout/$orderId".into()),
15976        };
15977        // Drop the conflicting HTTP `cart → payment` edge from the
15978        // fixture so the duplicate-store pair is the only one
15979        // distinguishable on this pair.
15980        s.contratos
15981            .retain(|c| !(c.de == "cart" && c.para == "payment"));
15982        s.contratos.push(store.clone());
15983        s.contratos.push(store);
15984        let err = s.validate().unwrap_err();
15985        assert!(
15986            matches!(
15987                err,
15988                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
15989                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
15990            ),
15991            "got {err:?}"
15992        );
15993    }
15994
15995    #[test]
15996    fn rejects_duplicate_capability_contrato() {
15997        // Same gate on the pure-capability axis (no payload selector).
15998        // Two contracts with identical (de, para, wit) and no
15999        // endpoint/subject/slot are duplicate edges; pin so a future
16000        // `target_label` change can't accidentally collapse the
16001        // capability arm into a None-shaped key that compares equal
16002        // to a populated one.
16003        let mut s = three_member_spec();
16004        let capability = WitContract {
16005            de: "cart".into(),
16006            para: "catalog".into(),
16007            wit: "pleme:cap/audit".into(),
16008            endpoint: None,
16009            subject: None,
16010            slot: None,
16011        };
16012        s.contratos.push(capability.clone());
16013        s.contratos.push(capability);
16014        let err = s.validate().unwrap_err();
16015        match err {
16016            AplicacaoError::ContratoDuplicate {
16017                de,
16018                para,
16019                wit,
16020                target,
16021            } => {
16022                assert_eq!(de, "cart");
16023                assert_eq!(para, "catalog");
16024                assert_eq!(wit, "pleme:cap/audit");
16025                assert!(
16026                    target.contains("capability"),
16027                    "capability-edge duplicate diagnostic must surface the \
16028                     no-payload shape (got target = {target:?})"
16029                );
16030            }
16031            other => panic!("expected ContratoDuplicate, got {other:?}"),
16032        }
16033    }
16034
16035    #[test]
16036    fn accepts_distinct_http_paths_between_same_pair() {
16037        // Negative pin: two HTTP contracts cart → catalog at distinct
16038        // endpoints (`/products/:id` and `/search`) are *not*
16039        // duplicates — they're distinct typed edges differing on the
16040        // payload axis. The duplicate-gate must not over-match here,
16041        // since the cart-calls-catalog-on-multiple-paths shape is the
16042        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
16043        // example: cart calls catalog at /products/:id, payment at
16044        // /charge — same shape extends to two paths on one para).
16045        let mut s = three_member_spec();
16046        s.contratos
16047            .push(contract_http("cart", "catalog", "/search"));
16048        s.validate()
16049            .expect("distinct endpoints between same (de, para) must validate");
16050    }
16051
16052    #[test]
16053    fn accepts_same_endpoint_on_different_pairs() {
16054        // Negative pin: the same `/charge` endpoint reused on two
16055        // different (de, para) pairs is two distinct edges, not a
16056        // duplicate. Pinning this shape so the gate's identity key
16057        // includes both `de` and `para` (not just `(wit, endpoint)`).
16058        let mut s = three_member_spec();
16059        s.contratos
16060            .push(contract_http("payment", "catalog", "/charge"));
16061        s.validate()
16062            .expect("same endpoint reused on distinct (de, para) must validate");
16063    }
16064
16065    #[test]
16066    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
16067        // Pin the diagnostic shape: the duplicate-edge error names
16068        // *which* target field carried the conflict, so the author
16069        // doesn't have to re-grep the source caixa.lisp to find it.
16070        // Same self-locating diagnostic discipline as
16071        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
16072        let mut s = three_member_spec();
16073        s.contratos
16074            .push(contract_http("cart", "catalog", "/products/:id"));
16075        let err = s.validate().unwrap_err();
16076        let msg = format!("{err}");
16077        assert!(
16078            msg.contains("\"/products/:id\""),
16079            "duplicate-contrato diagnostic must name the offending \
16080             :endpoint payload (got: {msg:?})"
16081        );
16082        assert!(
16083            msg.contains("cart") && msg.contains("catalog"),
16084            "diagnostic must name both endpoints of the duplicate edge \
16085             (got: {msg:?})"
16086        );
16087    }
16088
16089    #[test]
16090    fn duplicate_contrato_gate_runs_after_membership_check() {
16091        // Order pin: a duplicate contract whose `:de` is *also* not in
16092        // `:membros` surfaces the membership error first — the
16093        // missing-member diagnostic is more locating than the
16094        // duplicate-edge one (the author has to fix the membership
16095        // before the duplicate is meaningful). Same ordering
16096        // discipline as `membros_validation_runs_before_contratos_membership_check`.
16097        let mut s = three_member_spec();
16098        s.contratos.push(contract_http("phantom", "catalog", "/x"));
16099        s.contratos.push(contract_http("phantom", "catalog", "/x"));
16100        let err = s.validate().unwrap_err();
16101        assert!(
16102            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
16103            "membership-missing must fire before duplicate-edge (got {err:?})"
16104        );
16105    }
16106
16107    #[test]
16108    fn duplicate_contrato_gate_runs_after_target_shape_check() {
16109        // Order pin: a contract with a malformed target (e.g. an HTTP
16110        // wit world with an empty :endpoint) surfaces the target-shape
16111        // error first, not the duplicate one. Even when two such
16112        // malformed entries are identical, the per-contract `target()`
16113        // check fires inside the loop *before* the duplicate-key
16114        // insert, so the diagnostic remains the most-locating one.
16115        let mut s = three_member_spec();
16116        let malformed = WitContract {
16117            de: "cart".into(),
16118            para: "catalog".into(),
16119            wit: "wasi:http/proxy".into(),
16120            endpoint: Some(String::new()),
16121            subject: None,
16122            slot: None,
16123        };
16124        s.contratos.push(malformed.clone());
16125        s.contratos.push(malformed);
16126        let err = s.validate().unwrap_err();
16127        assert!(
16128            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
16129            "endpoint-empty must fire before duplicate-edge (got {err:?})"
16130        );
16131    }
16132
16133    #[test]
16134    fn wit_target_label_pins_per_variant_format() {
16135        // Label format is the single source of truth every duplicate-
16136        // `:contratos` diagnostic + every future `feira app graph`
16137        // consumer routes through. Pin the shape per variant so a
16138        // future edit to `WitTarget::label` (e.g. a JSON emitter that
16139        // strips the leading `:`, or a rename from `endpoint` →
16140        // `path`) surfaces as a red-red test rather than as a silent
16141        // downstream diagnostic drift. Together with the exhaustive
16142        // `match` on `WitTarget` inside `label()`, adding a future
16143        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
16144        // peer, per-edge WIT registry variants) is a compile error at
16145        // the label site — not a fall-through into the `Capability`
16146        // "no payload" default the prior raw-field-probe helper
16147        // silently landed on.
16148        assert_eq!(
16149            WitTarget::Http {
16150                endpoint: "/charge",
16151            }
16152            .label(),
16153            "\
16154:endpoint \"/charge\""
16155        );
16156        assert_eq!(
16157            WitTarget::PubSub {
16158                subject: "events.checkout.paid",
16159            }
16160            .label(),
16161            "\
16162:subject \"events.checkout.paid\""
16163        );
16164        assert_eq!(
16165            WitTarget::Store {
16166                slot: "checkout/$order",
16167            }
16168            .label(),
16169            "\
16170:slot \"checkout/$order\""
16171        );
16172        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
16173        // Capability-arm label routes through the lifted
16174        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
16175        // declaration per arm, next to the variant" discipline the
16176        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
16177        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16178        // consts already carry extends to the payload-less arm; the
16179        // byte-string equality pin below plus this label-routes-
16180        // through-the-const pin make a future rebrand on either the
16181        // const declaration or the `label()` template a build error
16182        // here rather than a downstream consumer surprise.
16183        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
16184        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
16185    }
16186
16187    #[test]
16188    fn wit_target_display_routes_through_label_helper() {
16189        // Fail-before-pass-after pin on the fourth (and only remaining)
16190        // typed-shape-discriminator axis to converge onto the
16191        // three-path-convergence discipline the sibling M3
16192        // [`PlacementStrategy`] (0a2f653) and M2
16193        // [`crate::supervisor::RestartStrategy`] /
16194        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
16195        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
16196        // through [`WitTarget::label`], so every consumer reaching for
16197        // `format!("{v}")` on a typed payload target lands on the same
16198        // stable author-facing byte-string [`WitTarget::label`] returns
16199        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
16200        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
16201        // `:contratos` gate seeds via [`WitTarget::label`] at
16202        // aplicacao.rs:5491 already threads through.
16203        //
16204        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
16205        // through to the `Debug` derive's structural output
16206        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
16207        // rather than the [`WitTarget::label`] helper's stable byte-
16208        // string (`:endpoint "/charge"` — the author-facing `:contratos`
16209        // keyword form). Every future consumer that reaches for
16210        // `format!("{target}")` — the canonical shape every user-facing
16211        // pretty-print site on the sibling typed-enum axes
16212        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
16213        // [`crate::supervisor::RestartPolicy`]) already uses — would
16214        // silently land under a different byte-string than the
16215        // [`WitTarget::label`] callers that the duplicate-`:contratos`
16216        // diagnostic already threads through, with the mismatch
16217        // surfacing as a downstream diagnostic / graph / audit line
16218        // reading one spelling while the substrate's own gate emitted
16219        // another.
16220        //
16221        // Pin the routing here so a future
16222        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
16223        // that hand-rolls the per-arm formatting instead of delegating
16224        // to [`WitTarget::label`] fails at caixa-core build time.
16225        for variant in [
16226            WitTarget::Http {
16227                endpoint: "/charge",
16228            },
16229            WitTarget::PubSub {
16230                subject: "events.checkout.paid",
16231            },
16232            WitTarget::Store {
16233                slot: "checkout/$order",
16234            },
16235            WitTarget::Capability,
16236        ] {
16237            assert_eq!(
16238                variant.to_string(),
16239                variant.label(),
16240                "WitTarget::{variant:?} Display must route through \
16241                 WitTarget::label (single source of truth: the lifted \
16242                 payload_pair 4-arm dispatch the label helper already \
16243                 threads through)"
16244            );
16245        }
16246    }
16247
16248    #[test]
16249    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
16250        // Consumer-side pin on the three-path convergence:
16251        // [`std::fmt::Display`] agrees byte-for-byte with the
16252        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
16253        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
16254        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
16255        // Pre-lift the two paths were structurally independent — the
16256        // substrate-side gate reached for `target_view.label()` while a
16257        // future downstream diagnostic / graph / audit line reaching
16258        // for `format!("{target}")` would silently land on the `Debug`
16259        // derive's structural output. Pin the two paths byte-for-byte
16260        // here so any future variant addition (M4 `Rest`/`Grpc` split
16261        // of [`WitTarget::Http`], `Queue`-shaped peer of
16262        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
16263        // match error at [`WitTarget::payload_pair`] rather than a
16264        // silent per-consumer dispatch miss.
16265        for variant in [
16266            WitTarget::Http {
16267                endpoint: "/charge",
16268            },
16269            WitTarget::PubSub {
16270                subject: "events.checkout.paid",
16271            },
16272            WitTarget::Store {
16273                slot: "checkout/$order",
16274            },
16275            WitTarget::Capability,
16276        ] {
16277            assert_eq!(
16278                format!("{variant}"),
16279                variant.label(),
16280                "WitTarget::{variant:?} Display byte-string must match \
16281                 the AplicacaoError::ContratoDuplicate `target:` carrier \
16282                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
16283                 seeds via WitTarget::label — three-path convergence: \
16284                 Display + label + payload_pair all resolve to the same \
16285                 per-arm byte-string"
16286            );
16287        }
16288    }
16289
16290    #[test]
16291    fn wit_target_payload_pair_pins_per_variant() {
16292        // Pin the per-arm `(field-name, payload)` pair single-sourced
16293        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
16294        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
16295        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
16296        // and [`WitTarget::field_name`] (returns the first component)
16297        // route through. Until this lift landed [`WitTarget::label`]
16298        // dispatched on the same three arms with a per-arm
16299        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
16300        // paired [`WitTarget::HTTP_FIELD_NAME`] /
16301        // [`WitTarget::PUBSUB_FIELD_NAME`] /
16302        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
16303        // canonical "same shape, written N times" duplication
16304        // THEORY.md §I.3.5 promotes to a build-time concern. A future
16305        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
16306        // [`WitTarget::Http`], `Queue`-shaped peer of
16307        // [`WitTarget::Store`]) is one match-arm edit at
16308        // [`WitTarget::payload_pair`], visible here as a compile-time
16309        // exhaustiveness error on both this pin and the label-format
16310        // pin above.
16311        assert_eq!(
16312            WitTarget::Http {
16313                endpoint: "/charge"
16314            }
16315            .payload_pair(),
16316            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
16317        );
16318        assert_eq!(
16319            WitTarget::PubSub {
16320                subject: "events.x",
16321            }
16322            .payload_pair(),
16323            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
16324        );
16325        assert_eq!(
16326            WitTarget::Store {
16327                slot: "checkout/$order",
16328            }
16329            .payload_pair(),
16330            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
16331        );
16332        assert_eq!(WitTarget::Capability.payload_pair(), None);
16333    }
16334
16335    #[test]
16336    fn wit_target_field_name_pins_per_variant() {
16337        // Pin the per-arm author-facing `:contratos` payload field
16338        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
16339        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
16340        // + returned by [`WitTarget::field_name`]. Every downstream
16341        // consumer (the [`WitContract::target`] gate's `expected:`
16342        // scalar, the [`WitTarget::label`] template's keyword prefix,
16343        // the `feira app graph` verb's `endpoint=…` prefix) routes
16344        // through the same three peer consts, so a rename on the
16345        // author-surface `(defcaixa … :contratos ((:de … :para …
16346        // :wit … :endpoint …)))` field lands in exactly one place.
16347        assert_eq!(
16348            WitTarget::Http {
16349                endpoint: "/charge"
16350            }
16351            .field_name(),
16352            Some(WitTarget::HTTP_FIELD_NAME),
16353        );
16354        assert_eq!(
16355            WitTarget::PubSub {
16356                subject: "events.x",
16357            }
16358            .field_name(),
16359            Some(WitTarget::PUBSUB_FIELD_NAME),
16360        );
16361        assert_eq!(
16362            WitTarget::Store {
16363                slot: "checkout/$order",
16364            }
16365            .field_name(),
16366            Some(WitTarget::STORE_FIELD_NAME),
16367        );
16368        // Capability arm carries no payload field — the diagnostic
16369        // never reports `expected: "capability"` because the gate's
16370        // Capability arm accepts no payload at all (it fires the
16371        // "expected: none" WrongTarget error instead), so the field-
16372        // name method returns None here rather than a placeholder.
16373        assert_eq!(WitTarget::Capability.field_name(), None);
16374
16375        // Peer const scalar values pinned so a rename on either side
16376        // (author-surface field name in the `(defcaixa …)` DSL, or
16377        // the diagnostic's `expected:` scalar) can't drift without
16378        // failing here first.
16379        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
16380        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
16381        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
16382    }
16383
16384    #[test]
16385    fn wit_target_payload_pins_per_variant() {
16386        // Pin the per-arm payload scalar single-sourced onto the
16387        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
16388        // [`WitTarget::payload`] — the peer per-half projection to
16389        // [`WitTarget::field_name`] on the paired sub-selector axis. The
16390        // three payload-carrying arms round-trip their author-declared
16391        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
16392        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
16393        // the payload-less [`WitTarget::Capability`] arm returns `None`.
16394        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
16395        // (c6ec2af) pin on the Component-0 projection axis, extended
16396        // onto the Component-1 projection axis so both per-half readers
16397        // on the paired dispatch carry their own byte-shape pin.
16398        assert_eq!(
16399            WitTarget::Http {
16400                endpoint: "/charge",
16401            }
16402            .payload(),
16403            Some("/charge"),
16404        );
16405        assert_eq!(
16406            WitTarget::PubSub {
16407                subject: "events.x",
16408            }
16409            .payload(),
16410            Some("events.x"),
16411        );
16412        assert_eq!(
16413            WitTarget::Store {
16414                slot: "checkout/$order",
16415            }
16416            .payload(),
16417            Some("checkout/$order"),
16418        );
16419        assert_eq!(WitTarget::Capability.payload(), None);
16420    }
16421
16422    #[test]
16423    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
16424        // Per-variant equivalence pin: for every arm of [`WitTarget`],
16425        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
16426        // byte-for-byte. Guards the drift surface where a future refactor
16427        // that split one accessor off the shared match onto its own
16428        // dispatch — a well-meaning "inline the pair back into per-half
16429        // fields for one crate-internal caller who only wanted one half"
16430        // or a scratch `impl` shadowing the derived projection — would
16431        // silently desynchronize [`WitTarget::payload`] from the
16432        // authoritative [`WitTarget::payload_pair`] dispatch, and every
16433        // downstream consumer that thinks "the payload half of the pair"
16434        // would drift from the diagnostic / graph consumers reading the
16435        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
16436        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
16437        // per-half projection pin (`gitrefspec_ref_pair_projects_
16438        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
16439        // FluxCD source-controller `spec.ref.<field>` axis — same "one
16440        // paired dispatch, both per-half projections agree byte-for-
16441        // byte" discipline extended onto the M3 `:contratos` payload-
16442        // arm surface.
16443        for variant in [
16444            WitTarget::Http {
16445                endpoint: "/charge",
16446            },
16447            WitTarget::PubSub {
16448                subject: "events.checkout.paid",
16449            },
16450            WitTarget::Store {
16451                slot: "checkout/$order",
16452            },
16453            WitTarget::Capability,
16454        ] {
16455            let via_projection = variant.payload();
16456            let via_pair = variant.payload_pair().map(|(_, p)| p);
16457            assert_eq!(
16458                via_projection, via_pair,
16459                "WitTarget::{variant:?} payload() must equal \
16460                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
16461                 regression that splits the two per-half projections off \
16462                 their shared match would silently desynchronize the \
16463                 payload accessor from the paired dispatch every \
16464                 diagnostic / graph consumer reads through",
16465            );
16466        }
16467    }
16468
16469    #[test]
16470    fn wit_target_http_endpoint_pins_per_variant() {
16471        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
16472        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
16473        // substrate-primitive per-arm post-projection accessor every
16474        // L7-HTTP-facing consumer routes through, sibling to the peer
16475        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
16476        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
16477        // arm round-trips its author-declared endpoint verbatim as
16478        // `Some("/charge")`; the three sibling arms
16479        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
16480        // [`WitTarget::Capability`]) each return `None` because they
16481        // carry no HTTP endpoint by definition. Same fail-before-pass-
16482        // after per-variant discipline as the sibling
16483        // `wit_target_payload_pins_per_variant` (5d6dc92) /
16484        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
16485        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
16486        // the peer pan-arm / per-half projection axes — extended onto
16487        // the per-arm HTTP-shape post-projection axis so a future
16488        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
16489        // [`WitTarget::Http`], a `Queue`-shaped peer of
16490        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
16491        // error on the sibling [`WitTarget::http_endpoint`] match arms
16492        // whose payload the L7-HTTP-shape accept-set is meant to bound.
16493        assert_eq!(
16494            WitTarget::Http {
16495                endpoint: "/charge",
16496            }
16497            .http_endpoint(),
16498            Some("/charge"),
16499        );
16500        assert_eq!(
16501            WitTarget::PubSub {
16502                subject: "events.checkout.paid",
16503            }
16504            .http_endpoint(),
16505            None,
16506        );
16507        assert_eq!(
16508            WitTarget::Store {
16509                slot: "checkout/$order",
16510            }
16511            .http_endpoint(),
16512            None,
16513        );
16514        assert_eq!(WitTarget::Capability.http_endpoint(), None);
16515    }
16516
16517    #[test]
16518    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
16519        // Per-variant coherence pin: for every arm of [`WitTarget`],
16520        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
16521        // arm (both project the same author-declared request-path
16522        // scalar), and returns `None` on every sibling arm regardless of
16523        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
16524        // Store carry their own payload the pan-arm accessor surfaces,
16525        // but that payload is not an HTTP endpoint — the per-arm
16526        // accessor must not leak it through the HTTP-shape channel).
16527        // Guards the drift surface where a future refactor that
16528        // conflated the per-arm HTTP projection with the pan-arm
16529        // [`WitTarget::payload`] projection — a well-meaning "one
16530        // accessor for the L7 branch, one for the graph" collapse that
16531        // routes both through the same 4-arm dispatch — would silently
16532        // widen the L7-HTTP-shape accept-set onto pub-sub / store
16533        // payloads at the caixa-mesh L7 emit branch, admitting a
16534        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
16535        // rule with the operator-side apply-time symptom (Cilium's
16536        // eBPF data-plane rejects every ingress edge whose L7 filter
16537        // doesn't match the wire-format HTTP request line) far from
16538        // the source refactor. Sibling to the peer
16539        // `wit_target_payload_matches_payload_pair_second_component_
16540        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
16541        // extended onto the per-arm HTTP specialization axis so both
16542        // the pan-arm and the per-arm projections carry their own
16543        // byte-shape coherence witness against the substrate's typed
16544        // arm-family accept-set.
16545        for variant in [
16546            WitTarget::Http {
16547                endpoint: "/charge",
16548            },
16549            WitTarget::PubSub {
16550                subject: "events.checkout.paid",
16551            },
16552            WitTarget::Store {
16553                slot: "checkout/$order",
16554            },
16555            WitTarget::Capability,
16556        ] {
16557            let per_arm = variant.http_endpoint();
16558            let pan_arm = variant.payload();
16559            if variant.is_http() {
16560                assert_eq!(
16561                    per_arm, pan_arm,
16562                    "WitTarget::{variant:?} http_endpoint() must equal \
16563                     payload() on the Http arm — a per-arm-vs-pan-arm \
16564                     split would silently drift the L7 emit branch's \
16565                     path-scalar source from the graph verb's payload \
16566                     scalar source",
16567                );
16568            } else {
16569                assert_eq!(
16570                    per_arm, None,
16571                    "WitTarget::{variant:?} http_endpoint() must return \
16572                     None on non-Http arms — a leak that surfaced a \
16573                     pub-sub :subject or a key/value :slot through the \
16574                     HTTP-endpoint accessor would silently widen the \
16575                     Cilium L7 HTTP `path:` rule accept-set onto \
16576                     protocol shapes Cilium's eBPF data-plane can't \
16577                     introspect",
16578                );
16579            }
16580        }
16581    }
16582
16583    #[test]
16584    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
16585        // Per-variant coherence pin: for every arm of [`WitTarget`],
16586        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
16587        // drift surface where a future extension of the
16588        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
16589        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
16590        // accessor to cover both peers) landed without a paired
16591        // extension of the [`gen_platform::IsVariant`]-derived
16592        // `is_http()` predicate's accept-set, or vice versa — a
16593        // regression that split the "which arms count as HTTP-shaped
16594        // for L7-path emission?" answer between two dispatch surfaces
16595        // the substrate ships. Sibling to the peer
16596        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
16597        // on the paired dispatch axis — extended onto the per-arm
16598        // predicate-vs-accessor coherence axis so the gen-platform
16599        // IsVariant predicate and the substrate-lifted per-arm
16600        // accessor carry one shared answer to "is this the HTTP arm?".
16601        for variant in [
16602            WitTarget::Http {
16603                endpoint: "/charge",
16604            },
16605            WitTarget::PubSub {
16606                subject: "events.checkout.paid",
16607            },
16608            WitTarget::Store {
16609                slot: "checkout/$order",
16610            },
16611            WitTarget::Capability,
16612        ] {
16613            assert_eq!(
16614                variant.http_endpoint().is_some(),
16615                variant.is_http(),
16616                "WitTarget::{variant:?} http_endpoint().is_some() must \
16617                 equal is_http() — a drift would split the L7 emit \
16618                 branch's arm-set gate from the substrate-derived \
16619                 shape-discrimination predicate on the same axis",
16620            );
16621        }
16622    }
16623
16624    #[test]
16625    fn wit_target_pubsub_subject_pins_per_variant() {
16626        // Fail-before-pass-after pin: the substrate-canonical per-arm
16627        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
16628        // is the single dispatch every future pub-sub-facing consumer
16629        // routes through, sibling to the peer [`WitContract::subject`]
16630        // (63e18a0) pre-projection scalar accessor on the raw-field
16631        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
16632        // post-projection per-arm accessor on the sibling HTTP-shape
16633        // axis. The [`WitTarget::PubSub`] arm round-trips its
16634        // author-declared subject verbatim as
16635        // `Some("events.checkout.paid")`; the three sibling arms each
16636        // return `None` because they carry no NATS-shaped subject by
16637        // definition. Same fail-before-pass-after per-variant discipline
16638        // as the sibling `wit_target_http_endpoint_pins_per_variant`
16639        // pin on the peer per-arm axis — extended onto the per-arm
16640        // pub-sub-shape post-projection axis so a future [`WitTarget`]
16641        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
16642        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
16643        // compile-time exhaustiveness error on the sibling
16644        // [`WitTarget::pubsub_subject`] match arms whose payload the
16645        // pub-sub-shape accept-set is meant to bound.
16646        assert_eq!(
16647            WitTarget::PubSub {
16648                subject: "events.checkout.paid",
16649            }
16650            .pubsub_subject(),
16651            Some("events.checkout.paid"),
16652        );
16653        assert_eq!(
16654            WitTarget::Http {
16655                endpoint: "/charge",
16656            }
16657            .pubsub_subject(),
16658            None,
16659        );
16660        assert_eq!(
16661            WitTarget::Store {
16662                slot: "checkout/$order",
16663            }
16664            .pubsub_subject(),
16665            None,
16666        );
16667        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
16668    }
16669
16670    #[test]
16671    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
16672        // Per-variant coherence pin: for every arm of [`WitTarget`],
16673        // `.pubsub_subject()` equals `.payload()` on the
16674        // [`WitTarget::PubSub`] arm (both project the same
16675        // author-declared subject scalar), and returns `None` on every
16676        // sibling arm regardless of whether [`WitTarget::payload`]
16677        // itself returns `Some` (Http / Store carry their own payload
16678        // the pan-arm accessor surfaces, but that payload is not a
16679        // pub-sub subject — the per-arm accessor must not leak it
16680        // through the pub-sub-shape channel). Sibling to the peer
16681        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
16682        // coherence pin on the per-arm HTTP-shape axis — extended onto
16683        // the per-arm pub-sub specialization axis so both per-arm
16684        // projections carry their own byte-shape coherence witness
16685        // against the substrate's typed arm-family accept-set.
16686        for variant in [
16687            WitTarget::Http {
16688                endpoint: "/charge",
16689            },
16690            WitTarget::PubSub {
16691                subject: "events.checkout.paid",
16692            },
16693            WitTarget::Store {
16694                slot: "checkout/$order",
16695            },
16696            WitTarget::Capability,
16697        ] {
16698            let per_arm = variant.pubsub_subject();
16699            let pan_arm = variant.payload();
16700            if variant.is_pubsub() {
16701                assert_eq!(
16702                    per_arm, pan_arm,
16703                    "WitTarget::{variant:?} pubsub_subject() must equal \
16704                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
16705                     split would silently drift the pub-sub-shape emit \
16706                     branch's subject-scalar source from the graph verb's \
16707                     payload scalar source",
16708                );
16709            } else {
16710                assert_eq!(
16711                    per_arm, None,
16712                    "WitTarget::{variant:?} pubsub_subject() must return \
16713                     None on non-PubSub arms — a leak that surfaced an \
16714                     HTTP :endpoint or a key/value :slot through the \
16715                     pub-sub-subject accessor would silently widen the \
16716                     downstream NATS-shape accept-set onto protocol \
16717                     shapes NATS servers can't route",
16718                );
16719            }
16720        }
16721    }
16722
16723    #[test]
16724    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
16725        // Per-variant coherence pin: for every arm of [`WitTarget`],
16726        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
16727        // drift surface where a future extension of the
16728        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
16729        // without a paired extension of the [`gen_platform::IsVariant`]-
16730        // derived `is_pubsub()` predicate's accept-set, or vice versa
16731        // — a regression that split the "which arms count as pub-sub-
16732        // shaped for subject emission?" answer between two dispatch
16733        // surfaces the substrate ships. Sibling to the peer
16734        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
16735        // pin on the per-arm HTTP-shape axis — extended onto the
16736        // per-arm pub-sub predicate-vs-accessor coherence axis so the
16737        // gen-platform IsVariant predicate and the substrate-lifted
16738        // per-arm accessor carry one shared answer to "is this the
16739        // PubSub arm?".
16740        for variant in [
16741            WitTarget::Http {
16742                endpoint: "/charge",
16743            },
16744            WitTarget::PubSub {
16745                subject: "events.checkout.paid",
16746            },
16747            WitTarget::Store {
16748                slot: "checkout/$order",
16749            },
16750            WitTarget::Capability,
16751        ] {
16752            assert_eq!(
16753                variant.pubsub_subject().is_some(),
16754                variant.is_pubsub(),
16755                "WitTarget::{variant:?} pubsub_subject().is_some() must \
16756                 equal is_pubsub() — a drift would split the pub-sub \
16757                 emit branch's arm-set gate from the substrate-derived \
16758                 shape-discrimination predicate on the same axis",
16759            );
16760        }
16761    }
16762
16763    #[test]
16764    fn wit_target_store_slot_pins_per_variant() {
16765        // Fail-before-pass-after pin: the substrate-canonical per-arm
16766        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
16767        // is the single dispatch every future store-facing consumer
16768        // routes through, sibling to the peer [`WitContract::slot`]
16769        // pre-projection scalar accessor on the raw-field axis and to
16770        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
16771        // [`WitTarget::pubsub_subject`] post-projection per-arm
16772        // accessors on the sibling per-payload-arm axes. The
16773        // [`WitTarget::Store`] arm round-trips its author-declared
16774        // slot verbatim as `Some("checkout/$order")`; the three
16775        // sibling arms each return `None` because they carry no
16776        // WASI-key/value slot by definition. Same fail-before-pass-
16777        // after per-variant discipline as the sibling
16778        // `wit_target_http_endpoint_pins_per_variant` +
16779        // `wit_target_pubsub_subject_pins_per_variant` pins on the
16780        // peer per-arm axes — extended onto the per-arm store-shape
16781        // post-projection axis so a future [`WitTarget`] variant
16782        // addition trips a compile-time exhaustiveness error on the
16783        // sibling [`WitTarget::store_slot`] match arms whose payload
16784        // the store-shape accept-set is meant to bound.
16785        assert_eq!(
16786            WitTarget::Store {
16787                slot: "checkout/$order",
16788            }
16789            .store_slot(),
16790            Some("checkout/$order"),
16791        );
16792        assert_eq!(
16793            WitTarget::Http {
16794                endpoint: "/charge",
16795            }
16796            .store_slot(),
16797            None,
16798        );
16799        assert_eq!(
16800            WitTarget::PubSub {
16801                subject: "events.checkout.paid",
16802            }
16803            .store_slot(),
16804            None,
16805        );
16806        assert_eq!(WitTarget::Capability.store_slot(), None);
16807    }
16808
16809    #[test]
16810    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
16811        // Per-variant coherence pin: for every arm of [`WitTarget`],
16812        // `.store_slot()` equals `.payload()` on the
16813        // [`WitTarget::Store`] arm (both project the same
16814        // author-declared slot scalar), and returns `None` on every
16815        // sibling arm regardless of whether [`WitTarget::payload`]
16816        // itself returns `Some`. Sibling to the peer
16817        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
16818        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
16819        // pins on the per-arm HTTP and PubSub axes — closes the
16820        // per-arm-vs-pan-arm byte-shape coherence trio across all
16821        // three payload arms.
16822        for variant in [
16823            WitTarget::Http {
16824                endpoint: "/charge",
16825            },
16826            WitTarget::PubSub {
16827                subject: "events.checkout.paid",
16828            },
16829            WitTarget::Store {
16830                slot: "checkout/$order",
16831            },
16832            WitTarget::Capability,
16833        ] {
16834            let per_arm = variant.store_slot();
16835            let pan_arm = variant.payload();
16836            if variant.is_store() {
16837                assert_eq!(
16838                    per_arm, pan_arm,
16839                    "WitTarget::{variant:?} store_slot() must equal \
16840                     payload() on the Store arm — a per-arm-vs-pan-arm \
16841                     split would silently drift the store-shape emit \
16842                     branch's slot-scalar source from the graph verb's \
16843                     payload scalar source",
16844                );
16845            } else {
16846                assert_eq!(
16847                    per_arm, None,
16848                    "WitTarget::{variant:?} store_slot() must return \
16849                     None on non-Store arms — a leak that surfaced an \
16850                     HTTP :endpoint or a NATS :subject through the \
16851                     key/value-slot accessor would silently widen the \
16852                     downstream WASI-key/value slot accept-set onto \
16853                     protocol shapes the kv backends can't route",
16854                );
16855            }
16856        }
16857    }
16858
16859    #[test]
16860    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
16861        // Per-variant coherence pin: for every arm of [`WitTarget`],
16862        // `.store_slot().is_some()` iff `.is_store()`. Guards the
16863        // drift surface where a future extension of the
16864        // [`WitTarget::store_slot`] accessor's accept-set landed
16865        // without a paired extension of the [`gen_platform::IsVariant`]-
16866        // derived `is_store()` predicate's accept-set. Sibling to the
16867        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
16868        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
16869        // pins — closes the per-arm predicate-vs-accessor coherence
16870        // trio across all three payload arms so the gen-platform
16871        // IsVariant predicate and the substrate-lifted per-arm
16872        // accessor carry one shared answer to "is this the Store arm?".
16873        for variant in [
16874            WitTarget::Http {
16875                endpoint: "/charge",
16876            },
16877            WitTarget::PubSub {
16878                subject: "events.checkout.paid",
16879            },
16880            WitTarget::Store {
16881                slot: "checkout/$order",
16882            },
16883            WitTarget::Capability,
16884        ] {
16885            assert_eq!(
16886                variant.store_slot().is_some(),
16887                variant.is_store(),
16888                "WitTarget::{variant:?} store_slot().is_some() must \
16889                 equal is_store() — a drift would split the store-shape \
16890                 emit branch's arm-set gate from the substrate-derived \
16891                 shape-discrimination predicate on the same axis",
16892            );
16893        }
16894    }
16895
16896    #[test]
16897    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
16898        // Fail-before-pass-after cross-axis pin on the trio
16899        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
16900        // payload-carrying arm of [`WitTarget`], exactly one per-arm
16901        // accessor returns `Some(payload)` and the two peers return
16902        // `None`; and on the payload-less [`WitTarget::Capability`]
16903        // arm, all three return `None`. Guards the drift surface where
16904        // a future extension of one per-arm accessor's accept-set (e.g.
16905        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
16906        // that widened `http_endpoint` to cover both peers without
16907        // narrowing the peer `pubsub_subject` / `store_slot` accept-
16908        // sets to keep the partition mutually exclusive) landed without
16909        // threading through the peer per-arm accessors — the resulting
16910        // silent overlap would land the same edge's payload on two
16911        // downstream per-shape emit branches at once, or leak a
16912        // pub-sub subject through the store-slot channel, at renderer
16913        // emit time far from the substrate primitive's arm-widening
16914        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
16915        // 3-way pin on the payload-field-name axis — extended onto the
16916        // per-arm-accessor payload-projection axis so the substrate-
16917        // owned partition invariant is load-bearing at every per-arm
16918        // consumer's read site.
16919        let payload_variants = [
16920            (
16921                WitTarget::Http {
16922                    endpoint: "/charge",
16923                },
16924                "http",
16925            ),
16926            (
16927                WitTarget::PubSub {
16928                    subject: "events.checkout.paid",
16929                },
16930                "pubsub",
16931            ),
16932            (
16933                WitTarget::Store {
16934                    slot: "checkout/$order",
16935                },
16936                "store",
16937            ),
16938        ];
16939        for (variant, own_arm_label) in payload_variants {
16940            let own_arm_hit = match own_arm_label {
16941                "http" => variant.is_http(),
16942                "pubsub" => variant.is_pubsub(),
16943                "store" => variant.is_store(),
16944                other => panic!("unknown own-arm label {other:?}"),
16945            };
16946            let per_arm_results = [
16947                ("http_endpoint", variant.http_endpoint()),
16948                ("pubsub_subject", variant.pubsub_subject()),
16949                ("store_slot", variant.store_slot()),
16950            ];
16951            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
16952            assert_eq!(
16953                some_count, 1,
16954                "WitTarget::{variant:?} must land exactly one per-arm \
16955                 post-projection accessor's Some result — the trio \
16956                 (http_endpoint, pubsub_subject, store_slot) must \
16957                 partition the payload arm-set; got {per_arm_results:?}",
16958            );
16959            assert!(
16960                own_arm_hit,
16961                "WitTarget::{variant:?} own-arm gen-platform predicate \
16962                 must return true on its own arm — a partition failure \
16963                 upstream of this pin",
16964            );
16965            assert!(
16966                variant.payload().is_some(),
16967                "WitTarget::{variant:?} pan-arm payload() must return \
16968                 Some on every payload-carrying arm the trio partitions",
16969            );
16970        }
16971        // The payload-less Capability arm must return None on every
16972        // per-arm accessor — the partition's terminal-fallback shape.
16973        let cap = WitTarget::Capability;
16974        assert_eq!(cap.http_endpoint(), None);
16975        assert_eq!(cap.pubsub_subject(), None);
16976        assert_eq!(cap.store_slot(), None);
16977        assert_eq!(
16978            cap.payload(),
16979            None,
16980            "WitTarget::Capability pan-arm payload() must return None — \
16981             the trio's payload-less-arm coherence witness",
16982        );
16983    }
16984
16985    #[test]
16986    fn wit_target_field_names_are_pairwise_distinct() {
16987        // Distinctness pin: if any two of the three payload-field-name
16988        // scalars ever collapse (e.g. an accidental `endpoint` copy-
16989        // paste over the `subject` const), the [`WitContract::target`]
16990        // gate's diagnostic would point authors at the wrong field —
16991        // an "expected `:endpoint`" error on a pub-sub edge would
16992        // silently misroute the fix. Same cross-axis-distinctness
16993        // discipline as the peer M3 `:placement :estrategia` variant-
16994        // discriminator scalar-value pins (cc8f749) applied to the
16995        // payload-field-name axis.
16996        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
16997        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
16998        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
16999    }
17000
17001    #[test]
17002    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
17003        // Fail-before-pass-after pin: the graph-verb payload column's
17004        // per-arm `{field}={payload}` byte-string is derived through the
17005        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
17006        // payload-carrying arms, not through a hand-rolled per-arm match
17007        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
17008        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
17009        // inline. A future variant addition — the M4-and-later per-edge
17010        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
17011        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
17012        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
17013        // and both [`WitTarget::label`] (duplicate-`:contratos`
17014        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
17015        // payload column) pick up the new arm from the same dispatch.
17016        // Prior to this lift the graph verb open-coded the 4-arm match
17017        // in caixa-feira, so a variant addition would have to be threaded
17018        // through both projections in lockstep or the graph verb would
17019        // silently drop the new arm to `(capability-only)`.
17020        for variant in [
17021            WitTarget::Http {
17022                endpoint: "/charge",
17023            },
17024            WitTarget::PubSub {
17025                subject: "events.checkout.paid",
17026            },
17027            WitTarget::Store {
17028                slot: "checkout/$order",
17029            },
17030        ] {
17031            let (field, payload) = variant
17032                .payload_pair()
17033                .expect("payload arm must expose (field, payload)");
17034            assert_eq!(
17035                variant.graph_label(),
17036                format!("{field}={payload}"),
17037                "WitTarget::{variant:?} graph_label must route the \
17038                 `{{field}}={{payload}}` template through payload_pair — \
17039                 a regression to a hand-rolled per-arm match at the graph \
17040                 verb would silently disagree with a future variant \
17041                 addition landed only at payload_pair"
17042            );
17043        }
17044    }
17045
17046    #[test]
17047    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
17048        // Fail-before-pass-after pin on the payload-less arm: the graph
17049        // verb's `(capability-only)` byte-string routes through the
17050        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
17051        // [`WitTarget::Capability`] arm, not through an inline
17052        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
17053        // per-`:contratos` payload column. Peer of the sibling
17054        // [`wit_target_label_pins_per_variant_format`] Capability-arm
17055        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
17056        // extended here onto the third payload-less-arm consumer axis
17057        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
17058        // axis and the wrong-target diagnostic axis).
17059        assert_eq!(
17060            WitTarget::Capability.graph_label(),
17061            WitTarget::CAPABILITY_GRAPH_LABEL,
17062        );
17063        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
17064    }
17065
17066    #[test]
17067    fn wit_target_capability_graph_label_distinct_from_capability_label() {
17068        // Cross-consumer-axis distinctness pin: the graph-verb
17069        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
17070        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
17071        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
17072        // payload)`) surface the payload-less arm on two distinct
17073        // consumer axes; a collapse (an accidental rebrand that lands
17074        // one spelling on both consts, a copy-paste that unifies them
17075        // "for consistency") would silently merge the two byte-strings
17076        // and lose the vocabulary distinction the graph verb's
17077        // compact-column form and the diagnostic's descriptive-clause
17078        // form each carry on purpose. Peer of the sibling 4-way
17079        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
17080        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
17081        // extended here onto the cross-consumer-axis distinctness of the
17082        // two payload-less-arm consts.
17083        assert_ne!(
17084            WitTarget::CAPABILITY_GRAPH_LABEL,
17085            WitTarget::CAPABILITY_LABEL,
17086            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
17087             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
17088             diagnostic) must remain distinct — a collapse would silently \
17089             merge two consumer axes onto one spelling"
17090        );
17091    }
17092
17093    #[test]
17094    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
17095        // 4-way distinctness pin extending the sibling
17096        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
17097        // (which covers only the HTTP / PubSub / Store payload arms)
17098        // onto the fourth scalar the shared
17099        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
17100        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
17101        // (`"none"`), the payload-less Capability-arm rejection scalar.
17102        //
17103        // All four [`WitTarget::HTTP_FIELD_NAME`] /
17104        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
17105        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
17106        // dispatch surface [`WitContract::target`] writes onto the
17107        // `ContratoWrongTarget::expected` field — the same `&'static
17108        // str` axis authors read as "this WIT world's shape admits
17109        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
17110        // downstream consumers rely on: an `expected: "endpoint"`
17111        // diagnostic on a Capability-shaped edge tells the author to
17112        // add a `:endpoint "…"` slot to a WIT world that admits none,
17113        // silently misrouting the fix. Until this pin landed the three
17114        // payload-arm consts were distinctness-guarded by the sibling
17115        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
17116        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
17117        // author-facing vocabulary shift from `"none"` to `"endpoint"`
17118        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
17119        // into per-shape peers) would have silently landed one
17120        // Capability-arm rejection on a payload-arm's `expected:` byte-
17121        // string and desynchronized the diagnostic from the author's
17122        // typed shape.
17123        //
17124        // Same 4-way pairwise-distinctness pin discipline as the peer
17125        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
17126        // (cc8f749) applies on the sibling M3 closed-set typed-enum
17127        // scalar-value dispatch axis; extends the pin trajectory the
17128        // sibling `wit_target_field_names_are_pairwise_distinct`
17129        // 3-way pin opened to cover the last unguarded corner on the
17130        // `ContratoWrongTarget::expected` scalar-value axis.
17131        //
17132        // Fail-before-pass-after locally verified by mutating
17133        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
17134        // — this pin fires as expected; restoring passes.
17135        let all = [
17136            WitTarget::HTTP_FIELD_NAME,
17137            WitTarget::PUBSUB_FIELD_NAME,
17138            WitTarget::STORE_FIELD_NAME,
17139            WitTarget::CAPABILITY_EXPECTED,
17140        ];
17141        for (i, a) in all.iter().enumerate() {
17142            for (j, b) in all.iter().enumerate() {
17143                if i != j {
17144                    assert_ne!(
17145                        a, b,
17146                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
17147                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
17148                         pairwise distinct — got duplicate {a:?} at indices \
17149                         {i} and {j}; all four scalars thread through the \
17150                         shared `AplicacaoError::ContratoWrongTarget::expected` \
17151                         &'static str axis, so a collapse silently misdirects \
17152                         the diagnostic on which typed shape the WIT world admits",
17153                    );
17154                }
17155            }
17156        }
17157    }
17158
17159    #[test]
17160    fn wit_target_is_variant_predicates_partition_the_arm_set() {
17161        // Fail-before-pass-after pin on the
17162        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
17163        // each of the four variants exactly one of the generated
17164        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
17165        // predicates returns `true` and the other three return
17166        // `false`. Prior to this derive the only production
17167        // arm-discriminator on [`WitTarget`] — the sync-cycle
17168        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
17169        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
17170        // the variant that expressed no compile-time link back to
17171        // the closed-set typed dispatch a future fifth
17172        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
17173        // split of [`WitTarget::PubSub`] into shape-specific peers,
17174        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
17175        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
17176        // to thread through in lockstep or the DFS exclusion would
17177        // silently disagree with the peer diagnostic templates on
17178        // which arms carry sync-versus-async semantics. Peer of the
17179        // sibling [`crate::CaixaKind`] (f5bba80),
17180        // [`PlacementStrategy`] (766ec63),
17181        // [`crate::supervisor::RestartStrategy`],
17182        // [`crate::supervisor::RestartPolicy`], and
17183        // [`crate::upgrade::UpgradeInstruction`] (915a934)
17184        // `IsVariant` derives on the sibling closed-set typed-enum
17185        // discriminator axes — extends the same one-typed-dispatch-
17186        // per-variant discipline onto the last unlifted closed-set
17187        // typed-enum discriminator on the caixa surface (the M3
17188        // mesh-slot per-`:contratos` target-arm axis), closing the
17189        // arm-discriminator convergence trajectory across every
17190        // closed-set typed enum in caixa-core.
17191        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
17192            (
17193                WitTarget::Http { endpoint: "/x" },
17194                [true, false, false, false],
17195            ),
17196            (
17197                WitTarget::PubSub {
17198                    subject: "events.x",
17199                },
17200                [false, true, false, false],
17201            ),
17202            (
17203                WitTarget::Store { slot: "kv/x" },
17204                [false, false, true, false],
17205            ),
17206            (WitTarget::Capability, [false, false, false, true]),
17207        ];
17208        for (variant, expected) in rows {
17209            let observed = [
17210                variant.is_http(),
17211                variant.is_pubsub(),
17212                variant.is_store(),
17213                variant.is_capability(),
17214            ];
17215            assert_eq!(
17216                observed, expected,
17217                "WitTarget::{variant:?} is_* predicates must partition \
17218                 the arm set (http, pubsub, store, capability); got {observed:?}"
17219            );
17220        }
17221    }
17222
17223    #[test]
17224    fn wit_target_is_variant_predicates_are_const_fn() {
17225        // The [`gen_platform::IsVariant`] derive emits `const fn`
17226        // predicates on the peer [`crate::CaixaKind`] +
17227        // [`crate::upgrade::UpgradeInstruction`] +
17228        // [`crate::supervisor::RestartStrategy`] +
17229        // [`crate::supervisor::RestartPolicy`] +
17230        // [`PlacementStrategy`] closed-set typed enums — pin the
17231        // same posture on [`WitTarget`] so a future accidental
17232        // downgrade to non-`const` (an added runtime helper reachable
17233        // only from a non-`const` context, a manual hand-rolled
17234        // `impl` that shadows the derive-generated method) trips at
17235        // caixa-core build time rather than surfacing as a downstream
17236        // `const`-context regression far from the derive declaration.
17237        //
17238        // Unlike the peer unit-variant enums (`CaixaKind` /
17239        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
17240        // whose `const` constructors need no arguments, the three
17241        // payload-carrying [`WitTarget`] arms are const-constructed
17242        // through `&'static str` payloads — the same `'static`
17243        // lifetime the closed-set typed enum's four-arm partition
17244        // pin above already threads through.
17245        //
17246        // The pin lives inside a `const { assert!(..) }` block so the
17247        // compiler enforces both halves (arm predicate is `const`-
17248        // callable AND returns `true` for the matching arm) at
17249        // caixa-core compile time — peer to the sibling
17250        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
17251        // typed enum arm-predicate const-callability axis.
17252        const {
17253            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
17254            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
17255            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
17256            assert!(WitTarget::Capability.is_capability());
17257        }
17258    }
17259
17260    #[test]
17261    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
17262        // Consumer-side pin on the sole production converge site:
17263        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
17264        // edges from the synchronous-subgraph DFS via the lifted
17265        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
17266        // predicate (rebound from the prior raw
17267        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
17268        // variant). Byte-equivalent today (`is_pubsub` is the
17269        // derive-generated `matches!(self, Self::PubSub { .. })` by
17270        // construction, the `#[is_variant(name = "pubsub")]` override
17271        // aliasing the auto-derived `is_pub_sub` back to the sibling
17272        // [`WitContract::is_pubsub`] name); pin the behavior so a
17273        // future accidental drift (a rebind onto a peer arm
17274        // predicate, a manual hand-rolled `impl` that shadows the
17275        // derive-generated method with different semantics, a peer
17276        // arm rename that shifts which variant carries sync-versus-
17277        // async semantics) trips at caixa-core test time rather than
17278        // at some downstream operator's runtime dispatch far from the
17279        // rebind commit.
17280        //
17281        // The fixture constructs a two-Servico Aplicacao with one
17282        // pub-sub edge that would close a sync-cycle if the DFS did
17283        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
17284        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
17285        // edge, which is not a cycle. A regression in the converge
17286        // (a rebind that reads the pub-sub arm as sync) would report
17287        // `AplicacaoError::ContratoCycle`.
17288        let s = AplicacaoSpec {
17289            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
17290            contratos: vec![
17291                // Pub-sub edge: DFS must skip via is_pubsub().
17292                WitContract {
17293                    de: "a".into(),
17294                    para: "b".into(),
17295                    wit: "nats:pub-sub".into(),
17296                    endpoint: None,
17297                    subject: Some("events.x".into()),
17298                    slot: None,
17299                },
17300                // HTTP edge: DFS must include.
17301                WitContract {
17302                    de: "b".into(),
17303                    para: "a".into(),
17304                    wit: "wasi:http/proxy".into(),
17305                    endpoint: Some("/x".into()),
17306                    subject: None,
17307                    slot: None,
17308                },
17309            ],
17310            politicas: MeshPolicy::default(),
17311            placement: Placement {
17312                estrategia: PlacementStrategy::Replicated,
17313                clusters: vec!["rio".into()],
17314                affinity: None,
17315                shard_key: None,
17316            },
17317            entrada: None,
17318        };
17319        s.validate()
17320            .expect("pub-sub edge must be excluded from sync-cycle DFS");
17321    }
17322
17323    #[test]
17324    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
17325        // Consumer-side pin: the same three peer consts thread through
17326        // both the [`WitTarget::label`] template (leading-`:` keyword
17327        // prefix in the duplicate-`:contratos` diagnostic) and the
17328        // [`WitContract::target`] gate's [`AplicacaoError::
17329        // ContratoMissingTarget`] `expected:` scalar (the field the
17330        // author needs to add). Pin both routes at once so a future
17331        // refactor can't accidentally split them onto separate string
17332        // literals — the "one place, everywhere reaches for it"
17333        // invariant the peer const set carries.
17334        let http_label = WitTarget::Http { endpoint: "/x" }.label();
17335        assert!(
17336            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
17337            "label must lead with :{} keyword (got {http_label:?})",
17338            WitTarget::HTTP_FIELD_NAME,
17339        );
17340
17341        let mut s = three_member_spec();
17342        s.contratos.push(WitContract {
17343            de: "cart".into(),
17344            para: "catalog".into(),
17345            wit: "kafka:topic".into(),
17346            endpoint: None,
17347            subject: None,
17348            slot: None,
17349        });
17350        match s.validate().unwrap_err() {
17351            AplicacaoError::ContratoMissingTarget { expected, .. } => {
17352                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
17353            }
17354            other => panic!("expected ContratoMissingTarget, got {other:?}"),
17355        }
17356    }
17357
17358    #[test]
17359    fn duplicate_pubsub_diagnostic_names_offending_subject() {
17360        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
17361        // on the pub-sub target axis: the duplicate-edge diagnostic
17362        // must name the `:subject` payload verbatim (not just the
17363        // `(de, para, wit)` triple). Prior to lifting the label onto
17364        // [`WitTarget::label`] the diagnostic derived the label from
17365        // raw [`WitContract`] `Option<String>` probes — a future
17366        // `WitTarget` variant addition (M4 per-edge WIT registry)
17367        // would silently fall through to the `Capability` "no
17368        // payload" default without a compiler warning. Pinning the
17369        // pub-sub arm's format closes the second of three
17370        // payload-carrying `WitTarget` arms this diagnostic threads
17371        // through.
17372        let mut s = three_member_spec();
17373        let pubsub = WitContract {
17374            de: "payment".into(),
17375            para: "cart".into(),
17376            wit: "nats:pub-sub".into(),
17377            endpoint: None,
17378            subject: Some("events.checkout.paid".into()),
17379            slot: None,
17380        };
17381        s.contratos.push(pubsub.clone());
17382        s.contratos.push(pubsub);
17383        let err = s.validate().unwrap_err();
17384        let msg = format!("{err}");
17385        assert!(
17386            msg.contains(":subject \"events.checkout.paid\""),
17387            "duplicate-pubsub diagnostic must name the offending \
17388             :subject payload (got: {msg:?})"
17389        );
17390    }
17391
17392    #[test]
17393    fn duplicate_store_diagnostic_names_offending_slot() {
17394        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
17395        // key-value target axis: the diagnostic must name the `:slot`
17396        // payload verbatim. Third of three payload-carrying
17397        // `WitTarget` arms this diagnostic threads through, closing
17398        // the per-arm label pin trilogy (`Http` — 6841,
17399        // `PubSub` + `Store` — this test + peer above).
17400        let mut s = three_member_spec();
17401        let store = WitContract {
17402            de: "cart".into(),
17403            para: "payment".into(),
17404            wit: "wasi:keyvalue/store".into(),
17405            endpoint: None,
17406            subject: None,
17407            slot: Some("checkout/$orderId".into()),
17408        };
17409        s.contratos
17410            .retain(|c| !(c.de == "cart" && c.para == "payment"));
17411        s.contratos.push(store.clone());
17412        s.contratos.push(store);
17413        let err = s.validate().unwrap_err();
17414        let msg = format!("{err}");
17415        assert!(
17416            msg.contains(":slot \"checkout/$orderId\""),
17417            "duplicate-store diagnostic must name the offending :slot \
17418             payload (got: {msg:?})"
17419        );
17420    }
17421
17422    #[test]
17423    fn rejects_entrada_path_without_leading_slash() {
17424        let mut s = three_member_spec();
17425        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
17426        let err = s.validate().unwrap_err();
17427        assert!(
17428            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
17429            "got {err:?}"
17430        );
17431    }
17432
17433    #[test]
17434    fn rejects_empty_entrada_path() {
17435        let mut s = three_member_spec();
17436        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
17437        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
17438    }
17439
17440    #[test]
17441    fn rejects_duplicate_entrada_paths() {
17442        let mut s = three_member_spec();
17443        s.entrada.as_mut().unwrap().paths = vec![
17444            "/api/cart".into(),
17445            "/api/products".into(),
17446            "/api/cart".into(),
17447        ];
17448        let err = s.validate().unwrap_err();
17449        assert!(
17450            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
17451            "got {err:?}"
17452        );
17453    }
17454
17455    #[test]
17456    fn rejects_zero_entrada_port() {
17457        let mut s = three_member_spec();
17458        s.entrada.as_mut().unwrap().port = 0;
17459        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
17460    }
17461
17462    // ── :entrada :paths value-shape gate ─────────────────────────────
17463    //
17464    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
17465    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
17466    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
17467    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
17468    // time now becomes a caixa-build-time `EntradaPathInvalid` with
17469    // the offending `:paths` entry named verbatim.
17470
17471    #[test]
17472    fn rejects_entrada_path_with_query() {
17473        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
17474        // silently passed validate and the Gateway API webhook
17475        // rejected it at apply time with no source citation.
17476        let mut s = three_member_spec();
17477        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
17478        let err = s.validate().unwrap_err();
17479        assert!(
17480            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17481                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
17482            "got {err:?}"
17483        );
17484    }
17485
17486    #[test]
17487    fn rejects_entrada_path_with_fragment() {
17488        let mut s = three_member_spec();
17489        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
17490        let err = s.validate().unwrap_err();
17491        assert!(
17492            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17493                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
17494            "got {err:?}"
17495        );
17496    }
17497
17498    #[test]
17499    fn rejects_entrada_path_with_space() {
17500        let mut s = three_member_spec();
17501        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
17502        let err = s.validate().unwrap_err();
17503        assert!(
17504            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17505                if path == "/api/my cart" && reason.contains("whitespace")),
17506            "got {err:?}"
17507        );
17508    }
17509
17510    #[test]
17511    fn rejects_entrada_path_with_tab() {
17512        let mut s = three_member_spec();
17513        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
17514        let err = s.validate().unwrap_err();
17515        assert!(
17516            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17517                if path == "/api/\tcart" && reason.contains("whitespace")),
17518            "got {err:?}"
17519        );
17520    }
17521
17522    #[test]
17523    fn rejects_entrada_path_with_control_char() {
17524        // 0x01 (SOH) — a non-whitespace control char surfaces the
17525        // distinct "control character" reason arm, separate from
17526        // the whitespace arm. Pinned so a future refactor that
17527        // collapses the two arms can't accidentally drop the more
17528        // self-locating diagnostic.
17529        let mut s = three_member_spec();
17530        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
17531        let err = s.validate().unwrap_err();
17532        assert!(
17533            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17534                if path == "/api/\x01cart" && reason.contains("control character")),
17535            "got {err:?}"
17536        );
17537    }
17538
17539    #[test]
17540    fn rejects_entrada_path_with_non_ascii() {
17541        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
17542        // unreserved-set rule rejects. The Gateway API webhook
17543        // rejects literal non-ASCII bytes; percent-encoding is the
17544        // only way to author non-ASCII in a path.
17545        let mut s = three_member_spec();
17546        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
17547        let err = s.validate().unwrap_err();
17548        assert!(
17549            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17550                if path == "/api/café" && reason.contains("non-ASCII")),
17551            "got {err:?}"
17552        );
17553    }
17554
17555    #[test]
17556    fn rejects_entrada_path_with_consecutive_slashes() {
17557        let mut s = three_member_spec();
17558        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
17559        let err = s.validate().unwrap_err();
17560        assert!(
17561            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17562                if path == "/api//cart" && reason.contains("consecutive `/`")),
17563            "got {err:?}"
17564        );
17565    }
17566
17567    #[test]
17568    fn rejects_entrada_path_with_dot_segment() {
17569        let mut s = three_member_spec();
17570        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
17571        let err = s.validate().unwrap_err();
17572        assert!(
17573            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17574                if path == "/api/./cart" && reason.contains("`.` segment")),
17575            "got {err:?}"
17576        );
17577    }
17578
17579    #[test]
17580    fn rejects_entrada_path_with_trailing_dot_segment() {
17581        // The bare `/.` and the trailing `/foo/.` are both rejected
17582        // by the Gateway API webhook; pinned separately so a future
17583        // narrowing that catches only the inner form surfaces here.
17584        let mut s = three_member_spec();
17585        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
17586        let err = s.validate().unwrap_err();
17587        assert!(
17588            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17589                if path == "/api/." && reason.contains("`.` segment")),
17590            "got {err:?}"
17591        );
17592    }
17593
17594    #[test]
17595    fn rejects_entrada_path_with_parent_segment() {
17596        let mut s = three_member_spec();
17597        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
17598        let err = s.validate().unwrap_err();
17599        assert!(
17600            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17601                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
17602            "got {err:?}"
17603        );
17604    }
17605
17606    #[test]
17607    fn rejects_entrada_path_with_trailing_parent_segment() {
17608        // Trailing `/..` — symmetric arm of the parent-segment rule,
17609        // pinned separately so a future relaxation that only checks
17610        // the inner form (`/../`) surfaces here.
17611        let mut s = three_member_spec();
17612        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
17613        let err = s.validate().unwrap_err();
17614        assert!(
17615            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17616                if path == "/api/.." && reason.contains("`..` parent-segment")),
17617            "got {err:?}"
17618        );
17619    }
17620
17621    #[test]
17622    fn rejects_entrada_path_too_long() {
17623        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
17624        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
17625        // ASCII-alphanumeric body so only the length rule fires.
17626        let mut s = three_member_spec();
17627        let big = format!("/api/{}", "a".repeat(1020));
17628        assert_eq!(big.len(), 1025);
17629        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
17630        let err = s.validate().unwrap_err();
17631        assert!(
17632            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17633                if path == &big && reason.contains("max length of 1024")),
17634            "got {err:?}"
17635        );
17636    }
17637
17638    #[test]
17639    fn entrada_path_max_length_validates() {
17640        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
17641        // maxLength cap. Boundary pin: drift in the cap surfaces here
17642        // and at `rejects_entrada_path_too_long` simultaneously.
17643        let mut s = three_member_spec();
17644        let big = format!("/api/{}", "a".repeat(1019));
17645        assert_eq!(big.len(), 1024);
17646        s.entrada.as_mut().unwrap().paths = vec![big];
17647        s.validate().unwrap();
17648    }
17649
17650    #[test]
17651    fn entrada_accepts_canonical_paths() {
17652        // Positive-control sweep — every form the Gateway API
17653        // apiserver accepts must round-trip through validate. Covers
17654        // the root catch-all, plain paths, dot-prefixed segments
17655        // (hidden-file-style, distinct from `.` and `..` segments
17656        // which are rejected), digit-bearing segments, the canonical
17657        // route-template `:param` form (`:` is RFC 3986 reserved-set
17658        // valid in paths), trailing-slash form, percent-encoded
17659        // segments, and an interior `..` *substring* (`/foo..bar` is
17660        // not the `..` segment and is allowed).
17661        for path in [
17662            "/",
17663            "/api/cart",
17664            "/healthz",
17665            "/api/.config",
17666            "/v1/products",
17667            "/products/:id",
17668            "/api/cart/",
17669            "/api/caf%C3%A9",
17670            "/foo..bar",
17671            "/...",
17672        ] {
17673            let mut s = three_member_spec();
17674            s.entrada.as_mut().unwrap().paths = vec![path.into()];
17675            s.validate()
17676                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
17677        }
17678    }
17679
17680    #[test]
17681    fn entrada_path_empty_takes_precedence_over_invalid() {
17682        // Ordering pin: `EntradaPathEmpty` is the more self-locating
17683        // diagnostic on `""` and must lead — `validate_entrada_path`
17684        // is only reached after the empty-check fires at the call
17685        // site. (The predicate itself defends against direct
17686        // invocation by returning the same error on `""`.)
17687        let mut s = three_member_spec();
17688        s.entrada.as_mut().unwrap().paths = vec![String::new()];
17689        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
17690    }
17691
17692    #[test]
17693    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
17694        // Ordering pin: a path without a leading `/` surfaces the
17695        // narrower `EntradaPathNotAbsolute` diagnostic first; the
17696        // value-shape gate is only consulted on paths that already
17697        // satisfy the absolute-prefix invariant.
17698        let mut s = three_member_spec();
17699        // `bad path` would fire the whitespace rule under the
17700        // value-shape gate, but missing-leading-`/` is the more
17701        // self-locating diagnostic.
17702        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
17703        let err = s.validate().unwrap_err();
17704        assert!(
17705            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
17706            "got {err:?}"
17707        );
17708    }
17709
17710    #[test]
17711    fn entrada_path_invalid_fires_before_duplicate_check() {
17712        // Ordering pin: a malformed path on the *first* entry of a
17713        // would-be duplicate pair fires the value-shape gate before
17714        // the duplicate gate, mirroring the
17715        // `placement_cluster_invalid_fires_before_duplicate_check`
17716        // (6cbb900) pattern on the peer axis.
17717        let mut s = three_member_spec();
17718        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
17719        let err = s.validate().unwrap_err();
17720        assert!(
17721            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
17722            "got {err:?}"
17723        );
17724    }
17725
17726    #[test]
17727    fn entrada_path_diagnostic_carries_offending_path() {
17728        // Diagnostic-shape pin — the offending path + a non-empty
17729        // reason flow through verbatim so the author can grep their
17730        // caixa.lisp for `:paths` and fix it in one edit. Same shape
17731        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
17732        let mut s = three_member_spec();
17733        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
17734        let err = s.validate().unwrap_err();
17735        match err {
17736            AplicacaoError::EntradaPathInvalid { path, reason } => {
17737                assert_eq!(path, "/api?q=1");
17738                assert!(!reason.is_empty(), "reason field must be non-empty");
17739            }
17740            other => panic!("expected EntradaPathInvalid, got {other:?}"),
17741        }
17742    }
17743
17744    #[test]
17745    fn rejects_entrada_path_with_curly_brace_template_form() {
17746        // Per-axis pin on the shared `is_gateway_api_http_path`
17747        // reserved-byte arm: the canonical "I wrote an OpenAPI
17748        // path-template `{id}` instead of the Gateway API `:id` form"
17749        // footgun the K8s apiserver would otherwise catch at admission
17750        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
17751        // landing site, far from the caixa.lisp. Surfaces as
17752        // `EntradaPathInvalid` carrying the offending path verbatim
17753        // plus the canonical `%7B`/`%7D` percent-encoding remediation
17754        // — the substrate-side `gateway_api_http_path_rejects_every_
17755        // reserved_printable_ascii_byte` predicate-level sweep pins the
17756        // full eleven-byte set; this per-axis pin confirms the
17757        // diagnostic flows through to the `EntradaPathInvalid` variant.
17758        let mut s = three_member_spec();
17759        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
17760        let err = s.validate().unwrap_err();
17761        assert!(
17762            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
17763                if path == "/api/cart/{id}"
17764                    && reason.contains("reserved character")
17765                    && reason.contains("'{'")
17766                    && reason.contains("%7B")),
17767            "got {err:?}"
17768        );
17769    }
17770
17771    #[test]
17772    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
17773        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
17774        // template_form` on the sibling `:contratos :endpoint` axis.
17775        // Same shared `is_gateway_api_http_path` reserved-byte arm
17776        // fires through `ContratoEndpointInvalid`, with the offending
17777        // endpoint + `:de` + `:para` + reason flowing through verbatim.
17778        // Pins that the lifted predicate's tightening lands on both
17779        // caller axes simultaneously — one source of truth for the
17780        // Gateway API HTTPPathMatch.value accepted set.
17781        let err = contrato_endpoint_err("/api/cart/{id}");
17782        assert!(
17783            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
17784                if endpoint == "/api/cart/{id}"
17785                    && reason.contains("reserved character")
17786                    && reason.contains("'{'")
17787                    && reason.contains("%7B")),
17788            "got {err:?}"
17789        );
17790    }
17791
17792    // ── :entrada :host value-shape gate ──────────────────────────────
17793    //
17794    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
17795    // the sibling `:host` axis. Every authoring footgun the K8s
17796    // Gateway API v1 apiserver would catch at admission time becomes
17797    // a caixa-build-time `EntradaHostInvalid` with the offending
17798    // `:host` named verbatim. Same diagnostic shape as
17799    // `MembroVersaoInvalid` (9888b13).
17800
17801    #[test]
17802    fn rejects_entrada_host_with_scheme() {
17803        // Fail-before-pass-after pin — pre-gate codebases silently
17804        // accepted `https://…` and the apiserver rejected it at apply
17805        // time with no source citation.
17806        let mut s = three_member_spec();
17807        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
17808        let err = s.validate().unwrap_err();
17809        assert!(
17810            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17811                if host == "https://checkout.quero.cloud"),
17812            "got {err:?}"
17813        );
17814    }
17815
17816    #[test]
17817    fn rejects_entrada_host_with_port() {
17818        // The `:8080` port suffix is the canonical "I forgot the port
17819        // belongs in `:entrada :port`" footgun. The top-level `:` arm
17820        // (introduced after the per-label loop-only impl silently
17821        // surfaced a deep "label \"cloud:8080\" contains invalid
17822        // character ':'" leak) names the canonical fix verbatim — the
17823        // `:entrada :port` slot.
17824        let mut s = three_member_spec();
17825        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
17826        let err = s.validate().unwrap_err();
17827        assert!(
17828            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17829                if host == "checkout.quero.cloud:8080"
17830                && reason.contains(":entrada :port")),
17831            "got {err:?}"
17832        );
17833    }
17834
17835    #[test]
17836    fn rejects_entrada_host_with_trailing_colon() {
17837        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
17838        // edit) — the per-label loop would land it as a deep
17839        // "label \"com:\" must start and end with an alphanumeric"
17840        // / "contains invalid character ':'" leak. The top-level
17841        // `:` arm pre-empts with the canonical `:port` slot
17842        // diagnostic.
17843        let mut s = three_member_spec();
17844        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
17845        let err = s.validate().unwrap_err();
17846        assert!(
17847            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17848                if host == "checkout.quero.cloud:"
17849                && reason.contains(":entrada :port")),
17850            "got {err:?}"
17851        );
17852    }
17853
17854    #[test]
17855    fn rejects_entrada_host_unbracketed_ipv6_literal() {
17856        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
17857        // literals across the board (peer with `rejects_entrada_host_
17858        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
17859        // Before this top-level `:` arm landed the per-label loop
17860        // surfaced a single-label byte-class diagnostic that named the
17861        // `:` byte but not the IP-literal prohibition. The top-level
17862        // `:` arm names both the `:port` slot and the IP-literal
17863        // prohibition verbatim, so an author whose `:host "2001:..."`
17864        // value lands here gets a self-locating fix either way.
17865        let mut s = three_member_spec();
17866        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
17867        let err = s.validate().unwrap_err();
17868        assert!(
17869            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17870                if host == "2001:db8::1"
17871                && reason.contains("IPv6")),
17872            "got {err:?}"
17873        );
17874    }
17875
17876    #[test]
17877    fn rejects_entrada_host_wildcard_with_port() {
17878        // Wildcard host with port suffix — the `*.` strip and the
17879        // per-label loop on `["foo", "quero", "cloud:8080"]` would
17880        // surface the deep byte-class leak. The top-level `:` arm sits
17881        // upstream of the `*.` strip, so it names the canonical `:port`
17882        // fix verbatim regardless of whether the host is wildcard-led.
17883        let mut s = three_member_spec();
17884        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
17885        let err = s.validate().unwrap_err();
17886        assert!(
17887            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
17888                if host == "*.quero.cloud:8080"
17889                && reason.contains(":entrada :port")),
17890            "got {err:?}"
17891        );
17892    }
17893
17894    #[test]
17895    fn rejects_entrada_host_with_path() {
17896        let mut s = three_member_spec();
17897        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
17898        let err = s.validate().unwrap_err();
17899        assert!(
17900            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17901                if host == "checkout.quero.cloud/api"),
17902            "got {err:?}"
17903        );
17904    }
17905
17906    #[test]
17907    fn rejects_entrada_host_with_uppercase() {
17908        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
17909        // rejected, not silently lower-cased.
17910        let mut s = three_member_spec();
17911        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
17912        let err = s.validate().unwrap_err();
17913        assert!(
17914            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17915                if reason.contains("uppercase")),
17916            "got {err:?}"
17917        );
17918    }
17919
17920    #[test]
17921    fn rejects_entrada_host_with_underscore() {
17922        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
17923        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
17924        let mut s = three_member_spec();
17925        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
17926        let err = s.validate().unwrap_err();
17927        assert!(
17928            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17929                if reason.contains('_')),
17930            "got {err:?}"
17931        );
17932    }
17933
17934    #[test]
17935    fn rejects_entrada_host_ipv4_literal() {
17936        // Gateway API v1 explicitly forbids IP literals as Hostnames.
17937        let mut s = three_member_spec();
17938        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
17939        let err = s.validate().unwrap_err();
17940        assert!(
17941            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17942                if reason.contains("IPv4")),
17943            "got {err:?}"
17944        );
17945    }
17946
17947    #[test]
17948    fn rejects_entrada_host_with_trailing_dot() {
17949        // The Gateway API regex anchors at end-of-string with no
17950        // trailing `.` allowance — the FQDN root-dot form is rejected.
17951        let mut s = three_member_spec();
17952        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
17953        let err = s.validate().unwrap_err();
17954        assert!(
17955            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
17956                if host == "checkout.quero.cloud."),
17957            "got {err:?}"
17958        );
17959    }
17960
17961    #[test]
17962    fn rejects_entrada_host_with_leading_dot() {
17963        let mut s = three_member_spec();
17964        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
17965        let err = s.validate().unwrap_err();
17966        assert!(
17967            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17968                if reason.contains("empty label")),
17969            "got {err:?}"
17970        );
17971    }
17972
17973    #[test]
17974    fn rejects_entrada_host_with_consecutive_dots() {
17975        let mut s = three_member_spec();
17976        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
17977        let err = s.validate().unwrap_err();
17978        assert!(
17979            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17980                if reason.contains("empty label")),
17981            "got {err:?}"
17982        );
17983    }
17984
17985    #[test]
17986    fn rejects_entrada_host_with_leading_hyphen_label() {
17987        let mut s = three_member_spec();
17988        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
17989        let err = s.validate().unwrap_err();
17990        assert!(
17991            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
17992                if reason.contains("alphanumeric")),
17993            "got {err:?}"
17994        );
17995    }
17996
17997    #[test]
17998    fn rejects_entrada_host_with_trailing_hyphen_label() {
17999        let mut s = three_member_spec();
18000        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
18001        let err = s.validate().unwrap_err();
18002        assert!(
18003            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18004                if reason.contains("alphanumeric")),
18005            "got {err:?}"
18006        );
18007    }
18008
18009    #[test]
18010    fn rejects_entrada_host_with_inner_wildcard() {
18011        // Gateway API allows `*` only as the first label (`*.foo`);
18012        // any inner or trailing `*` is rejected.
18013        let mut s = three_member_spec();
18014        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
18015        let err = s.validate().unwrap_err();
18016        assert!(
18017            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18018                if reason.contains("wildcard")),
18019            "got {err:?}"
18020        );
18021    }
18022
18023    #[test]
18024    fn rejects_entrada_host_bare_wildcard() {
18025        // `*.` with no domain is meaningless; Gateway API rejects it.
18026        let mut s = three_member_spec();
18027        s.entrada.as_mut().unwrap().host = "*.".into();
18028        let err = s.validate().unwrap_err();
18029        assert!(
18030            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18031                if reason.contains("wildcard")),
18032            "got {err:?}"
18033        );
18034    }
18035
18036    #[test]
18037    fn rejects_entrada_host_with_whitespace() {
18038        let mut s = three_member_spec();
18039        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
18040        let err = s.validate().unwrap_err();
18041        assert!(
18042            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18043                if reason.contains("whitespace")),
18044            "got {err:?}"
18045        );
18046    }
18047
18048    #[test]
18049    fn rejects_entrada_host_space_names_offending_byte() {
18050        // Embedded space in the `:entrada :host` axis surfaces the
18051        // byte-naming diagnostic through the lifted
18052        // `find_ascii_whitespace_byte` predicate. Peer with the
18053        // sibling `parse_rejects_leading_whitespace` pins on
18054        // `supervisor::duration_codec` (a7ae622) — same "the
18055        // diagnostic carries the offending byte's `0x{b:02x}` shape"
18056        // discipline extended from the shared duration codec to the
18057        // Gateway API v1 Hostname axis.
18058        let mut s = three_member_spec();
18059        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
18060        let err = s.validate().unwrap_err();
18061        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18062            panic!("expected EntradaHostInvalid, got {err:?}");
18063        };
18064        assert!(
18065            reason.contains("ASCII whitespace byte"),
18066            "expected byte-naming diagnostic, got {reason:?}"
18067        );
18068        assert!(
18069            reason.contains("0x20"),
18070            "expected offending space byte 0x20, got {reason:?}"
18071        );
18072    }
18073
18074    #[test]
18075    fn rejects_entrada_host_tab_names_offending_byte() {
18076        // Embedded tab byte in the `:entrada :host` axis — the
18077        // canonical paste-from-YAML-block-scalar / paste-from-
18078        // indented-doc footgun. Pins that the lifted predicate covers
18079        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
18080        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
18081        // not just the leading-space case the pre-lift `.bytes().any`
18082        // arm's opaque "must not contain whitespace" reason already
18083        // covered. Peer with `parse_rejects_tab_byte` on
18084        // `supervisor::duration_codec` (a7ae622).
18085        let mut s = three_member_spec();
18086        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
18087        let err = s.validate().unwrap_err();
18088        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18089            panic!("expected EntradaHostInvalid, got {err:?}");
18090        };
18091        assert!(
18092            reason.contains("ASCII whitespace byte"),
18093            "expected byte-naming diagnostic, got {reason:?}"
18094        );
18095        assert!(
18096            reason.contains("0x09"),
18097            "expected offending tab byte 0x09, got {reason:?}"
18098        );
18099    }
18100
18101    #[test]
18102    fn rejects_entrada_host_lf_names_offending_byte() {
18103        // Embedded LF byte in the `:entrada :host` axis — the
18104        // canonical paste-from-shell-heredoc / paste-from-multiline-
18105        // doc footgun the caixa-mesh YAML emitter would silently
18106        // reinterpret at the Gateway API v1 HTTPRoute admission
18107        // layer (an embedded LF byte in a YAML plain scalar either
18108        // truncates the value at the emitter or crashes the parser
18109        // on the k8s-apiserver side). Pins the third representative
18110        // of the full ASCII-whitespace set through the shared
18111        // predicate.
18112        let mut s = three_member_spec();
18113        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
18114        let err = s.validate().unwrap_err();
18115        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18116            panic!("expected EntradaHostInvalid, got {err:?}");
18117        };
18118        assert!(
18119            reason.contains("ASCII whitespace byte"),
18120            "expected byte-naming diagnostic, got {reason:?}"
18121        );
18122        assert!(
18123            reason.contains("0x0a"),
18124            "expected offending LF byte 0x0a, got {reason:?}"
18125        );
18126    }
18127
18128    #[test]
18129    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
18130        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
18131        // axis — the canonical paste-from-typography /
18132        // paste-from-word-processor footgun. Before the non-ASCII
18133        // Unicode `White_Space` scan lifted through the shared
18134        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
18135        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
18136        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
18137        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
18138        // with the far-from-source `label "…" must start and end
18139        // with an alphanumeric` diagnostic — burying the
18140        // paste-from-typography origin under a label-shape leak.
18141        // Peer with the sibling non-ASCII-whitespace pins at
18142        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
18143        // — 1b75b38), `limits::parse_duration`,
18144        // `limits::parse_millicores`, and the shared duration codec
18145        // — same "the diagnostic carries the offending Unicode
18146        // codepoint's `U+XXXX` shape" discipline extended from every
18147        // typed-magnitude codec to the Gateway API v1 Hostname axis.
18148        let mut s = three_member_spec();
18149        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
18150        let err = s.validate().unwrap_err();
18151        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18152            panic!("expected EntradaHostInvalid, got {err:?}");
18153        };
18154        assert!(
18155            reason.contains("non-ASCII Unicode whitespace character"),
18156            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
18157        );
18158        assert!(
18159            reason.contains("U+00A0"),
18160            "expected offending NBSP codepoint U+00A0, got {reason:?}"
18161        );
18162    }
18163
18164    #[test]
18165    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
18166        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
18167        // `:entrada :host` axis — the canonical paste-from-web-doc /
18168        // paste-from-published-HTML footgun. `char::is_whitespace`
18169        // returns true for `U+2028` per the Unicode `White_Space`
18170        // property, so `str::trim` at any downstream site would
18171        // silently strip it — same drift class as NBSP but on a
18172        // different codepoint region. Pins the second representative
18173        // (non-Latin-1 `char::is_whitespace` member) through the
18174        // shared predicate. Peer with
18175        // `parse_byte_size_rejects_internal_line_separator` on
18176        // `limits::parse_byte_size` (1b75b38).
18177        let mut s = three_member_spec();
18178        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
18179        let err = s.validate().unwrap_err();
18180        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18181            panic!("expected EntradaHostInvalid, got {err:?}");
18182        };
18183        assert!(
18184            reason.contains("non-ASCII Unicode whitespace character"),
18185            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
18186        );
18187        assert!(
18188            reason.contains("U+2028"),
18189            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
18190        );
18191    }
18192
18193    #[test]
18194    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
18195        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
18196        // labels in the `:entrada :host` axis — the canonical
18197        // paste-from-CJK-typography footgun (CJK IMEs default to
18198        // full-width whitespace when the space bar is pressed in
18199        // Japanese / Chinese input modes). Pins the third
18200        // representative of the non-ASCII Unicode `White_Space` set
18201        // through the shared predicate: the CJK block, distinct from
18202        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
18203        // SEPARATOR `U+2028` — covering the same axis breadth the
18204        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
18205        // (1b75b38) pins on `limits::parse_byte_size`.
18206        let mut s = three_member_spec();
18207        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
18208        let err = s.validate().unwrap_err();
18209        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
18210            panic!("expected EntradaHostInvalid, got {err:?}");
18211        };
18212        assert!(
18213            reason.contains("non-ASCII Unicode whitespace character"),
18214            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
18215        );
18216        assert!(
18217            reason.contains("U+3000"),
18218            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
18219        );
18220    }
18221
18222    #[test]
18223    fn rejects_entrada_host_too_long() {
18224        // Total length cap = 253; build a 254-byte host out of two
18225        // 63-byte labels + one 62-byte label + dots.
18226        let mut s = three_member_spec();
18227        let big = format!(
18228            "{}.{}.{}.{}",
18229            "a".repeat(63),
18230            "b".repeat(63),
18231            "c".repeat(63),
18232            "d".repeat(254 - 63 * 3 - 3)
18233        );
18234        assert_eq!(big.len(), 254);
18235        s.entrada.as_mut().unwrap().host = big;
18236        let err = s.validate().unwrap_err();
18237        assert!(
18238            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18239                if reason.contains("max length of 253")),
18240            "got {err:?}"
18241        );
18242    }
18243
18244    #[test]
18245    fn rejects_entrada_host_label_too_long() {
18246        let mut s = three_member_spec();
18247        // 64-byte label — one over the per-label cap.
18248        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
18249        let err = s.validate().unwrap_err();
18250        assert!(
18251            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
18252                if reason.contains("label max length of 63")),
18253            "got {err:?}"
18254        );
18255    }
18256
18257    #[test]
18258    fn entrada_host_diagnostic_carries_offending_host() {
18259        // Diagnostic-shape pin — the offending host + a non-empty
18260        // reason flow through verbatim so the author can grep their
18261        // caixa.lisp for `:host "<host>"` and fix it in one edit.
18262        let mut s = three_member_spec();
18263        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
18264        let err = s.validate().unwrap_err();
18265        match err {
18266            AplicacaoError::EntradaHostInvalid { host, reason } => {
18267                assert_eq!(host, "checkout.quero.cloud:8080");
18268                assert!(!reason.is_empty(), "reason field must be non-empty");
18269            }
18270            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18271        }
18272    }
18273
18274    // Equivalence pin for the [`AplicacaoError::entrada_host_invalid`]
18275    // substrate primitive that folds the fourteen
18276    // `AplicacaoError::EntradaHostInvalid { host: host.to_string(),
18277    // reason: <expr> }` wire-up sites at [`validate_entrada_host`] onto
18278    // one dispatch — peer with the sixteen equivalence pins the
18279    // [`crate::LayoutError`] `_violation` constructor family carries in
18280    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d). The
18281    // fixture host + reason are fixed `&'static str`s so both fields of
18282    // both constructed variants pin verbatim: the `host` axis is pinned
18283    // through the shared `host.to_string()` wrap (the ctor's uniform
18284    // one-slot construction) and the `reason` axis is pinned through
18285    // the shared `reason.into()` wrap (the ctor's `impl Into<String>`
18286    // routing). Any future regression on the lift (an extra field
18287    // introduced without updating the ctor, a diverging string
18288    // conversion at either arm) surfaces at this pin's diagnostic
18289    // rather than at a per-wire-up struct-literal reintroduction.
18290    #[test]
18291    fn entrada_host_invalid_ctor_matches_struct_literal_wrap() {
18292        let host = "checkout.quero.cloud:8080";
18293        let reason = "sample reason text";
18294        assert_eq!(
18295            AplicacaoError::entrada_host_invalid(host, reason),
18296            AplicacaoError::EntradaHostInvalid {
18297                host: host.to_string(),
18298                reason: reason.to_string(),
18299            },
18300            "generated constructor must produce byte-equal AplicacaoError to open-coded struct-literal wrap",
18301        );
18302    }
18303
18304    // Routing pin — the ctor's `host: &str` argument threads through
18305    // `.to_string()` verbatim on the `host` field, so the constructed
18306    // variant carries the offending host bytes without any wrapper-
18307    // side transformation (no `.to_ascii_lowercase()` normalization,
18308    // no `.trim()` strip, no truncation) — the same "diagnostic carries
18309    // the offending value verbatim so the author can grep their
18310    // caixa.lisp" discipline every peer typed-slot ctor at this
18311    // altitude carries.
18312    #[test]
18313    fn entrada_host_invalid_ctor_routes_host_through_to_string() {
18314        // Uppercase + trailing whitespace + port suffix — three
18315        // wrapper-side transformations the ctor must *not* apply.
18316        let host = " Checkout.quero.CLOUD:8080 ";
18317        let err = AplicacaoError::entrada_host_invalid(host, "sample");
18318        match err {
18319            AplicacaoError::EntradaHostInvalid { host: h, .. } => {
18320                assert_eq!(h, host, "host must thread through `.to_string()` verbatim");
18321            }
18322            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18323        }
18324    }
18325
18326    // Routing pin — the ctor's `reason: impl Into<String>` accepts both
18327    // `&str` literals and `format!(…)` outputs identically and both
18328    // route through `Into::into` verbatim onto the `reason` field.
18329    // Pins both codepaths against the same host to prove the two
18330    // shapes the fourteen wire-up sites use at their per-arm diagnostic
18331    // (ten `&str` literals — some with `.to_string()` at the caller,
18332    // some without — plus four `format!(…)` outputs) each produce
18333    // byte-equal `reason` fields against the same offending host.
18334    #[test]
18335    fn entrada_host_invalid_ctor_routes_reason_through_into() {
18336        let host = "checkout.quero.cloud";
18337        // `&str` literal — the ctor's `impl Into<String>` accepts it
18338        // without a caller-side `.to_string()`.
18339        let from_literal = AplicacaoError::entrada_host_invalid(host, "literal reason text");
18340        // Owned `String` from `format!` — the peer `format!(…)`-shaped
18341        // wire-up arm.
18342        let from_format =
18343            AplicacaoError::entrada_host_invalid(host, format!("{} reason text", "literal"));
18344        // `String` from `.to_string()` on a literal — the peer
18345        // `"literal".to_string()`-shaped wire-up arm the pre-lift
18346        // sites carried.
18347        let from_to_string =
18348            AplicacaoError::entrada_host_invalid(host, "literal reason text".to_string());
18349        match (&from_literal, &from_format, &from_to_string) {
18350            (
18351                AplicacaoError::EntradaHostInvalid {
18352                    reason: r_lit,
18353                    host: h_lit,
18354                },
18355                AplicacaoError::EntradaHostInvalid {
18356                    reason: r_fmt,
18357                    host: h_fmt,
18358                },
18359                AplicacaoError::EntradaHostInvalid {
18360                    reason: r_ts,
18361                    host: h_ts,
18362                },
18363            ) => {
18364                assert_eq!(r_lit, "literal reason text");
18365                assert_eq!(r_fmt, "literal reason text");
18366                assert_eq!(r_ts, "literal reason text");
18367                assert_eq!(h_lit, host);
18368                assert_eq!(h_fmt, host);
18369                assert_eq!(h_ts, host);
18370            }
18371            _ => panic!("expected three EntradaHostInvalid variants"),
18372        }
18373        // Cross-arm equivalence — the three shapes must produce
18374        // byte-equal `AplicacaoError` values, so the fourteen wire-up
18375        // sites' mixed per-arm shapes fold onto one canonical form.
18376        assert_eq!(from_literal, from_format);
18377        assert_eq!(from_literal, from_to_string);
18378    }
18379
18380    // Equivalence pins for the six sibling
18381    // [`aplicacao_field_reason_ctors!`]-generated constructors that
18382    // fold the peer `{ <field>: String, reason: String }` variants
18383    // onto the same substrate-primitive family
18384    // `entrada_host_invalid` (17dd504) already carries pins for.
18385    // Each ctor's fixture pair (a fixed `&'static str` value and a
18386    // fixed `&'static str` reason) pins both fields verbatim so any
18387    // future regression on the macro (an extra field introduced
18388    // without updating the macro, a diverging string conversion at
18389    // either arm, a field-name typo on one variant that dropped it
18390    // off the shared shape) surfaces at the affected variant's pin
18391    // rather than at a per-wire-up struct-literal reintroduction. Peer
18392    // discipline of the sixteen `LayoutError` _violation ctor pins in
18393    // `layout::tests::*_ctor_matches_struct_literal_wrap` (131ca0d)
18394    // and the paired
18395    // `contrato_wrong_target_ctor_matches_struct_literal_wrap` /
18396    // `contrato_missing_target_ctor_matches_struct_literal_wrap`
18397    // (14b81d5) / `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
18398    // (8580068) equivalence pins on the sibling `AplicacaoError`
18399    // ctor macros.
18400    #[test]
18401    fn membro_caixa_invalid_ctor_matches_struct_literal_wrap() {
18402        let caixa = "cart-svc";
18403        let reason = "sample reason text";
18404        assert_eq!(
18405            AplicacaoError::membro_caixa_invalid(caixa, reason),
18406            AplicacaoError::MembroCaixaInvalid {
18407                caixa: caixa.to_string(),
18408                reason: reason.to_string(),
18409            },
18410        );
18411    }
18412
18413    #[test]
18414    fn entrada_para_invalid_ctor_matches_struct_literal_wrap() {
18415        let para = "checkout";
18416        let reason = "sample reason text";
18417        assert_eq!(
18418            AplicacaoError::entrada_para_invalid(para, reason),
18419            AplicacaoError::EntradaParaInvalid {
18420                para: para.to_string(),
18421                reason: reason.to_string(),
18422            },
18423        );
18424    }
18425
18426    #[test]
18427    fn entrada_path_invalid_ctor_matches_struct_literal_wrap() {
18428        let path = "/api/cart";
18429        let reason = "sample reason text";
18430        assert_eq!(
18431            AplicacaoError::entrada_path_invalid(path, reason),
18432            AplicacaoError::EntradaPathInvalid {
18433                path: path.to_string(),
18434                reason: reason.to_string(),
18435            },
18436        );
18437    }
18438
18439    #[test]
18440    fn placement_cluster_invalid_ctor_matches_struct_literal_wrap() {
18441        let cluster = "rio";
18442        let reason = "sample reason text";
18443        assert_eq!(
18444            AplicacaoError::placement_cluster_invalid(cluster, reason),
18445            AplicacaoError::PlacementClusterInvalid {
18446                cluster: cluster.to_string(),
18447                reason: reason.to_string(),
18448            },
18449        );
18450    }
18451
18452    #[test]
18453    fn placement_affinity_invalid_ctor_matches_struct_literal_wrap() {
18454        let affinity = "data-locality";
18455        let reason = "sample reason text";
18456        assert_eq!(
18457            AplicacaoError::placement_affinity_invalid(affinity, reason),
18458            AplicacaoError::PlacementAffinityInvalid {
18459                affinity: affinity.to_string(),
18460                reason: reason.to_string(),
18461            },
18462        );
18463    }
18464
18465    #[test]
18466    fn shard_key_invalid_ctor_matches_struct_literal_wrap() {
18467        let shard_key = "tenantId";
18468        let reason = "sample reason text";
18469        assert_eq!(
18470            AplicacaoError::shard_key_invalid(shard_key, reason),
18471            AplicacaoError::ShardKeyInvalid {
18472                shard_key: shard_key.to_string(),
18473                reason: reason.to_string(),
18474            },
18475        );
18476    }
18477
18478    // Pin the three-slot per-`:contratos <slot>` sibling of the
18479    // two-slot `aplicacao_field_reason_ctors!` family — the sole
18480    // per-axis ctor carrying the extra `slot: &'static str` axis-tag
18481    // distinguishing the two-arm `:de` / `:para` cascade. Sweeps both
18482    // canonical author-side slot tags through the ctor and asserts
18483    // byte-equality against the pre-lift struct-literal shape so no
18484    // per-arm wrapper transformation drifts in against the sole
18485    // in-crate wire-up.
18486    #[test]
18487    fn contrato_caixa_invalid_ctor_matches_struct_literal_wrap() {
18488        let caixa = "cart-svc";
18489        let reason = "sample reason text";
18490        for slot in [
18491            crate::render::CONTRATO_AUTHOR_KEY_DE,
18492            crate::render::CONTRATO_AUTHOR_KEY_PARA,
18493        ] {
18494            assert_eq!(
18495                AplicacaoError::contrato_caixa_invalid(slot, caixa, reason),
18496                AplicacaoError::ContratoCaixaInvalid {
18497                    slot,
18498                    caixa: caixa.to_string(),
18499                    reason: reason.to_string(),
18500                },
18501            );
18502        }
18503    }
18504
18505    // The `reason: impl Into<String>` bound accepts both a `&str`
18506    // literal and a `format!(…)` owned-`String` output verbatim,
18507    // matching the peer `aplicacao_field_reason_ctors!` family's
18508    // reason-axis invariance so the sole in-crate wire-up's
18509    // `require_valid_dns_1123_label`-delivered owned-`String` return
18510    // and any future `&str` literal caller land on the same variant.
18511    #[test]
18512    fn contrato_caixa_invalid_ctor_routes_reason_through_into_uniformly() {
18513        let via_literal = "literal reason text";
18514        let via_format = format!("{} reason text", "literal");
18515        for slot in [
18516            crate::render::CONTRATO_AUTHOR_KEY_DE,
18517            crate::render::CONTRATO_AUTHOR_KEY_PARA,
18518        ] {
18519            assert_eq!(
18520                AplicacaoError::contrato_caixa_invalid(slot, "c", via_literal),
18521                AplicacaoError::contrato_caixa_invalid(slot, "c", via_format.clone()),
18522            );
18523        }
18524    }
18525
18526    // Pin the paired one-slot empty-arm sibling of the three-slot
18527    // `contrato_caixa_invalid` per-`:contratos <slot>` ctor — the sole
18528    // closure-form empty-arm on the shared
18529    // [`crate::render::require_valid_dns_1123_label`] two-closure
18530    // cascade at [`validate_contrato_caixa`], carrying the same
18531    // `slot: &'static str` axis-tag that distinguishes the two-arm
18532    // `:de` / `:para` cascade. Sweeps both canonical author-side slot
18533    // tags through the ctor and asserts byte-equality against the
18534    // pre-lift struct-literal shape so no per-arm wrapper transformation
18535    // drifts in against the sole in-crate wire-up. Peer of the sibling
18536    // [`crate::behavior::BehaviorError::empty_path`] one-slot
18537    // `{ slot: &'static str }` equivalence pin on the paired
18538    // `BehaviorError` envelope's four-arm sandboxed-lisp-path cascade
18539    // ([`crate::render::require_sandboxed_lisp_path`]) — extended here
18540    // onto the sibling `AplicacaoError` envelope's two-arm
18541    // DNS-1123-label cascade so both empty-arm axes carry a
18542    // substrate-primitive equivalence pin rather than the pre-lift
18543    // hand-open struct-literal.
18544    #[test]
18545    fn contrato_caixa_empty_ctor_matches_struct_literal_wrap() {
18546        for slot in [
18547            crate::render::CONTRATO_AUTHOR_KEY_DE,
18548            crate::render::CONTRATO_AUTHOR_KEY_PARA,
18549        ] {
18550            assert_eq!(
18551                AplicacaoError::contrato_caixa_empty(slot),
18552                AplicacaoError::ContratoCaixaEmpty { slot },
18553                "generated contrato_caixa_empty ctor must produce \
18554                 byte-equal AplicacaoError to the open-coded \
18555                 struct-literal wrap on the same &'static str fixture \
18556                 (slot = {slot:?})",
18557            );
18558        }
18559    }
18560
18561    // Cross-axis pin: sweep the constructor's single input axis (`slot:
18562    // &'static str`) through every canonical
18563    // [`crate::render::CONTRATO_AUTHOR_KEY_*`] tag *plus* a non-canonical
18564    // `&'static str` value (`":phantom"`), so any wrapper-side lowercase
18565    // / trim / truncate / re-order / fixed-slot substitution on the
18566    // one-field construction surfaces here rather than at a downstream
18567    // diagnostic-shape mismatch. The non-canonical arm proves the
18568    // constructor does not silently clamp `slot` to the `:de` /
18569    // `:para` roster (a future third `:contratos <slot>` axis lands on
18570    // this ctor without a per-arm rewrite), matching the discipline the
18571    // sibling [`Self::contrato_caixa_invalid`] ctor's tri-slot sweep
18572    // establishes at
18573    // `contrato_caixa_invalid_ctor_matches_struct_literal_wrap`
18574    // (18114) on the paired three-slot invalid-arm envelope.
18575    #[test]
18576    fn contrato_caixa_empty_ctor_routes_slot_verbatim_across_both_axes() {
18577        for slot in [
18578            crate::render::CONTRATO_AUTHOR_KEY_DE,
18579            crate::render::CONTRATO_AUTHOR_KEY_PARA,
18580            ":phantom",
18581        ] {
18582            assert_eq!(
18583                AplicacaoError::contrato_caixa_empty(slot),
18584                AplicacaoError::ContratoCaixaEmpty { slot },
18585            );
18586        }
18587    }
18588
18589    // End-to-end wire-up pin: `AplicacaoSpec::validate` on an empty
18590    // `:contratos :de` value must surface a diagnostic byte-equal to
18591    // the substrate primitive `AplicacaoError::contrato_caixa_empty`'s
18592    // output on the same slot fixture. Proves the sole in-crate
18593    // closure-form wire-up inside [`validate_contrato_caixa`]'s
18594    // [`crate::render::require_valid_dns_1123_label`] empty-arm routes
18595    // through the ctor rather than the pre-lift open-coded
18596    // struct-literal block, matching the sibling per-arm
18597    // `end_to_end_wire_up_routes_through_ctor` discipline the peer
18598    // per-envelope ctor pins the recent
18599    // [`Self::policy_rate_limit_cannot_admit_retry_burst`] (9703bd6),
18600    // [`Self::policy_breaker_trips_before_retries_exhausted`] (f54c539),
18601    // [`Self::policy_breaker_cannot_trip_under_rate_limit`] (6bb4e46),
18602    // and [`Self::policy_breaker_window_below_timeout`] (9b30c07)
18603    // cross-axis Policy* variants carry. Complements the two axis-tag
18604    // arms already pinned above the `:contratos` value-shape gate
18605    // block (`rejects_contrato_de_empty`, `rejects_contrato_para_empty`)
18606    // which anchor via the shape; this pin additionally verifies the
18607    // ctor is the exclusive construction path.
18608    #[test]
18609    fn contrato_caixa_empty_end_to_end_wire_up_routes_through_ctor() {
18610        // Empty `:de` — the sole in-crate wire-up hits the empty-arm
18611        // closure at the first `:contratos` value-shape gate, threading
18612        // the `CONTRATO_AUTHOR_KEY_DE` label through the ctor.
18613        let mut s_de = three_member_spec();
18614        s_de.contratos.push(contract_http("", "catalog", "/x"));
18615        assert_eq!(
18616            s_de.validate().unwrap_err(),
18617            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_DE),
18618        );
18619        // Symmetric arm: an empty `:para` on a valid `:de` fires the
18620        // same closure with the `CONTRATO_AUTHOR_KEY_PARA` label.
18621        let mut s_para = three_member_spec();
18622        s_para.contratos.push(contract_http("cart", "", "/x"));
18623        assert_eq!(
18624            s_para.validate().unwrap_err(),
18625            AplicacaoError::contrato_caixa_empty(crate::render::CONTRATO_AUTHOR_KEY_PARA),
18626        );
18627    }
18628
18629    // Cross-family invariance pin — the six sibling ctors and
18630    // `entrada_host_invalid` all route `reason: impl Into<String>` +
18631    // `<field>: &str` verbatim onto their respective typed variants
18632    // through the shared [`aplicacao_field_reason_ctors!`] macro.
18633    // Sweeps a fixture pair (`&str` literal, `format!` output) against
18634    // every ctor to pin that no per-arm wrapper transformation drifted
18635    // in against the uniform macro-generated body.
18636    #[test]
18637    fn aplicacao_field_reason_ctors_route_reason_through_into_uniformly() {
18638        let via_literal = "literal reason text";
18639        let via_format = format!("{} reason text", "literal");
18640        assert_eq!(
18641            AplicacaoError::membro_caixa_invalid("m", via_literal),
18642            AplicacaoError::membro_caixa_invalid("m", via_format.clone()),
18643        );
18644        assert_eq!(
18645            AplicacaoError::entrada_para_invalid("p", via_literal),
18646            AplicacaoError::entrada_para_invalid("p", via_format.clone()),
18647        );
18648        assert_eq!(
18649            AplicacaoError::entrada_path_invalid("/a", via_literal),
18650            AplicacaoError::entrada_path_invalid("/a", via_format.clone()),
18651        );
18652        assert_eq!(
18653            AplicacaoError::placement_cluster_invalid("c", via_literal),
18654            AplicacaoError::placement_cluster_invalid("c", via_format.clone()),
18655        );
18656        assert_eq!(
18657            AplicacaoError::placement_affinity_invalid("a", via_literal),
18658            AplicacaoError::placement_affinity_invalid("a", via_format.clone()),
18659        );
18660        assert_eq!(
18661            AplicacaoError::shard_key_invalid("k", via_literal),
18662            AplicacaoError::shard_key_invalid("k", via_format.clone()),
18663        );
18664        assert_eq!(
18665            AplicacaoError::entrada_host_invalid("h", via_literal),
18666            AplicacaoError::entrada_host_invalid("h", via_format),
18667        );
18668    }
18669
18670    #[test]
18671    fn entrada_host_empty_takes_precedence_over_invalid() {
18672        // Ordering pin: `EmptyEntradaHost` is the more self-locating
18673        // diagnostic on `""` and must lead — `validate_entrada_host`
18674        // is only reached after the empty-check fires at the call
18675        // site. (The predicate itself defends against direct
18676        // invocation by returning the same error on `""`.)
18677        let mut s = three_member_spec();
18678        s.entrada.as_mut().unwrap().host = String::new();
18679        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
18680    }
18681
18682    #[test]
18683    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
18684        // Ordering pin: a missing :para member is the more
18685        // self-locating diagnostic and fires before the host gate.
18686        let mut s = three_member_spec();
18687        let e = s.entrada.as_mut().unwrap();
18688        e.para = "ghost".into();
18689        e.host = "BAD HOST".into();
18690        let err = s.validate().unwrap_err();
18691        assert!(
18692            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
18693            "got {err:?}"
18694        );
18695    }
18696
18697    #[test]
18698    fn entrada_host_invalid_fires_before_port_zero() {
18699        // Ordering pin: the host gate fires before the port gate so
18700        // a malformed host is named even when the port is also wrong.
18701        let mut s = three_member_spec();
18702        let e = s.entrada.as_mut().unwrap();
18703        e.host = "Checkout.quero.cloud".into();
18704        e.port = 0;
18705        let err = s.validate().unwrap_err();
18706        assert!(
18707            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
18708                if host == "Checkout.quero.cloud"),
18709            "got {err:?}"
18710        );
18711    }
18712
18713    #[test]
18714    fn entrada_accepts_canonical_hosts() {
18715        // Positive-control sweep — every form the Gateway API
18716        // apiserver accepts must round-trip through validate. Covers
18717        // a plain DNS subdomain, a leading wildcard, a single-label
18718        // host (cluster-internal), a max-length-edge label, a
18719        // hyphen-bearing label, and a Punycode IDN label.
18720        for host in [
18721            "checkout.quero.cloud",
18722            "*.quero.cloud",
18723            "checkout",
18724            // 63-byte label — exactly the per-label cap.
18725            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
18726            "foo-bar.quero.cloud",
18727            // Punycode IDN — valid because the author pre-encoded.
18728            "xn--bcher-kva.example.com",
18729        ] {
18730            let mut s = three_member_spec();
18731            s.entrada.as_mut().unwrap().host = host.into();
18732            s.validate()
18733                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
18734        }
18735    }
18736
18737    #[test]
18738    fn entrada_host_max_length_validates() {
18739        // 253-byte host is the cap exactly — must validate. Build a
18740        // 253-byte host out of three 63-byte labels + one 61-byte
18741        // label + 3 dots = 252 bytes, then pad one byte to 253.
18742        let mut s = three_member_spec();
18743        let host = format!(
18744            "{}.{}.{}.{}",
18745            "a".repeat(63),
18746            "b".repeat(63),
18747            "c".repeat(63),
18748            "d".repeat(253 - 63 * 3 - 3)
18749        );
18750        assert_eq!(host.len(), 253);
18751        s.entrada.as_mut().unwrap().host = host;
18752        s.validate().unwrap();
18753    }
18754
18755    #[test]
18756    fn entrada_host_total_length_cap_threads_lifted_render_const() {
18757        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
18758        // total-length gate now reads the K8s Gateway API v1 Hostname
18759        // `maxLength: 253` cap from the lifted
18760        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
18761        // of truth — the same constant every future Gateway-API-Hostname
18762        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
18763        // materializer's per-host validator, the future per-`Certificate`
18764        // SAN emitter for cert-manager, the multi-`:entrada`
18765        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
18766        // from. Before the lift, the aplicacao-side reader consumed a
18767        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
18768        // 253-byte value as the peer render-side canonical bounds
18769        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
18770        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
18771        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
18772        // module boundary — a future 253-byte drift on either side would
18773        // silently split into two axes' worth of admission-schema mismatch
18774        // without a build-time signal. Pin the cap through a fresh 254-
18775        // byte host that hits the total-length arm, then read the reason
18776        // for the exact byte count the shared constant carries: any future
18777        // regression on the lift (a private alias reintroduced, a hard-
18778        // coded literal at the arm, a mismatch between the aplicacao-side
18779        // and render-side canonicals) surfaces as this pin's diagnostic
18780        // failing to match, not as a per-cluster admission rejection far
18781        // from the caixa.lisp source line.
18782        let mut s = three_member_spec();
18783        let over_cap = format!(
18784            "{}.{}.{}.{}",
18785            "a".repeat(63),
18786            "b".repeat(63),
18787            "c".repeat(63),
18788            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
18789        );
18790        assert_eq!(
18791            over_cap.len(),
18792            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
18793        );
18794        s.entrada.as_mut().unwrap().host = over_cap;
18795        let err = s.validate().unwrap_err();
18796        match err {
18797            AplicacaoError::EntradaHostInvalid { reason, .. } => {
18798                let needle = format!(
18799                    "max length of {} bytes",
18800                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
18801                );
18802                assert!(
18803                    reason.contains(&needle),
18804                    "diagnostic must name the lifted \
18805                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
18806                );
18807            }
18808            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18809        }
18810    }
18811
18812    #[test]
18813    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
18814        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
18815        // on the per-label-cap axis. Before the lift, the aplicacao-side
18816        // per-label arm consumed a private const alias
18817        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
18818        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
18819        // split from it at the module boundary — every `.`-separated
18820        // label in a Gateway API v1 Hostname is a DNS-1123 label under
18821        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
18822        // so the private alias's 63 and the canonical const's 63 were
18823        // pinning the same underlying rule twice. Pin the cap through a
18824        // 64-byte label that hits the per-label arm, then read the reason
18825        // for the exact byte count the shared constant carries: any
18826        // future drift on either side (a private alias reintroduced, a
18827        // hard-coded literal at the arm, a mismatch between the two
18828        // 63-byte pins) surfaces at this pin's diagnostic rather than at
18829        // a per-cluster admission rejection whose "field is invalid"
18830        // opacity misframes the root cause.
18831        let mut s = three_member_spec();
18832        let over_cap_label = format!(
18833            "{}.quero.cloud",
18834            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
18835        );
18836        s.entrada.as_mut().unwrap().host = over_cap_label;
18837        let err = s.validate().unwrap_err();
18838        match err {
18839            AplicacaoError::EntradaHostInvalid { reason, .. } => {
18840                let needle = format!(
18841                    "label max length of {} bytes",
18842                    crate::render::DNS_1123_LABEL_MAX_LEN,
18843                );
18844                assert!(
18845                    reason.contains(&needle),
18846                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
18847                     cap verbatim on the per-label arm, got: {reason:?}",
18848                );
18849            }
18850            other => panic!("expected EntradaHostInvalid, got {other:?}"),
18851        }
18852    }
18853
18854    #[test]
18855    fn entrada_with_empty_paths_validates() {
18856        // Empty `:paths` is the documented "match every path" form;
18857        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
18858        let mut s = three_member_spec();
18859        s.entrada.as_mut().unwrap().paths = vec![];
18860        s.validate().unwrap();
18861    }
18862
18863    #[test]
18864    fn entrada_root_path_validates() {
18865        // The author-supplied bare-root `:entrada :paths` entry is the
18866        // same byte-shape the peer emit-side catch-all constant
18867        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
18868        // the author's `:paths` list is empty — sweeping the test-side
18869        // probe literal onto the lifted const closes the two-axis pin
18870        // (author-side admit + emit-side canonical fallback) around
18871        // one `&'static str`, so a future rebrand of the catch-all
18872        // reaches both consumers by construction. Peer to
18873        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
18874        // on the canonical-literal pin surface.
18875        let mut s = three_member_spec();
18876        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
18877        s.validate().unwrap();
18878    }
18879
18880    #[test]
18881    fn placement_strategy_variants_round_trip() {
18882        for s in [
18883            PlacementStrategy::SingleNode,
18884            PlacementStrategy::Replicated,
18885            PlacementStrategy::Sharded,
18886        ] {
18887            let p = Placement {
18888                estrategia: s,
18889                clusters: vec!["rio".into()],
18890                affinity: None,
18891                // Route the paired `:shard-key` fixture-builder through the
18892                // typed cross-slot invariant predicate
18893                // [`PlacementStrategy::requires_shard_key`] rather than the
18894                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
18895                // arm-identity predicate — the two answer the same
18896                // question under today's closed accept-set but a future
18897                // arm addition that consumed `:shard-key` under a
18898                // non-`Sharded` name would silently mis-attach the
18899                // fixture's `:shard-key` if the builder read through the
18900                // arm-identity predicate. The cross-slot-invariant
18901                // predicate migrates through one caixa-core edit on any
18902                // future arm addition; the fixture keeps producing a
18903                // `validate()`-passing round-trip by construction.
18904                shard_key: if s.requires_shard_key() {
18905                    Some("$key".into())
18906                } else {
18907                    None
18908                },
18909            };
18910            let json = serde_json::to_string(&p).unwrap();
18911            let back: Placement = serde_json::from_str(&json).unwrap();
18912            assert_eq!(back, p);
18913        }
18914    }
18915
18916    #[test]
18917    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
18918        // The fail-before-pass-after pin: pre-lift there was no
18919        // single-source binding between the [`PlacementStrategy`]
18920        // variant name the `Serialize` derive emits and the byte-
18921        // string every downstream cluster-side dispatcher (the
18922        // `lareira-fleet-programs` aggregator's per-entry strategy
18923        // branch, the future `app-operator` reconciler, the M3
18924        // Adaptive compression pass's per-strategy weighting) probes
18925        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
18926        // future `#[serde(rename_all = "kebab-case")]` attribute on
18927        // the enum — or a variant rename in the source — would
18928        // silently rebrand the emitted scalar under one spelling
18929        // while every downstream dispatcher still probed the other,
18930        // with the failure surfacing at the aggregator's dispatch
18931        // step or the operator's reconcile posture (workloads coming
18932        // up under the `default()` `Replicated` arm rather than the
18933        // typed slot's declared strategy) far from the source
18934        // rebrand commit and with no field naming the drift. Pinning
18935        // the two paths (the `Serialize` derive's serialized string
18936        // AND the [`PlacementStrategy::as_str`] helper) to the same
18937        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
18938        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
18939        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
18940        // makes any future drift on either endpoint fail here at
18941        // caixa-core build time.
18942        for (variant, expected) in [
18943            (
18944                PlacementStrategy::SingleNode,
18945                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
18946            ),
18947            (
18948                PlacementStrategy::Replicated,
18949                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
18950            ),
18951            (
18952                PlacementStrategy::Sharded,
18953                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
18954            ),
18955        ] {
18956            let json = serde_json::to_string(&variant).unwrap();
18957            assert_eq!(
18958                json,
18959                format!("\"{expected}\""),
18960                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
18961            );
18962            assert_eq!(
18963                variant.as_str(),
18964                expected,
18965                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
18966                 M3_PLACEMENT_ESTRATEGIA_* constant"
18967            );
18968        }
18969    }
18970
18971    #[test]
18972    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
18973        // Cross-arm drift-detection pin on the M3
18974        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
18975        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
18976        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
18977        // scalar-value pentad: a future collapse of two canonical
18978        // variant byte-strings onto the same value (an accidental
18979        // copy-paste flip of
18980        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
18981        // read `"SingleNode"`, a per-arm rebrand that lands one const
18982        // without touching its paired peer) would silently reroute
18983        // every downstream operator's per-strategy dispatch onto the
18984        // sibling arm's reconcile branch and pass every
18985        // propagation-probe test that expected only the stale arm's
18986        // value — a `Replicated`-declared Aplicacao would come up
18987        // under the `SingleNode` primary-and-standby reconcile
18988        // posture, so every-cluster active-active workload would
18989        // silently collapse onto one-cluster-runs-at-a-time takeover
18990        // semantics against its declared strategy, with no field
18991        // naming the strategy-value drift root cause. Peer of the
18992        // sibling
18993        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
18994        // (09ffb2d) /
18995        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
18996        // (ccdf955) /
18997        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
18998        // (d739850) distinctness pins on the sibling OTP-shape /
18999        // caixa-kind closed-set typed-enum discriminator axes — the
19000        // fourth (and structurally the M3 mesh-primitive-defining)
19001        // closed-set typed-enum axis to converge on the same
19002        // "pairwise-distinct-by-construction" discipline.
19003        //
19004        // Fail-before-pass-after locally verified by mutating
19005        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
19006        // also read `"SingleNode"` — this pin fires as expected;
19007        // restoring passes.
19008        let all = [
19009            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19010            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19011            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
19012        ];
19013        for (i, a) in all.iter().enumerate() {
19014            for (j, b) in all.iter().enumerate() {
19015                if i != j {
19016                    assert_ne!(
19017                        a, b,
19018                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
19019                         distinct — got duplicate {a:?} at indices {i} and {j}",
19020                    );
19021                }
19022            }
19023        }
19024    }
19025
19026    #[test]
19027    fn placement_strategy_display_routes_through_as_str_helper() {
19028        // The fail-before-pass-after pin: pre-lift the sibling
19029        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
19030        // / [`crate::supervisor::RestartPolicy`] both carried a stable
19031        // [`std::fmt::Display`] surface via their
19032        // `#[discriminant(also_display)]` gen-platform derive, but
19033        // [`PlacementStrategy`] did not — every consumer reaching for
19034        // a strategy byte-string past the wire format had to pick
19035        // between three paths ([`PlacementStrategy::as_str`], the
19036        // `Serialize` derive's serialized string, or `format!("{v:?}")`
19037        // on the `Debug` derive), any two of which a future variant
19038        // rename or `#[serde(rename_all = "kebab-case")]` attribute
19039        // would silently desynchronize. Wiring [`std::fmt::Display`]
19040        // through [`PlacementStrategy::as_str`] closes the third path:
19041        // every `format!("{v}")` call reaches the same lifted
19042        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
19043        // and the [`PlacementStrategy::as_str`] helper already route
19044        // through, so a future variant rename lands at exactly one
19045        // place. Pin the routing here so a future
19046        // `impl std::fmt::Display for PlacementStrategy` reimplementation
19047        // that hand-rolls the arms instead of delegating to
19048        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
19049        for variant in [
19050            PlacementStrategy::SingleNode,
19051            PlacementStrategy::Replicated,
19052            PlacementStrategy::Sharded,
19053        ] {
19054            assert_eq!(
19055                variant.to_string(),
19056                variant.as_str(),
19057                "PlacementStrategy::{variant:?} Display must route through \
19058                 PlacementStrategy::as_str (single source of truth: the lifted \
19059                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
19060            );
19061        }
19062    }
19063
19064    #[test]
19065    fn placement_strategy_display_matches_serialized_wire_byte_string() {
19066        // The fail-before-pass-after pin on the second half of the
19067        // three-path convergence: `Display` (user-facing text) agrees
19068        // byte-for-byte with the `Serialize` derive's wire format
19069        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
19070        // scalar) on every variant. Pre-lift the two paths were
19071        // structurally independent — a future
19072        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
19073        // would silently rebrand the emitted wire scalar
19074        // (`single-node`, `replicated`, `sharded`) while every consumer
19075        // that pretty-prints the strategy (the M3 diagnostic templates,
19076        // the future `feira app graph` per-Aplicacao strategy line,
19077        // the future M4 CR materializer's admission-webhook rejection
19078        // body) would still emit the TitleCase form the `as_str` /
19079        // `Display` route returns, with the mismatch surfacing at
19080        // consumer parse time / operator dispatch time far from the
19081        // source rebrand commit. Pin the two paths byte-for-byte here
19082        // so any future serde-attribute or variant-rename drift is a
19083        // caixa-core-build-time test failure at this call, not a
19084        // silent per-consumer dispatch miss.
19085        for variant in [
19086            PlacementStrategy::SingleNode,
19087            PlacementStrategy::Replicated,
19088            PlacementStrategy::Sharded,
19089        ] {
19090            let wire = serde_json::to_string(&variant).unwrap();
19091            // Strip the outer `"…"` the JSON string form carries — the
19092            // wire scalar the K8s / YAML apiserver consumes is the
19093            // enclosed byte-string, not the quote wrapper.
19094            let unquoted = wire
19095                .strip_prefix('"')
19096                .and_then(|s| s.strip_suffix('"'))
19097                .expect("serialized PlacementStrategy is a JSON string");
19098            assert_eq!(
19099                variant.to_string(),
19100                unquoted,
19101                "PlacementStrategy::{variant:?} Display byte-string must match the \
19102                 Serialize derive's wire byte-string (three-path convergence: \
19103                 Display + as_str + Serialize all resolve to the same \
19104                 M3_PLACEMENT_ESTRATEGIA_* const)"
19105            );
19106        }
19107    }
19108
19109    #[test]
19110    fn placement_strategy_as_ref_str_routes_through_as_str_accessor() {
19111        // Fail-before-pass-after byte-parity pin on the lifted
19112        // `impl AsRef<str> for PlacementStrategy` — asserts the
19113        // standard-library trait impl and the substrate-primitive
19114        // [`PlacementStrategy::as_str`] `pub const fn` accessor resolve
19115        // to the same `&str` per instance across the three-arm closed
19116        // set, so any future silent detour that routes the impl through
19117        // a divergent projection (a per-arm inline
19118        // `match self { PlacementStrategy::Sharded => "Sharded", … }`
19119        // re-inlining that opens a compile-time link to the un-lifted
19120        // arm-literal, a swap onto the kebab-case
19121        // [`gen_platform::Discriminant`] catalog identity that would
19122        // collide the wire axis with the dispatcher-catalog axis) trips
19123        // at caixa-core test time under `PartialEq` rather than at a
19124        // downstream `impl AsRef<str>`-bound consumer's silent split.
19125        // Sweeps every one of the three arms [`PlacementStrategy::ALL`]
19126        // carries so no arm's projection is covered only by the sibling
19127        // wire-format `Serialize` derive path. Peer of the sibling
19128        // [`crate::supervisor::tests::restart_policy_as_ref_str_routes_through_as_str_accessor`]
19129        // (419ea81) / `restart_strategy_as_ref_str_routes_through_as_str_accessor`
19130        // (63eb1a4) on the paired M2 per-supervisor closed-set typed
19131        // enums, and the [`crate::version::tests::caixa_version_as_ref_str_routes_through_as_str_accessor`]
19132        // (16d5c7e) pin on the paired top-level `:versao` typed newtype
19133        // — the four pins together close the substrate primitive's
19134        // `AsRef<str>` projection axis on every closed-set typed enum
19135        // /newtype on the M2/M3 mesh + supervision + version surface.
19136        for &variant in PlacementStrategy::ALL {
19137            assert_eq!(
19138                <PlacementStrategy as AsRef<str>>::as_ref(&variant),
19139                variant.as_str(),
19140                "AsRef<str> impl on PlacementStrategy::{variant:?} must \
19141                 byte-equal PlacementStrategy::as_str on the same instance \
19142                 — divergence signals a silent detour off the substrate-\
19143                 primitive accessor"
19144            );
19145        }
19146    }
19147
19148    #[test]
19149    fn placement_strategy_as_ref_str_routes_through_display_via_shared_accessor() {
19150        // Fail-before-pass-after byte-parity pin on the three-path
19151        // convergence discipline the M3 per-Aplicacao distribution-
19152        // strategy primitive now carries on the `&str`-projection axis:
19153        // `<PlacementStrategy as AsRef<str>>::as_ref(&v)` (the newly
19154        // lifted impl), `format!("{v}")` (the pre-existing
19155        // [`fmt::Display`] impl), and `v.as_str()` (the substrate-
19156        // primitive `pub const fn` accessor both trait impls delegate
19157        // through) must resolve to the same byte-string on every
19158        // instance across the three-arm closed set. Refuses any future
19159        // divergence between the two trait impls (a stray
19160        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms rather
19161        // than delegating through the shared accessor; a hypothetical
19162        // `AsRef<str>` rewrite that inlines a per-arm literal cascade)
19163        // that would silently split the two projection paths of the
19164        // same closed-set typed enum. Mirrors the sibling three-path-
19165        // convergence discipline the peer
19166        // [`crate::supervisor::RestartPolicy`] typed enum carries on its
19167        // `AsRef<str>` / `Display` / `as_str` triple (supervisor.rs pin
19168        // `restart_policy_as_ref_str_routes_through_display_via_shared_accessor`,
19169        // 419ea81), the peer [`crate::supervisor::RestartStrategy`]
19170        // triple (supervisor.rs pin
19171        // `restart_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
19172        // 63eb1a4), and the [`crate::CaixaVersion`] typed newtype
19173        // triple (version.rs pin
19174        // `caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
19175        // 16d5c7e).
19176        for &variant in PlacementStrategy::ALL {
19177            let via_as_ref: &str = <PlacementStrategy as AsRef<str>>::as_ref(&variant);
19178            let via_display: String = format!("{variant}");
19179            let via_accessor: &str = variant.as_str();
19180            assert_eq!(via_as_ref, via_accessor);
19181            assert_eq!(via_display, via_accessor);
19182            assert_eq!(via_as_ref, via_display.as_str());
19183        }
19184    }
19185
19186    #[test]
19187    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
19188        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
19189        // derive on [`PlacementStrategy`]: for each of the three variants
19190        // exactly one of the generated `is_single_node` / `is_replicated`
19191        // / `is_sharded` predicates returns `true` and the other two
19192        // return `false`. Prior to this derive the three per-arm
19193        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
19194        // (the `placement_strategy_variants_round_trip` fixture, the
19195        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
19196        // fixture, and the
19197        // `validate_placement_reads_through_lifted_estrategia_accessor`
19198        // fixture) each open-coded a per-arm PartialEq compare against
19199        // the enum variant — three sites that expressed no compile-time
19200        // link back to the closed-set typed dispatch a future fourth
19201        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
19202        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
19203        // would have to thread through in lockstep or one fixture would
19204        // silently disagree with the others on which arms consume the
19205        // `:shard-key` axis. Peer of the sibling
19206        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
19207        // / [`crate::supervisor::RestartPolicy`] /
19208        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
19209        // the sibling closed-set typed-enum discriminator axes — extends
19210        // the same one-typed-dispatch-per-variant discipline onto the
19211        // fifth (and only remaining) closed-set typed-enum discriminator
19212        // on the caixa surface, closing the axis on the M3 mesh-slot
19213        // family.
19214        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
19215            (PlacementStrategy::SingleNode, [true, false, false]),
19216            (PlacementStrategy::Replicated, [false, true, false]),
19217            (PlacementStrategy::Sharded, [false, false, true]),
19218        ];
19219        for (variant, expected) in rows {
19220            let observed = [
19221                variant.is_single_node(),
19222                variant.is_replicated(),
19223                variant.is_sharded(),
19224            ];
19225            assert_eq!(
19226                observed, expected,
19227                "PlacementStrategy::{variant:?} is_* predicates must partition \
19228                 the arm set (single_node, replicated, sharded); got {observed:?}"
19229            );
19230        }
19231    }
19232
19233    #[test]
19234    fn placement_strategy_is_variant_predicates_are_const_fn() {
19235        // The [`gen_platform::IsVariant`] derive emits `const fn`
19236        // predicates on the peer [`crate::CaixaKind`] +
19237        // [`crate::upgrade::UpgradeInstruction`] +
19238        // [`crate::supervisor::RestartStrategy`] +
19239        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
19240        // pin the same posture on [`PlacementStrategy`] so a future
19241        // accidental downgrade to non-`const` (an added runtime helper
19242        // reachable only from a non-`const` context, a manual hand-rolled
19243        // `impl` that shadows the derive-generated method) trips at
19244        // caixa-core build time rather than surfacing as a downstream
19245        // `const`-context regression far from the derive declaration.
19246        //
19247        // The pin lives inside a `const { assert!(..) }` block so the
19248        // compiler enforces both halves (arm predicate is `const`-
19249        // callable AND returns `true` for the matching arm) at
19250        // caixa-core compile time — peer to the sibling
19251        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
19252        // pins on the closed-set typed enum arm-predicate const-
19253        // callability axis.
19254        const {
19255            assert!(PlacementStrategy::SingleNode.is_single_node());
19256            assert!(PlacementStrategy::Replicated.is_replicated());
19257            assert!(PlacementStrategy::Sharded.is_sharded());
19258        }
19259    }
19260
19261    #[test]
19262    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
19263        // Fail-before-pass-after pin on the substrate-lifted
19264        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
19265        // per-arm predicate: for each variant in the closed accept-set the
19266        // predicate returns `true` iff the variant consumes the paired
19267        // [`Placement::shard_key`] axis under
19268        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
19269        // partition. Today the accept-set is the singleton `{Sharded}` —
19270        // `Sharded` is the Akka-style hash-keyed distribution arm
19271        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
19272        // §II.1) and `Replicated` (active-active) refuse the axis through
19273        // [`AplicacaoError::ShardKeyOnNonSharded`].
19274        //
19275        // Pins the per-arm truth-table so a future arm addition (an
19276        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
19277        // roadmap names, a `WeightedShard` promotion the future M5
19278        // adaptive-placement engine acknowledges) that landed a variant
19279        // without extending this predicate's arm-set would surface as a
19280        // caixa-core build-time exhaustiveness error at the
19281        // `match self { … }` arm-fan below rather than a silent per-consumer
19282        // mis-classification at renderer emit time. The paired
19283        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
19284        // predicate stays a distinct question — arm-identity (which the
19285        // sibling
19286        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
19287        // pin already locks) is not cross-slot-invariant consumption; today
19288        // they trip on the same singleton but the pair migrates through
19289        // one caixa-core edit on any future arm addition.
19290        //
19291        // Peer of the sibling per-arm classifier pins
19292        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
19293        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
19294        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
19295        // derived paired predicate on the post-projection typed-view axis
19296        // — same "per-arm semantic-classification predicate paired with
19297        // the arm-identity predicate the derive already emits" discipline
19298        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
19299        // `:placement :shard-key` cross-slot-invariant axis.
19300        let rows: [(PlacementStrategy, bool); 3] = [
19301            (PlacementStrategy::SingleNode, false),
19302            (PlacementStrategy::Replicated, false),
19303            (PlacementStrategy::Sharded, true),
19304        ];
19305        for (variant, expected) in rows {
19306            assert_eq!(
19307                variant.requires_shard_key(),
19308                expected,
19309                "PlacementStrategy::{variant:?}.requires_shard_key() must \
19310                 be {expected} (the substrate-canonical cross-slot invariant \
19311                 on the :placement :shard-key axis; today `Sharded` is the \
19312                 singleton consuming arm — MESH-COMPOSITION §II.4)",
19313            );
19314        }
19315    }
19316
19317    #[test]
19318    fn placement_strategy_requires_shard_key_is_const_fn() {
19319        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
19320        // invariant per-arm predicate is declared `#[must_use] pub const
19321        // fn` — pin the `const`-eval posture here so a future accidental
19322        // downgrade to non-`const` (an added runtime helper reachable
19323        // only from a non-`const` context, a manual hand-rolled `impl`
19324        // that shadows the current three-arm `match self { … }` dispatch)
19325        // trips at caixa-core build time rather than surfacing as a
19326        // downstream `const`-context regression far from the declaration.
19327        // Same shape as the sibling
19328        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
19329        // the peer [`gen_platform::IsVariant`]-derived arm-identity
19330        // predicate axis, but here the load-bearing assertions live in
19331        // module-scope `const _: () = assert!(…)` items so a violation
19332        // fails at compile time (const-eval trip) rather than test time —
19333        // strictly stronger than the runtime `assert!(CONST)` pattern the
19334        // sibling pin uses, and side-steps the
19335        // `clippy::assertions_on_constants` lint the runtime pattern
19336        // otherwise accumulates on the module baseline.
19337        //
19338        // The test body simply witnesses that the module-scope items
19339        // compiled and the runtime dispatch agrees with the const-eval
19340        // dispatch on every arm — the runtime read gives the test a
19341        // failure surface (rather than an empty test body clippy would
19342        // flag as a no-op).
19343        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
19344        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
19345        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
19346        assert_eq!(
19347            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
19348            [
19349                PlacementStrategy::SingleNode.requires_shard_key(),
19350                PlacementStrategy::Replicated.requires_shard_key(),
19351                PlacementStrategy::Sharded.requires_shard_key(),
19352            ],
19353            "runtime and const-eval dispatch on \
19354             PlacementStrategy::requires_shard_key must agree on every arm",
19355        );
19356    }
19357
19358    #[test]
19359    fn placement_estrategia_accessor_is_const_fn() {
19360        // The [`Placement::estrategia`] per-`:placement` distribution-
19361        // strategy `Copy`-return scalar accessor is declared
19362        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
19363        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
19364        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
19365        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
19366        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
19367        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
19368        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
19369        // [`RateLimit`], every one a `pub const fn`). Pin the
19370        // `const`-eval posture here so a future accidental downgrade to
19371        // non-`const` (an added runtime helper reachable only from a
19372        // non-`const` context, a slot promotion to a non-`Copy` return
19373        // that would silently drop the `const` qualifier, a manual
19374        // hand-rolled shadow) trips at caixa-core build time rather
19375        // than surfacing as a downstream `const`-context regression far
19376        // from the declaration.
19377        //
19378        // Same shape as the sibling
19379        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
19380        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
19381        // predicate axis — the load-bearing witness lives in the
19382        // module-scope `const fn` wrapper `estrategia_via_const_fn`
19383        // below: a body that calls [`Placement::estrategia`] under a
19384        // `const fn` signature is well-formed only when the callee is
19385        // itself `const fn`, so any future accidental downgrade of
19386        // [`Placement::estrategia`] to non-`const` fails at caixa-core
19387        // build time (const-eval E0015 / E0658 depending on the arm),
19388        // strictly stronger than a runtime `assert!(CONST)` and
19389        // side-stepping the destructor-in-const restriction that
19390        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
19391        // items on `Placement`'s `Vec<String>` / `Option<String>`
19392        // carriers.
19393        //
19394        // The runtime body witnesses that the const-eval-shaped
19395        // wrapper agrees with a direct call on every closed-set arm.
19396        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
19397            p.estrategia()
19398        }
19399        for estrategia in [
19400            PlacementStrategy::SingleNode,
19401            PlacementStrategy::Replicated,
19402            PlacementStrategy::Sharded,
19403        ] {
19404            let placement = Placement {
19405                estrategia,
19406                clusters: Vec::new(),
19407                affinity: None,
19408                shard_key: None,
19409            };
19410            assert_eq!(
19411                estrategia_via_const_fn(&placement),
19412                placement.estrategia(),
19413                "const-fn-wrapped and direct dispatch on \
19414                 Placement::estrategia must agree for {estrategia:?}",
19415            );
19416        }
19417    }
19418
19419    #[test]
19420    fn entrada_port_accessor_is_const_fn() {
19421        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
19422        // scalar accessor is declared `#[must_use] pub const fn` —
19423        // matching the peer M3 mesh-slot `Copy`-return accessor family
19424        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
19425        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
19426        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
19427        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
19428        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
19429        // [`RateLimit::window`] on the sibling [`RateLimit`], the
19430        // sibling per-`:placement` [`Placement::estrategia`] pinned by
19431        // [`placement_estrategia_accessor_is_const_fn`] above — every
19432        // one a `pub const fn`). Pin the `const`-eval posture here so
19433        // a future accidental downgrade to non-`const` (an added
19434        // runtime helper reachable only from a non-`const` context, an
19435        // `Option<u16>`-shape migration once the substrate grows
19436        // per-`:membros` heterogeneous listener ports that would
19437        // silently drop the `const` qualifier, a manual hand-rolled
19438        // shadow) trips at caixa-core build time rather than surfacing
19439        // as a downstream `const`-context regression far from the
19440        // declaration.
19441        //
19442        // Same shape as the sibling
19443        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
19444        // load-bearing witness lives in the module-scope `const fn`
19445        // wrapper `port_via_const_fn`: a body that calls
19446        // [`Entrada::port`] under a `const fn` signature is well-formed
19447        // only when the callee is itself `const fn`, side-stepping the
19448        // destructor-in-const restriction that would otherwise block a
19449        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
19450        // `String` / `Vec<String>` carriers.
19451        //
19452        // The runtime body sweeps a representative port set spanning
19453        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
19454        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
19455        // ceiling — the const-fn-wrapped call must agree with a direct
19456        // call on every fixture (a violation trips the test) and every
19457        // returned scalar must byte-equal the input `port` (a violation
19458        // means the accessor stopped being a raw field-return copy).
19459        const fn port_via_const_fn(e: &Entrada) -> u16 {
19460            e.port()
19461        }
19462        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
19463            let entrada = Entrada {
19464                host: String::new(),
19465                para: String::new(),
19466                port,
19467                paths: Vec::new(),
19468            };
19469            assert_eq!(
19470                port_via_const_fn(&entrada),
19471                entrada.port(),
19472                "const-fn-wrapped and direct dispatch on Entrada::port \
19473                 must agree for port={port}",
19474            );
19475            assert_eq!(
19476                entrada.port(),
19477                port,
19478                "Entrada::port must return the storage-side u16 verbatim \
19479                 for port={port}",
19480            );
19481        }
19482    }
19483
19484    #[test]
19485    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
19486        // Load-bearing cross-slot-partition pin closing the loop between
19487        // the substrate-lifted
19488        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
19489        // the closed-set typed enum and the actual
19490        // [`AplicacaoSpec::validate_placement`] runtime behavior across
19491        // the paired `:placement :shard-key` axis: every validated
19492        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
19493        // satisfies `placement.shard_key().is_some() ==
19494        // placement.estrategia().requires_shard_key()`. The four-cell
19495        // shape witness sweeps every combination of (variant in the
19496        // closed accept-set, `:shard-key` Some/None) and pins:
19497        //
19498        //   * variant.requires_shard_key() && shard_key.is_some() →
19499        //     validate() passes; the paired shape is the sole
19500        //     `requires_shard_key` arm-family accepted shape.
19501        //   * variant.requires_shard_key() && shard_key.is_none() →
19502        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
19503        //     the paired shape is the refused missing-key shape on
19504        //     Sharded-family arms.
19505        //   * !variant.requires_shard_key() && shard_key.is_some() →
19506        //     validate() fails with
19507        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
19508        //     is the refused declared-but-inert shape on non-Sharded-
19509        //     family arms.
19510        //   * !variant.requires_shard_key() && shard_key.is_none() →
19511        //     validate() passes; the paired shape is the sole
19512        //     non-`requires_shard_key` arm-family accepted shape.
19513        //
19514        // The compile-time-exhaustive `match p.estrategia()` dispatch at
19515        // [`AplicacaoSpec::validate_placement`] preserves its structural
19516        // arm-fan (a future arm addition still surfaces a build-time
19517        // exhaustiveness error there); this pin closes the semantic loop
19518        // between the arm-fan's shape-gate cascades and the substrate-
19519        // canonical predicate every downstream consumer of the paired
19520        // shape reads through. Fail-before-pass-after locally verified by
19521        // mutating the predicate's `Sharded => true` arm to `false` — the
19522        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
19523        // `validate() must pass` assertion; restoring passes. Same "close
19524        // the loop between the typed predicate and the runtime behavior"
19525        // discipline as the sibling
19526        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
19527        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
19528        // per-arm classifier axis.
19529        for variant in [
19530            PlacementStrategy::SingleNode,
19531            PlacementStrategy::Replicated,
19532            PlacementStrategy::Sharded,
19533        ] {
19534            for present in [false, true] {
19535                let mut spec = three_member_spec();
19536                spec.placement.estrategia = variant;
19537                spec.placement.shard_key = present.then(|| "tenantId".into());
19538                let expects_ok = variant.requires_shard_key() == present;
19539                let result = spec.validate();
19540                match (expects_ok, &result) {
19541                    (true, Ok(())) => {}
19542                    (false, Err(err)) => {
19543                        // Cross-check the refusal diagnostic names the
19544                        // right cell of the four-cell shape witness — the
19545                        // `requires_shard_key && !present` cell must trip
19546                        // [`AplicacaoError::ShardedWithoutKey`]; the
19547                        // `!requires_shard_key && present` cell must trip
19548                        // [`AplicacaoError::ShardKeyOnNonSharded`].
19549                        match (variant.requires_shard_key(), present, err) {
19550                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
19551                            (
19552                                false,
19553                                true,
19554                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
19555                            ) => {
19556                                assert_eq!(
19557                                    *e, variant,
19558                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
19559                                     the paired PlacementStrategy",
19560                                );
19561                            }
19562                            _ => panic!(
19563                                "unexpected refusal for estrategia={variant:?} \
19564                                 present={present}: {err:?}"
19565                            ),
19566                        }
19567                    }
19568                    (true, Err(err)) => panic!(
19569                        "validate() must pass for estrategia={variant:?} \
19570                         present={present} (requires_shard_key={} == present={present}), \
19571                         got {err:?}",
19572                        variant.requires_shard_key(),
19573                    ),
19574                    (false, Ok(())) => panic!(
19575                        "validate() must fail for estrategia={variant:?} \
19576                         present={present} (requires_shard_key={} != present={present})",
19577                        variant.requires_shard_key(),
19578                    ),
19579                }
19580            }
19581        }
19582    }
19583
19584    #[test]
19585    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
19586        // Pin the M3 diagnostic template routes through the typed
19587        // [`PlacementStrategy`] Display byte-string (rebound from the
19588        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
19589        // routes emitted identical bytes (the `Debug` derive on a
19590        // unit variant emits the variant name verbatim, exactly what
19591        // `as_str` returns), but the two paths were structurally
19592        // independent — a future `#[serde(rename_all = "…")]`
19593        // attribute or variant rename would coordinate the wire /
19594        // `Display` / `as_str` triple through the lifted const but
19595        // leave the `Debug` route on the compiler-derived variant name,
19596        // silently desynchronizing the diagnostic byte-string from the
19597        // wire byte-string. Rebinding the template onto `Display`
19598        // ties the diagnostic to the same lifted
19599        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
19600        // emits — drift becomes structurally impossible. Pin the
19601        // byte-string here so a future edit that reverts the template
19602        // to `{estrategia:?}` is caught at caixa-core test time, not
19603        // at consumer dispatch time.
19604        for (variant, expected_scalar) in [
19605            (
19606                PlacementStrategy::SingleNode,
19607                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19608            ),
19609            (
19610                PlacementStrategy::Replicated,
19611                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19612            ),
19613            (
19614                PlacementStrategy::Sharded,
19615                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
19616            ),
19617        ] {
19618            let err = AplicacaoError::PlacementWithoutClusters {
19619                estrategia: variant,
19620            };
19621            let msg = err.to_string();
19622            assert!(
19623                msg.starts_with(&format!(":placement {expected_scalar} requires")),
19624                "PlacementWithoutClusters diagnostic for {variant:?} must open \
19625                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
19626            );
19627        }
19628    }
19629
19630    #[test]
19631    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
19632        // Peer of
19633        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
19634        // on the second M3 diagnostic that carries the typed
19635        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
19636        // diagnostics now route the strategy scalar through the same
19637        // [`std::fmt::Display`] surface, tying the diagnostic
19638        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
19639        // const set the wire format also emits. The two non-Sharded
19640        // arms are exercised here (the diagnostic exists to flag a
19641        // `:shard-key` slot the current strategy will never consume);
19642        // the peer `Sharded` arm never reaches this diagnostic (the
19643        // `Sharded` strategy consumes `:shard-key` — the
19644        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
19645        // slot instead).
19646        for (variant, expected_scalar) in [
19647            (
19648                PlacementStrategy::SingleNode,
19649                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19650            ),
19651            (
19652                PlacementStrategy::Replicated,
19653                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19654            ),
19655        ] {
19656            let err = AplicacaoError::ShardKeyOnNonSharded {
19657                estrategia: variant,
19658                shard_key: "$tenantId".into(),
19659            };
19660            let msg = err.to_string();
19661            assert!(
19662                msg.starts_with(&format!(":placement {expected_scalar} carries")),
19663                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
19664                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
19665            );
19666        }
19667    }
19668
19669    #[test]
19670    fn placement_strategy_all_enumerates_every_variant_once() {
19671        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
19672        // exhaustive-iteration surface: every variant appears exactly
19673        // once, and the slice length matches the arm count of the
19674        // closed set. Every consumer that walks the accepted-strategy
19675        // set (a future `feira app placement --list` CLI-side surfacing,
19676        // a future M4 admission-webhook's rejection body naming the
19677        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
19678        // reverse-projection consumers that iterate the accept-set for
19679        // a "did you mean" hint) reads through this slice, so a future
19680        // variant addition (an `Anycast` mesh-anycast arm the
19681        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
19682        // grows the enum but forgets to grow [`Self::ALL`] silently
19683        // truncates every downstream consumer's accept-set at the same
19684        // pre-addition boundary — this pin fails at caixa-core build
19685        // time on the pairwise-distinct + arm-count invariants.
19686        //
19687        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
19688        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
19689        // pins on the peer closed-set typed-enum axes.
19690        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
19691        assert_eq!(
19692            all.len(),
19693            3,
19694            "PlacementStrategy::ALL must enumerate every variant of the \
19695             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
19696        );
19697        for (i, a) in all.iter().enumerate() {
19698            for (j, b) in all.iter().enumerate() {
19699                if i != j {
19700                    assert_ne!(
19701                        a, b,
19702                        "PlacementStrategy::ALL must carry every variant exactly \
19703                         once — got duplicate {a:?} at indices {i} and {j}"
19704                    );
19705                }
19706            }
19707        }
19708        for variant in [
19709            PlacementStrategy::SingleNode,
19710            PlacementStrategy::Replicated,
19711            PlacementStrategy::Sharded,
19712        ] {
19713            assert!(
19714                all.contains(&variant),
19715                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
19716                 addition that grows the enum but forgets to grow the ALL slice \
19717                 silently truncates every downstream consumer's accept-set at the \
19718                 pre-addition boundary"
19719            );
19720        }
19721    }
19722
19723    #[test]
19724    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
19725        // Fail-before-pass-after pin on the forward accept-set of the
19726        // [`PlacementStrategy::from_wire`] reverse projection: every
19727        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
19728        // constant the [`PlacementStrategy::as_str`] emitter walks
19729        // parses back to its paired variant. Any future arm addition
19730        // that grows the emitter's `as_str` match but forgets to grow
19731        // the parser's `from_str` match silently splits the two halves
19732        // of the round-trip — the wire byte-string one non-serde
19733        // consumer parses from the one the emitter wrote — with the
19734        // failure surfacing at parse time far from the rebrand commit.
19735        // Pinning the three-arm accept-set here catches the drift at
19736        // caixa-core build time.
19737        //
19738        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
19739        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
19740        // closed-set typed-enum `str → Self` axes.
19741        for (wire, expected) in [
19742            (
19743                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
19744                PlacementStrategy::SingleNode,
19745            ),
19746            (
19747                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
19748                PlacementStrategy::Replicated,
19749            ),
19750            (
19751                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
19752                PlacementStrategy::Sharded,
19753            ),
19754        ] {
19755            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
19756                panic!(
19757                    "PlacementStrategy::from_wire({wire:?}) must accept every \
19758                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
19759                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
19760                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
19761                )
19762            });
19763            assert_eq!(
19764                parsed, expected,
19765                "PlacementStrategy::from_wire({wire:?}) must return \
19766                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
19767            );
19768        }
19769    }
19770
19771    #[test]
19772    fn placement_strategy_from_wire_round_trips_through_as_str() {
19773        // Fail-before-pass-after pin on the closed round-trip between
19774        // the forward [`PlacementStrategy::as_str`] emitter and the
19775        // reverse [`PlacementStrategy::from_wire`] parser: for every
19776        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
19777        // output must return exactly the same variant. Any per-arm
19778        // divergence — a future arm added to `as_str` but not
19779        // `from_str`, an accidental copy-paste flip in one but not the
19780        // other — silently splits the emit and parse halves and the
19781        // failure surfaces at consumer parse time far from the drift
19782        // site. The `ALL`-iterating shape means a future variant
19783        // addition picks up the coverage by construction.
19784        //
19785        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
19786        // [`crate::CaixaKind::from_wire`] and the
19787        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
19788        // sibling round-trip pin on [`RateLimitUnit`].
19789        for &variant in PlacementStrategy::ALL {
19790            let wire = variant.as_str();
19791            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
19792                panic!(
19793                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
19794                     must be Some({variant:?}) — the two halves of the round-trip \
19795                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
19796                     got None on wire byte-string {wire:?}"
19797                )
19798            });
19799            assert_eq!(
19800                parsed, variant,
19801                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
19802                 must round-trip to the same variant; got {parsed:?}"
19803            );
19804        }
19805    }
19806
19807    #[test]
19808    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
19809        // Fail-before-pass-after pin on the closed-set refusal
19810        // discipline of [`PlacementStrategy::from_wire`]: every
19811        // byte-string outside the three-arm accept-set returns `None`
19812        // rather than silently collapsing onto the [`Default`]
19813        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
19814        // exercised here sweeps the load-bearing drift shapes: the
19815        // empty string (a stripped serde-attribute drift), an all-
19816        // whitespace string (the canonical text-editor accidental
19817        // padding shape), the lowercased kebab-case forms a future
19818        // `#[serde(rename_all = "kebab-case")]` attribute would emit
19819        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
19820        // coincidentally match the accepted canonical scalars, so only
19821        // `"single-node"` fires as a refusal, but pinning the case-
19822        // sensitivity of the accepted arms via the peer [`SingleNode`]
19823        // assertion in the round-trip pin makes the discipline
19824        // structurally clear), the lowercased single-word forms
19825        // (`"singlenode"`), the padded canonical scalar
19826        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
19827        // (`"Sharded\n"`), and a pointer-different `&'static str` that
19828        // happens to alias a canonical byte-string by content but not
19829        // by identity (validated implicitly by the emitter's routing
19830        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
19831        // identity a paired [`crate::assert_str_reexport_identity`] pin
19832        // in caixa-core's per-const declaration surface would catch).
19833        //
19834        // Peer of the sibling
19835        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
19836        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
19837        for bad in [
19838            "",
19839            " ",
19840            "\n",
19841            "\t",
19842            "single-node",
19843            "singlenode",
19844            "SingleNodes",
19845            "single_node",
19846            "single node",
19847            "SINGLENODE",
19848            "SingleNode ",
19849            " SingleNode",
19850            " Sharded ",
19851            "Sharded\n",
19852            "replicated ",
19853            "sharded",
19854            "REPLICATED",
19855            "Anycast",
19856            "Global",
19857            "?",
19858        ] {
19859            assert!(
19860                PlacementStrategy::from_wire(bad).is_none(),
19861                "PlacementStrategy::from_wire({bad:?}) must return None — the \
19862                 parser's accept-set is exactly the three PlacementStrategy::as_str \
19863                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
19864                 is outside that closed set"
19865            );
19866        }
19867    }
19868
19869    #[test]
19870    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
19871        // Fail-before-pass-after pin on the third path of the four-path
19872        // convergence: `from_str` (the reverse projection) inverts the
19873        // `Serialize` derive's wire byte-string on every variant.
19874        // Together with the pre-existing three-path convergence
19875        // (`Display` + `as_str` + `Serialize` all resolve to the same
19876        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
19877        // the peer
19878        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
19879        // this closes the round-trip: the wire byte-string the
19880        // `Serialize` derive emits parses back to the same variant
19881        // through `from_str`, so any future serde-attribute or variant-
19882        // rename drift on the emit half now surfaces as a matched drift
19883        // on the parse half at caixa-core build time — the two halves
19884        // migrate as a unit through the lifted consts on any future
19885        // rename, and the round-trip cannot silently split.
19886        //
19887        // Peer of the sibling
19888        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
19889        // wire-format pin — extends the three-path convergence
19890        // (`Display` + `as_str` + `Serialize`) onto the fourth path
19891        // (`from_str`), closing the `str ↔ Self` round-trip on the
19892        // M3 `:placement :estrategia` closed-set axis.
19893        for &variant in PlacementStrategy::ALL {
19894            let wire = serde_json::to_string(&variant).unwrap();
19895            let unquoted = wire
19896                .strip_prefix('"')
19897                .and_then(|s| s.strip_suffix('"'))
19898                .expect("serialized PlacementStrategy is a JSON string");
19899            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
19900                panic!(
19901                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
19902                     Serialize derive's wire byte-string for \
19903                     PlacementStrategy::{variant:?} — the four-path convergence \
19904                     (Display + as_str + Serialize + from_str) resolves through \
19905                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
19906                )
19907            });
19908            assert_eq!(
19909                parsed, variant,
19910                "PlacementStrategy::from_wire of the Serialize derive's wire \
19911                 byte-string for PlacementStrategy::{variant:?} must round-trip \
19912                 to the same variant; got {parsed:?}"
19913            );
19914        }
19915    }
19916
19917    #[test]
19918    fn rejects_zero_policy_timeout() {
19919        let mut s = three_member_spec();
19920        s.politicas.timeout = Some(Duration::ZERO);
19921        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
19922    }
19923
19924    #[test]
19925    fn rejects_zero_policy_retries() {
19926        let mut s = three_member_spec();
19927        s.politicas.retries = Some(0);
19928        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
19929    }
19930
19931    #[test]
19932    fn rejects_policy_retries_above_cap() {
19933        // The fail-before-pass-after pin: `Some(11)` is structurally
19934        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
19935        // passed validate on every pre-gate codebase because the
19936        // typed slot's only check was the zero-floor arm. The
19937        // thundering-herd amplification vector only surfaced at the
19938        // runtime substrate (Envoy / Cilium L7 retry overlay)
19939        // far from the source caixa.lisp with no field naming the
19940        // offending policy.
19941        let mut s = three_member_spec();
19942        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
19943        assert_eq!(
19944            s.validate().unwrap_err(),
19945            AplicacaoError::PolicyRetriesExceedsCap {
19946                retries: POLICY_RETRIES_MAX + 1
19947            }
19948        );
19949    }
19950
19951    #[test]
19952    fn rejects_policy_retries_far_above_cap() {
19953        // The `u32::MAX` worst case — the four-billion-retry policy
19954        // a typo (`(:retries 4294967295)`) or struct-literal
19955        // copy-paste lands in the slot. Pin the cap arm's coverage
19956        // explicitly across the full `u32` overflow so a future
19957        // relaxation that drops the upper bound surfaces here.
19958        let mut s = three_member_spec();
19959        s.politicas.retries = Some(u32::MAX);
19960        assert_eq!(
19961            s.validate().unwrap_err(),
19962            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
19963        );
19964    }
19965
19966    #[test]
19967    fn accepts_policy_retries_at_cap() {
19968        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
19969        // must validate. The cap is inclusive on the top edge,
19970        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
19971        // discipline on the sibling [`crate::LimitsSpec::memory`]
19972        // axis. Pin the boundary explicitly so a future off-by-one
19973        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
19974        // surfaces here as a test failure rather than a silent
19975        // contract narrowing.
19976        let mut s = three_member_spec();
19977        s.politicas.retries = Some(POLICY_RETRIES_MAX);
19978        s.validate()
19979            .expect("retries == POLICY_RETRIES_MAX must validate");
19980    }
19981
19982    #[test]
19983    fn accepts_policy_retries_typical_values() {
19984        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
19985        // every value in the validated set must pass. The
19986        // Envoy / Istio production-playbook recommendation band
19987        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
19988        // (`maxRetries ≤ 10`) both lie within this set.
19989        for r in 1..=POLICY_RETRIES_MAX {
19990            let mut s = three_member_spec();
19991            s.politicas.retries = Some(r);
19992            s.validate()
19993                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
19994        }
19995    }
19996
19997    #[test]
19998    fn policy_retries_zero_takes_precedence_over_cap() {
19999        // The cross-arm ordering pin: `Some(0)` is structurally
20000        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
20001        // (cap), but the zero-floor diagnostic is the more
20002        // self-locating one (it directly names the omit-axis
20003        // remediation), so the validate gate must fire on zero
20004        // first. Pin the order so a future refactor that reorders
20005        // the arms surfaces here as a test failure rather than a
20006        // silent diagnostic regression. Same shape every other
20007        // zero-then-shape ordering on this surface uses
20008        // ([`AplicacaoError::PolicyTimeoutZero`] then
20009        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
20010        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
20011        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
20012        let mut s = three_member_spec();
20013        s.politicas.retries = Some(0);
20014        assert_eq!(
20015            s.validate().unwrap_err(),
20016            AplicacaoError::PolicyRetriesZero,
20017            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
20018        );
20019    }
20020
20021    #[test]
20022    fn policy_retries_cap_diagnostic_carries_offending_value() {
20023        // The diagnostic-shape pin: the offending `u32` is carried
20024        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
20025        // variant so the surfaced error message names the value the
20026        // author wrote (`":politicas :retries (47) exceeds the
20027        // mesh-policy ceiling …"`), not just the cap. Same
20028        // self-locating diagnostic shape every other typed-cap arm
20029        // on this surface carries
20030        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
20031        // offending byte count verbatim).
20032        let mut s = three_member_spec();
20033        s.politicas.retries = Some(47);
20034        let err = s.validate().unwrap_err();
20035        assert!(
20036            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
20037            "got {err:?}"
20038        );
20039        let msg = err.to_string();
20040        assert!(
20041            msg.contains("47"),
20042            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
20043        );
20044    }
20045
20046    #[test]
20047    fn policy_retries_cap_is_aws_app_mesh_aligned() {
20048        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
20049        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
20050        // schema cap — the only upstream mesh-policy schema that
20051        // documents an explicit hard cap. Pinning the literal value
20052        // here surfaces a future drift (a relaxation to 20, a
20053        // tightening to 5) as a deliberate test edit, not a silent
20054        // contract narrowing.
20055        assert_eq!(POLICY_RETRIES_MAX, 10);
20056    }
20057
20058    #[test]
20059    fn rejects_circuit_breaker_zero_max_failures() {
20060        let mut s = three_member_spec();
20061        s.politicas.circuit_breaker = Some(CircuitBreaker {
20062            max_failures: 0,
20063            window: Duration::from_secs(60),
20064        });
20065        assert_eq!(
20066            s.validate().unwrap_err(),
20067            AplicacaoError::PolicyBreakerZeroFailures
20068        );
20069    }
20070
20071    #[test]
20072    fn rejects_circuit_breaker_max_failures_above_cap() {
20073        // The fail-before-pass-after pin: `1001` is structurally one
20074        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
20075        // silently passed validate on every pre-gate codebase
20076        // because the typed slot's only check was the zero-floor
20077        // arm. The breaker-no-op vector only surfaced at the runtime
20078        // substrate (Envoy / Cilium L7 outlier-detection overlay)
20079        // far from the source caixa.lisp with no field naming the
20080        // offending policy.
20081        let mut s = three_member_spec();
20082        s.politicas.circuit_breaker = Some(CircuitBreaker {
20083            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20084            window: Duration::from_secs(60),
20085        });
20086        assert_eq!(
20087            s.validate().unwrap_err(),
20088            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20089                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20090            }
20091        );
20092    }
20093
20094    #[test]
20095    fn rejects_circuit_breaker_max_failures_far_above_cap() {
20096        // The `u32::MAX` worst case — the four-billion-failure
20097        // threshold a typo (`(:max-failures 4294967295)`) or a
20098        // struct-literal copy-paste lands in the slot. Pin the cap
20099        // arm's coverage explicitly across the full `u32` overflow
20100        // so a future relaxation that drops the upper bound surfaces
20101        // here.
20102        let mut s = three_member_spec();
20103        s.politicas.circuit_breaker = Some(CircuitBreaker {
20104            max_failures: u32::MAX,
20105            window: Duration::from_secs(60),
20106        });
20107        assert_eq!(
20108            s.validate().unwrap_err(),
20109            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20110                max_failures: u32::MAX,
20111            }
20112        );
20113    }
20114
20115    #[test]
20116    fn accepts_circuit_breaker_max_failures_at_cap() {
20117        // The boundary value — exactly
20118        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
20119        // cap is inclusive on the top edge, matching the
20120        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
20121        // discipline on the sibling capped axes. Pin the boundary
20122        // explicitly so a future off-by-one tightening
20123        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
20124        // surfaces here as a test failure rather than a silent
20125        // contract narrowing.
20126        let mut s = three_member_spec();
20127        s.politicas.circuit_breaker = Some(CircuitBreaker {
20128            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
20129            window: Duration::from_secs(60),
20130        });
20131        s.validate()
20132            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
20133    }
20134
20135    #[test]
20136    fn accepts_circuit_breaker_max_failures_typical_values() {
20137        // The documented production-playbook band positive-control
20138        // sweep — every value Hystrix / Istio / Envoy / Polly /
20139        // Resilience4j recommend (5..=50) must pass, plus a sweep
20140        // through the hyperscale band (100, 500, 1000) the cap
20141        // accepts. Pin the inclusive validated set explicitly so a
20142        // future tightening of the ceiling surfaces here.
20143        //
20144        // Clears the fixture's `:retries` (which is `Some(3)`) so this
20145        // per-axis sweep is pure: the sibling cross-axis
20146        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
20147        // gate rejects any `max_failures <= retries` pair, so the
20148        // `max_failures = 1` boundary at the head of the sweep would
20149        // otherwise trip on the fixture-inherited retry policy rather
20150        // than the per-axis boundary this test names. Same discipline
20151        // the sibling per-axis `accepts_circuit_breaker_window_*`
20152        // sweeps take against the fixture's `:timeout` for the
20153        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`]
20154        // cross-axis arm.
20155        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
20156            let mut s = three_member_spec();
20157            s.politicas.retries = None;
20158            s.politicas.circuit_breaker = Some(CircuitBreaker {
20159                max_failures: n,
20160                window: Duration::from_secs(60),
20161            });
20162            s.validate()
20163                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
20164        }
20165    }
20166
20167    #[test]
20168    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
20169        // The cross-arm ordering pin: `0` is structurally outside
20170        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
20171        // (cap), but the zero-floor diagnostic is the more
20172        // self-locating one (it directly names the omit-axis
20173        // remediation), so the validate gate must fire on zero
20174        // first. Same shape every other zero-then-shape ordering on
20175        // this surface uses
20176        // ([`AplicacaoError::PolicyRetriesZero`] then
20177        // [`AplicacaoError::PolicyRetriesExceedsCap`];
20178        // [`AplicacaoError::PolicyTimeoutZero`] then
20179        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
20180        let mut s = three_member_spec();
20181        s.politicas.circuit_breaker = Some(CircuitBreaker {
20182            max_failures: 0,
20183            window: Duration::from_secs(60),
20184        });
20185        assert_eq!(
20186            s.validate().unwrap_err(),
20187            AplicacaoError::PolicyBreakerZeroFailures,
20188            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
20189        );
20190    }
20191
20192    #[test]
20193    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
20194        // The cross-arm ordering pin between the cap and the
20195        // sibling `:window` gates (zero-window, canonical-window).
20196        // A breaker carrying both an over-cap `max_failures` AND a
20197        // structurally invalid window (zero, sub-ms) must surface
20198        // the cap diagnostic first — the cap arm is wired
20199        // immediately after the zero-failure arm and strictly
20200        // before the window arms, so the offending value the
20201        // diagnostic names matches the order the author would
20202        // discover the gates by reading top-to-bottom through
20203        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
20204        // future refactor that reorders the arms surfaces here as a
20205        // test failure rather than a silent diagnostic regression.
20206        let mut s = three_member_spec();
20207        s.politicas.circuit_breaker = Some(CircuitBreaker {
20208            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20209            window: Duration::ZERO,
20210        });
20211        assert_eq!(
20212            s.validate().unwrap_err(),
20213            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20214                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
20215            },
20216            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
20217        );
20218    }
20219
20220    #[test]
20221    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
20222        // The diagnostic-shape pin: the offending `u32` is carried
20223        // verbatim into the
20224        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
20225        // variant so the surfaced error message names the value the
20226        // author wrote (`":politicas :circuit-breaker :max-failures
20227        // (50000) exceeds the mesh-policy ceiling …"`), not just
20228        // the cap. Same self-locating diagnostic shape every other
20229        // typed-cap arm on this surface carries
20230        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
20231        // offending retry count verbatim,
20232        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
20233        // offending byte count verbatim).
20234        let mut s = three_member_spec();
20235        s.politicas.circuit_breaker = Some(CircuitBreaker {
20236            max_failures: 50_000,
20237            window: Duration::from_secs(60),
20238        });
20239        let err = s.validate().unwrap_err();
20240        assert!(
20241            matches!(
20242                err,
20243                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
20244                    max_failures: 50_000
20245                }
20246            ),
20247            "got {err:?}"
20248        );
20249        let msg = err.to_string();
20250        assert!(
20251            msg.contains("50000"),
20252            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
20253        );
20254    }
20255
20256    #[test]
20257    fn policy_breaker_max_failures_cap_pins_canonical_value() {
20258        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
20259        // value at 1000 — an order of magnitude above every
20260        // documented production-playbook recommendation band
20261        // (Hystrix `requestVolumeThreshold` default 20, Istio
20262        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
20263        // `outlier_detection.consecutive_5xx` default 5, Polly /
20264        // Resilience4j typical 5..=50) and below the
20265        // clearly-pathological "effectively no protection" floor
20266        // (10_000, 100_000, u32::MAX). Pinning the literal value
20267        // here surfaces a future drift (a relaxation to 10_000, a
20268        // tightening to 100) as a deliberate test edit, not a
20269        // silent contract narrowing.
20270        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
20271    }
20272
20273    #[test]
20274    fn rejects_circuit_breaker_zero_window() {
20275        let mut s = three_member_spec();
20276        s.politicas.circuit_breaker = Some(CircuitBreaker {
20277            max_failures: 5,
20278            window: Duration::ZERO,
20279        });
20280        assert_eq!(
20281            s.validate().unwrap_err(),
20282            AplicacaoError::PolicyBreakerZeroWindow
20283        );
20284    }
20285
20286    #[test]
20287    fn rejects_zero_rate_limit() {
20288        let mut s = three_member_spec();
20289        s.politicas.rate_limit = Some(RateLimit {
20290            rate: 0,
20291            window: Duration::from_secs(1),
20292        });
20293        assert_eq!(
20294            s.validate().unwrap_err(),
20295            AplicacaoError::PolicyRateLimitZero
20296        );
20297    }
20298
20299    #[test]
20300    fn rejects_rate_limit_zero_window() {
20301        // `RateLimit { rate: 100, window: Duration::ZERO }` is
20302        // constructible programmatically (the typed `Duration` field
20303        // imposes no nonzero invariant) but renders through
20304        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
20305        // codec's `parse` rejects as `unknown rate-limit window unit
20306        // "0s"`. Until this validate-time gate landed the typed slot
20307        // accepted the value silently and the round-trip break only
20308        // surfaced at deserialize time (potentially in a downstream
20309        // consumer that never re-validates). Pin the rejection at
20310        // `AplicacaoSpec::validate` so the typed slot's valid set
20311        // matches the codec's round-trippable set structurally.
20312        let mut s = three_member_spec();
20313        s.politicas.rate_limit = Some(RateLimit {
20314            rate: 100,
20315            window: Duration::ZERO,
20316        });
20317        assert_eq!(
20318            s.validate().unwrap_err(),
20319            AplicacaoError::PolicyRateLimitWindowNotCanonical {
20320                window: Duration::ZERO
20321            }
20322        );
20323    }
20324
20325    #[test]
20326    fn rejects_rate_limit_arbitrary_seconds_window() {
20327        // 45 seconds is a valid `Duration` but not one of the three
20328        // canonical rate-limit windows the codec round-trips
20329        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
20330        // refuses on round-trip — same round-trip-break shape the
20331        // zero-window arm above pins, with a non-zero magnitude to
20332        // guard against a future "reject only zero" half-measure.
20333        let mut s = three_member_spec();
20334        let window = Duration::from_secs(45);
20335        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
20336        assert_eq!(
20337            s.validate().unwrap_err(),
20338            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
20339        );
20340    }
20341
20342    #[test]
20343    fn rejects_rate_limit_two_minute_window() {
20344        // 120 seconds = 2 minutes is a "looks-canonical" but
20345        // not-canonical window: it's a clean integer multiple of the
20346        // minute unit, but the codec only round-trips the
20347        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
20348        // A `Duration::from_secs(120)` window renders as `"100/120s"`
20349        // which the parser rejects. Pinning this case rules out a
20350        // future "accept any clean multiple of s/m/h" relaxation
20351        // that would silently break the codec contract.
20352        let mut s = three_member_spec();
20353        let window = Duration::from_secs(120);
20354        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
20355        assert_eq!(
20356            s.validate().unwrap_err(),
20357            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
20358        );
20359    }
20360
20361    #[test]
20362    fn rejects_rate_limit_subsecond_window() {
20363        // A sub-second window (e.g. 500ms) is a valid `Duration` but
20364        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
20365        // Pin the rejection so a future relaxation can't silently
20366        // admit fractional-second windows that the codec can't
20367        // round-trip.
20368        let mut s = three_member_spec();
20369        let window = Duration::from_millis(500);
20370        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
20371        assert_eq!(
20372            s.validate().unwrap_err(),
20373            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
20374        );
20375    }
20376
20377    #[test]
20378    fn rejects_policy_rate_limit_above_cap() {
20379        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
20380        // is structurally one past the cap and silently passed
20381        // validate on every pre-gate codebase because the typed slot's
20382        // only `rate` check was the zero-floor arm. The no-op-limiter
20383        // shape only surfaced at the runtime substrate (Envoy's
20384        // `local_rate_limit.token_bucket.max_tokens`, the future
20385        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
20386        // with no field naming the offending policy.
20387        let mut s = three_member_spec();
20388        s.politicas.rate_limit = Some(RateLimit {
20389            rate: POLICY_RATE_LIMIT_MAX + 1,
20390            window: Duration::from_secs(1),
20391        });
20392        assert_eq!(
20393            s.validate().unwrap_err(),
20394            AplicacaoError::PolicyRateLimitExceedsCap {
20395                rate: POLICY_RATE_LIMIT_MAX + 1
20396            }
20397        );
20398    }
20399
20400    #[test]
20401    fn rejects_policy_rate_limit_far_above_cap() {
20402        // The `u32::MAX` worst case — the four-billion-token rate-limit
20403        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
20404        // copy-paste lands in the slot. Pin the cap arm's coverage
20405        // explicitly across the full `u32` overflow so a future
20406        // relaxation that drops the upper bound surfaces here. Peer to
20407        // `rejects_policy_retries_far_above_cap` on the sibling
20408        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
20409        // on the sibling `:max-failures` axis.
20410        let mut s = three_member_spec();
20411        s.politicas.rate_limit = Some(RateLimit {
20412            rate: u32::MAX,
20413            window: Duration::from_secs(1),
20414        });
20415        assert_eq!(
20416            s.validate().unwrap_err(),
20417            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
20418        );
20419    }
20420
20421    #[test]
20422    fn accepts_policy_rate_limit_at_cap() {
20423        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
20424        // must validate. The cap is inclusive on the top edge, matching
20425        // every other typed upper bound in this crate
20426        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
20427        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
20428        // across all three canonical windows so a future off-by-one
20429        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
20430        // window-conditional cap surfaces here as a test failure rather
20431        // than a silent contract narrowing.
20432        for secs in [1u64, 60, 3600] {
20433            let mut s = three_member_spec();
20434            s.politicas.rate_limit = Some(RateLimit {
20435                rate: POLICY_RATE_LIMIT_MAX,
20436                window: Duration::from_secs(secs),
20437            });
20438            s.validate().unwrap_or_else(|e| {
20439                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
20440            });
20441        }
20442    }
20443
20444    #[test]
20445    fn accepts_policy_rate_limit_typical_values() {
20446        // The documented production-playbook recommendation band —
20447        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
20448        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
20449        // Enterprise ~1M per-hour. Every value in the validated set
20450        // must pass; pin the band explicitly so a future tightening
20451        // surfaces here.
20452        //
20453        // Clears the fixture's `:retries` (which is `Some(3)`) so this
20454        // per-axis sweep is pure: the sibling cross-axis
20455        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] gate
20456        // rejects any `rate <= retries` pair, so the `rate = 1`
20457        // boundary at the head of the sweep would otherwise trip on the
20458        // fixture-inherited retry policy rather than the per-axis
20459        // boundary this test names. Same discipline the sibling per-axis
20460        // `accepts_circuit_breaker_max_failures_typical_values` sweep
20461        // takes against the fixture's `:retries` for the peer cross-axis
20462        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
20463        // arm.
20464        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
20465            for secs in [1u64, 60, 3600] {
20466                let mut s = three_member_spec();
20467                s.politicas.retries = None;
20468                s.politicas.rate_limit = Some(RateLimit {
20469                    rate,
20470                    window: Duration::from_secs(secs),
20471                });
20472                s.validate().unwrap_or_else(|e| {
20473                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
20474                });
20475            }
20476        }
20477    }
20478
20479    #[test]
20480    fn policy_rate_limit_zero_takes_precedence_over_cap() {
20481        // The cross-arm ordering pin: `rate == 0` is structurally
20482        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
20483        // (cap), but the zero-floor diagnostic is the more
20484        // self-locating one (it directly names the omit-axis
20485        // remediation). Pin the order so a future refactor that
20486        // reorders the arms surfaces here as a test failure rather
20487        // than a silent diagnostic regression. Same shape every other
20488        // zero-then-cap ordering on this surface uses
20489        // ([`AplicacaoError::PolicyRetriesZero`] then
20490        // [`AplicacaoError::PolicyRetriesExceedsCap`];
20491        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
20492        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
20493        let mut s = three_member_spec();
20494        s.politicas.rate_limit = Some(RateLimit {
20495            rate: 0,
20496            window: Duration::from_secs(1),
20497        });
20498        assert_eq!(
20499            s.validate().unwrap_err(),
20500            AplicacaoError::PolicyRateLimitZero,
20501            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
20502        );
20503    }
20504
20505    #[test]
20506    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
20507        // Two-axis-bad pin: rate above cap *and* window non-canonical.
20508        // The validate gate must fire on the rate cap first — the
20509        // amplification-shape (no-op limiter) diagnostic is the more
20510        // fundamental one; the window-canonical diagnostic is the
20511        // narrower codec-round-trip shape. Pin the ordering so a future
20512        // refactor that reorders the rate-then-window check arms
20513        // surfaces here as a test failure rather than a silent
20514        // diagnostic regression.
20515        let mut s = three_member_spec();
20516        s.politicas.rate_limit = Some(RateLimit {
20517            rate: POLICY_RATE_LIMIT_MAX + 1,
20518            window: Duration::from_secs(45),
20519        });
20520        assert_eq!(
20521            s.validate().unwrap_err(),
20522            AplicacaoError::PolicyRateLimitExceedsCap {
20523                rate: POLICY_RATE_LIMIT_MAX + 1
20524            },
20525            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
20526        );
20527    }
20528
20529    #[test]
20530    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
20531        // The diagnostic-shape pin: the offending `u32` is carried
20532        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
20533        // variant so the surfaced error message names the value the
20534        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
20535        // the mesh-policy ceiling …"`), not just the cap. Same
20536        // self-locating diagnostic shape every other typed-cap arm on
20537        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
20538        // carries the offending retries count verbatim,
20539        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
20540        // the offending failure count verbatim).
20541        let mut s = three_member_spec();
20542        s.politicas.rate_limit = Some(RateLimit {
20543            rate: 5_000_000,
20544            window: Duration::from_secs(1),
20545        });
20546        let err = s.validate().unwrap_err();
20547        assert!(
20548            matches!(
20549                err,
20550                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
20551            ),
20552            "got {err:?}"
20553        );
20554        let msg = err.to_string();
20555        assert!(
20556            msg.contains("5000000"),
20557            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
20558        );
20559    }
20560
20561    #[test]
20562    fn policy_rate_limit_cap_pins_canonical_value() {
20563        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
20564        // 1_000_000 — two-to-three orders of magnitude above every
20565        // documented production-playbook recommendation band (Envoy /
20566        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
20567        // Gateway 10_000..=100_000 per-minute) and below the
20568        // clearly-pathological "paste-from-binary blob" floor
20569        // (100_000_000, u32::MAX). Pinning the literal value here
20570        // surfaces a future drift (a relaxation to 10_000_000, a
20571        // tightening to 100_000) as a deliberate test edit, not a
20572        // silent contract narrowing.
20573        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
20574    }
20575
20576    #[test]
20577    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
20578        // Both axes are invalid here: rate == 0 *and* window is
20579        // non-canonical. The validate gate must fire on rate first
20580        // (matching the existing `rejects_zero_rate_limit` ordering),
20581        // so the existing diagnostic continues to lead with the
20582        // simpler "zero rate" framing. Pinning the order of checks
20583        // so a future refactor that reorders the arms surfaces here
20584        // as a test failure rather than a silent diagnostic
20585        // regression.
20586        let mut s = three_member_spec();
20587        s.politicas.rate_limit = Some(RateLimit {
20588            rate: 0,
20589            window: Duration::from_secs(45),
20590        });
20591        assert_eq!(
20592            s.validate().unwrap_err(),
20593            AplicacaoError::PolicyRateLimitZero
20594        );
20595    }
20596
20597    #[test]
20598    fn rate_limit_canonical_windows_validate() {
20599        // The three canonical windows the codec round-trips
20600        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
20601        // unchanged. Pin the full canonical set as a positive case
20602        // (the existing `rate_limit_round_trip_seconds` /
20603        // `rate_limit_round_trip_minutes` tests pin the
20604        // serialize-then-deserialize property at the codec layer; this
20605        // test pins the validate-side complement so a future tightening
20606        // of the canonical set — e.g. dropping `:hour` — surfaces here
20607        // as a test failure rather than a silent contract narrowing).
20608        for secs in [1u64, 60, 3600] {
20609            let mut s = three_member_spec();
20610            s.politicas.rate_limit = Some(RateLimit {
20611                rate: 100,
20612                window: Duration::from_secs(secs),
20613            });
20614            s.validate().expect("canonical window must validate");
20615        }
20616    }
20617
20618    #[test]
20619    fn rate_limit_validated_value_round_trips_through_codec() {
20620        // The structural property the validate gate enforces:
20621        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
20622        // losslessly through the `rate_limit_codec` (serialize → string
20623        // → deserialize → equal value). Pin this end-to-end so a future
20624        // change to either side (the validate gate's accepted window
20625        // set, the codec's parse/render unit set) that breaks the
20626        // alignment surfaces here. The previous-state shape (typed
20627        // slot accepts arbitrary `Duration`, codec only round-trips
20628        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
20629        // window — the validate gate now forecloses that.
20630        for secs in [1u64, 60, 3600] {
20631            let mut s = three_member_spec();
20632            s.politicas.rate_limit = Some(RateLimit {
20633                rate: 250,
20634                window: Duration::from_secs(secs),
20635            });
20636            s.validate().unwrap();
20637            let json = serde_json::to_string(&s.politicas).unwrap();
20638            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20639            assert_eq!(
20640                back.rate_limit, s.politicas.rate_limit,
20641                "every validated :rate-limit must round-trip losslessly through the codec"
20642            );
20643        }
20644    }
20645
20646    #[test]
20647    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
20648        // The hour-window canonical form (`"<n>/h"`) was missing from
20649        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
20650        // pair. Now that the validate gate pins 3600s as part of the
20651        // canonical set, pin its serialize-side render shape too so
20652        // the third leg of the s/m/h tripod is explicitly tested.
20653        let policy = MeshPolicy {
20654            rate_limit: Some(RateLimit {
20655                rate: 10000,
20656                window: Duration::from_secs(3600),
20657            }),
20658            ..Default::default()
20659        };
20660        let json = serde_json::to_string(&policy).unwrap();
20661        assert!(
20662            json.contains("\"10000/h\""),
20663            "hour-window canonical form must render with `h` suffix (got: {json})"
20664        );
20665        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20666        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
20667    }
20668
20669    #[test]
20670    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
20671        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
20672        // typed accessor's accepted-window set against the codec's
20673        // accepted set explicitly. A future addition to the codec
20674        // (e.g. accepting `:day`/`:week` as authoring units) must be
20675        // accompanied by a parallel addition here, and a regression
20676        // that drops one of the three canonical units from either
20677        // side surfaces as a test failure. The accessor is the
20678        // single source of truth for the canonical-window set —
20679        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
20680        // gate and [`rate_limit_codec::render`]'s canonical arm both
20681        // read through it — this test enshrines that its
20682        // `Duration → Option<RateLimitUnit>` projection matches the
20683        // codec's parse / render arms' accepted-window set exactly.
20684        //
20685        // Predecessor: this pin previously read the module-private
20686        // free helper `is_canonical_rate_limit_window` — a delegate
20687        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
20688        // — but the helper had no production consumers left after the
20689        // validate-gate migration onto [`RateLimit::canonical_unit`]
20690        // and was deleted; the closed-set arm-window bijection now
20691        // lives on exactly one typed dispatch on the substrate
20692        // primitive.
20693        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
20694            RateLimit { rate: 1, window }.canonical_unit()
20695        };
20696        assert!(canonical_unit(Duration::from_secs(1)).is_some());
20697        assert!(canonical_unit(Duration::from_secs(60)).is_some());
20698        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
20699        // Non-canonical windows the accessor rejects.
20700        assert!(canonical_unit(Duration::ZERO).is_none());
20701        assert!(canonical_unit(Duration::from_secs(2)).is_none());
20702        assert!(canonical_unit(Duration::from_secs(30)).is_none());
20703        assert!(canonical_unit(Duration::from_secs(120)).is_none());
20704        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
20705        // Sub-second windows: even `Duration::from_millis(1000)` is
20706        // exactly 1s and accepted; `Duration::from_millis(500)` is
20707        // sub-second and rejected.
20708        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
20709        assert!(canonical_unit(Duration::from_millis(500)).is_none());
20710        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
20711    }
20712
20713    #[test]
20714    fn rate_limit_unit_table_projections_are_mutual_inverses() {
20715        // Bidirection pin against the closed-set typed enum
20716        // [`RateLimitUnit`] arm-table (the canonical
20717        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
20718        // of the rate-limit unit surface reads from). The two
20719        // projection directions [`RateLimitUnit::from_suffix`] /
20720        // [`RateLimitUnit::window`] (str → Duration, exposed as one
20721        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
20722        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
20723        // (Duration → str, exposed as one typed dispatch through
20724        // [`RateLimit::canonical_unit`] composed with
20725        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
20726        // codec's parse arm ([`rate_limit_codec::parse`] via
20727        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
20728        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
20729        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
20730        // via [`RateLimit::canonical_unit`]) all key off. A future
20731        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
20732        // sub-second window) is one variant + one arm per method on the
20733        // closed-set enum; the compiler-enforced exhaustiveness on
20734        // every consumer's `match self` arms picks it up by
20735        // construction. This pin enshrines that both projection
20736        // directions agree on every canonical arm row and neither
20737        // leaks a spurious entry the other doesn't recognize.
20738        //
20739        // Predecessor: this test previously read the two vestigial
20740        // module-private free helpers `rate_limit_window_unit` and
20741        // `rate_limit_window_from_unit` on the `Duration → &str` and
20742        // `&str → Duration` axes; the former was deleted after its
20743        // sole production consumer ([`rate_limit_codec::render`])
20744        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
20745        // the latter is folded here into the substrate primitive
20746        // [`RateLimitUnit::window_from_suffix`] so both projection
20747        // directions live on the closed-set enum's arm-table.
20748        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
20749            let window = super::RateLimitUnit::window_from_suffix(unit)
20750                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
20751            assert_eq!(
20752                window,
20753                Duration::from_secs(secs),
20754                "unit {unit:?} must resolve to {secs}s"
20755            );
20756            let projected_suffix = RateLimit { rate: 1, window }
20757                .canonical_unit()
20758                .map(super::RateLimitUnit::as_suffix);
20759            assert_eq!(
20760                projected_suffix,
20761                Some(unit),
20762                "Duration({secs}s) must render as {unit:?} \
20763                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
20764            );
20765        }
20766        // Non-table units yield None on the `unit → Duration`
20767        // projection — a future `"d"` addition to the table would
20768        // flip this arm; today it pins the current three-row table's
20769        // rejection semantics.
20770        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
20771        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
20772        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
20773        // Non-table Durations yield None on the `Duration → unit`
20774        // projection — pins that the two projections agree on the
20775        // "not in the table" semantic too, so a drift where the
20776        // parse-side accepts a value the render-side can't emit is
20777        // a build error at the two-arm pair, not a silent codec
20778        // round-trip break.
20779        let projected_suffix = |window: Duration| -> Option<&'static str> {
20780            RateLimit { rate: 1, window }
20781                .canonical_unit()
20782                .map(super::RateLimitUnit::as_suffix)
20783        };
20784        assert!(projected_suffix(Duration::from_secs(2)).is_none());
20785        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
20786        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
20787    }
20788
20789    #[test]
20790    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
20791        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
20792        // substrate-primitive `&str → Duration` associated method the
20793        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
20794        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
20795        // to the same [`Duration`] the two-step composition
20796        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
20797        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
20798        // `"MIN"`) must project to [`None`] on both paths. A future
20799        // implementation of `window_from_suffix` that took a shortcut
20800        // through a per-suffix `match` table (bypassing the arm-table's
20801        // `Self::from_suffix` scan and the arm-table's `Self::window`
20802        // dispatch) would silently split the accept-set — the parse
20803        // arm would accept a suffix the enum's arm-table doesn't know,
20804        // or reject a suffix the enum's arm-table does; this pin
20805        // surfaces that drift at caixa-core build time rather than at a
20806        // downstream serde round-trip audit on a live `MeshPolicy`.
20807        //
20808        // Same byte-parity discipline the sibling
20809        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
20810        // pin carries on the peer `Duration → RateLimitUnit` axis via
20811        // [`RateLimit::canonical_unit`], and the peer
20812        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
20813        // carries on the bidirectional arm-table axis — extended here
20814        // onto the fifth (and last unlifted) projection axis on the
20815        // closed-set enum's arm-table.
20816        let composition = |suffix: &str| -> Option<Duration> {
20817            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
20818        };
20819        for suffix in ["s", "m", "h"] {
20820            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
20821            let via_composition = composition(suffix);
20822            assert_eq!(
20823                via_method, via_composition,
20824                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
20825                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
20826                 method must delegate to the arm-table's two typed dispatches, \
20827                 not shortcut through a per-suffix match table"
20828            );
20829            assert!(
20830                via_method.is_some(),
20831                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
20832                 RateLimitUnit::window_from_suffix"
20833            );
20834        }
20835        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
20836            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
20837            let via_composition = composition(suffix);
20838            assert_eq!(
20839                via_method, via_composition,
20840                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
20841                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
20842                 axis too"
20843            );
20844            assert!(
20845                via_method.is_none(),
20846                "non-arm suffix {suffix:?} must project to None via \
20847                 RateLimitUnit::window_from_suffix — a future extension that \
20848                 accepted this suffix without a corresponding arm on the enum \
20849                 would split the codec's parse-accepted set from the enum's \
20850                 arm-table"
20851            );
20852        }
20853        // And the codec's parse arm now reads through this method: a
20854        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
20855        // the same `Duration` the method returns for its unit, closing
20856        // the two-consumer drift surface (the codec's parse arm and the
20857        // enum's arm-table) with one typed dispatch on the substrate
20858        // primitive.
20859        for suffix in ["s", "m", "h"] {
20860            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
20861            let mp: MeshPolicy = serde_json::from_str(&wire)
20862                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
20863            let parsed = mp.rate_limit().expect("rate_limit payload present");
20864            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
20865                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
20866            assert_eq!(
20867                parsed.window(),
20868                via_method,
20869                "codec parse arm on {wire:?} must resolve the window through \
20870                 RateLimitUnit::window_from_suffix, not a divergent path"
20871            );
20872        }
20873    }
20874
20875    #[test]
20876    fn rate_limit_unit_all_enumerates_every_arm_once() {
20877        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
20878        // enumerate every arm of the closed-set enum exactly once, in
20879        // the canonical shortest-to-longest window order (Second before
20880        // Minute before Hour) — the same order the sibling
20881        // [`crate::supervisor::RestartStrategy`] /
20882        // [`crate::supervisor::RestartPolicy`] /
20883        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
20884        // typed enums carry (the arm declared first is the arm listed
20885        // first). A future variant addition that extends the enum
20886        // without appending to [`RateLimitUnit::ALL`] leaves the
20887        // exhaustive iteration surface silently short one arm — the
20888        // codec's parse arm would then reject the new suffix even
20889        // though the enum knows it. This pin closes the drift.
20890        assert_eq!(
20891            super::RateLimitUnit::ALL,
20892            &[
20893                super::RateLimitUnit::Second,
20894                super::RateLimitUnit::Minute,
20895                super::RateLimitUnit::Hour,
20896            ],
20897            "RateLimitUnit::ALL must enumerate every arm exactly once, \
20898             in canonical shortest-to-longest window order"
20899        );
20900    }
20901
20902    #[test]
20903    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
20904        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
20905        // every arm's [`RateLimitUnit::as_suffix`] output must parse
20906        // back through [`RateLimitUnit::from_suffix`] to the same
20907        // variant. A future arm addition that lands `as_suffix` but
20908        // forgets `from_suffix` (`from_suffix` iterates
20909        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
20910        // is the load-bearing carrier of the round-trip; the sibling
20911        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
20912        // the `ALL` half) trips here at caixa-core build time rather
20913        // than surfacing as a codec round-trip miss (a `render` emit
20914        // that lands a suffix the paired `parse` cannot decode).
20915        for unit in super::RateLimitUnit::ALL {
20916            let suffix = unit.as_suffix();
20917            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
20918                panic!(
20919                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
20920                     RateLimitUnit::as_suffix output — got None for {unit:?}"
20921                )
20922            });
20923            assert_eq!(
20924                parsed, *unit,
20925                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
20926                 must return RateLimitUnit::{unit:?}"
20927            );
20928        }
20929    }
20930
20931    #[test]
20932    fn rate_limit_unit_from_window_and_window_round_trip() {
20933        // Total round-trip pin on the `(from_window, window)` pair:
20934        // every arm's [`RateLimitUnit::window`] output must parse back
20935        // through [`RateLimitUnit::from_window`] to the same variant.
20936        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
20937        // on the peer `Duration` axis — the two round-trip pins
20938        // together enshrine that both projections of the typed
20939        // canonical-unit bijection are total on the arm-set.
20940        for unit in super::RateLimitUnit::ALL {
20941            let window = unit.window();
20942            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
20943                panic!(
20944                    "RateLimitUnit::from_window({window:?}) must accept every \
20945                     RateLimitUnit::window output — got None for {unit:?}"
20946                )
20947            });
20948            assert_eq!(
20949                parsed, *unit,
20950                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
20951                 must return RateLimitUnit::{unit:?}"
20952            );
20953        }
20954    }
20955
20956    #[test]
20957    fn rate_limit_unit_from_window_accessor_is_const_fn() {
20958        // Fail-before-pass-after pin: witnesses the
20959        // [`RateLimitUnit::from_window`] `const`-eval posture via a
20960        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
20961        // -> Option<RateLimitUnit>` whose body calls
20962        // `RateLimitUnit::from_window(window)`, well-formed only when
20963        // the callee is itself `const fn` (any future downgrade to
20964        // non-`const` fails at caixa-core build time with E0015 `cannot
20965        // call non-const function`, strictly stronger than a runtime
20966        // `assert!`, side-stepping the destructor-in-const restriction
20967        // that blocks direct `const _: Option<RateLimitUnit> =
20968        // RateLimitUnit::from_window(...)` items on `Duration`'s
20969        // carrier). The runtime body sweeps every closed-set
20970        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
20971        // rejection sample (`Duration::from_millis(500)` sub-second
20972        // residue) and asserts the wrapped and direct dispatches agree
20973        // — a violation means the wrapper stopped compiling under a
20974        // future `const`-posture downgrade, or the reverse resolver's
20975        // arm-set silently split from the peer `Self::window` emitter's
20976        // arm-set. Peer of the sibling
20977        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
20978        // (152c868) /
20979        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
20980        // (152c868) /
20981        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
20982        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
20983        // `const`-eval-surface pins on the peer M2 / M3 substrate-
20984        // primitive `Copy`-return accessor axes, extended onto the
20985        // reverse `Duration → RateLimitUnit` projection axis on the
20986        // M3 mesh-slot rate-limit closed-set typed enum.
20987        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
20988            super::RateLimitUnit::from_window(window)
20989        }
20990        for unit in super::RateLimitUnit::ALL {
20991            let window = unit.window();
20992            let via_wrapper = from_window_via_const_fn(window);
20993            let direct = super::RateLimitUnit::from_window(window);
20994            assert_eq!(
20995                via_wrapper, direct,
20996                "RateLimitUnit::from_window({window:?}) via const fn \
20997                 wrapper must agree with direct dispatch for {unit:?}"
20998            );
20999            assert_eq!(
21000                via_wrapper,
21001                Some(*unit),
21002                "RateLimitUnit::from_window({window:?}) via const fn \
21003                 wrapper must return Some({unit:?}) for the peer \
21004                 window() output"
21005            );
21006        }
21007        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
21008        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
21009    }
21010
21011    #[test]
21012    fn rate_limit_unit_from_window_composes_through_window_accessor() {
21013        // Composition-witness pin on the routing-through-peer discipline:
21014        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
21015        // through the peer `pub const fn` [`RateLimitUnit::window`]
21016        // canonical-`Duration` projection rather than a hand-authored
21017        // per-arm second-magnitude literal — a future arm-magnitude edit
21018        // on the sibling `window()` accessor (a `Second → 2s` typo, a
21019        // `Hour → 3599s` off-by-one) must therefore reach this reverse
21020        // resolver by construction. A pin that hard-coded the three
21021        // second-magnitudes here would silently split from the peer
21022        // emitter on any such edit; instead, this pin asserts the
21023        // composition invariant `from_window(u.window()) == Some(u)`
21024        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
21025        // arm — a violation means either the peer `Self::window`
21026        // accessor drifted (breaking every downstream consumer that
21027        // reads through it), or the reverse resolver stopped routing
21028        // through the peer (introducing a hand-authored literal that
21029        // silently disagrees with the emitter). Either failure is a
21030        // caixa-core-build-time surface, not a downstream renderer
21031        // round-trip regression.
21032        //
21033        // Peer of the sibling
21034        // [`crate::render::assert_str_reexport_identity`] discipline on
21035        // the substrate-primitive `&'static str` re-export axis and the
21036        // [`rate_limit_unit_from_window_and_window_round_trip`]
21037        // round-trip pin on the peer projection direction; extends the
21038        // one-canonical-dispatch-per-projection discipline onto the
21039        // reverse-resolver's per-arm probe axis.
21040        for unit in super::RateLimitUnit::ALL {
21041            let window_via_peer = unit.window();
21042            let resolved = super::RateLimitUnit::from_window(window_via_peer);
21043            assert_eq!(
21044                resolved,
21045                Some(*unit),
21046                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
21047                 must return Some({unit:?}) — the reverse resolver's per-arm \
21048                 probes must route through the peer `Self::window` accessor \
21049                 so any future arm-magnitude edit reaches both projection \
21050                 directions by construction"
21051            );
21052        }
21053    }
21054
21055    #[test]
21056    fn rate_limit_canonical_unit_accessor_is_const_fn() {
21057        // Fail-before-pass-after pin: witnesses the
21058        // [`RateLimit::canonical_unit`] `const`-eval posture via a
21059        // `const fn` wrapper
21060        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
21061        // whose body calls `rl.canonical_unit()`, well-formed only when
21062        // the callee is itself `const fn` (any future downgrade to
21063        // non-`const` fails at caixa-core build time with E0015 `cannot
21064        // call non-const method`). The runtime body sweeps every
21065        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
21066        // constructs a typed [`RateLimit`] with the peer `Self::window`
21067        // canonical `Duration`, then asserts both the wrapper and the
21068        // direct dispatch agree and both return `Some(unit)`. Composes
21069        // with the sibling
21070        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
21071        // typed [`RateLimit`] projection layer's `const`-posture is
21072        // load-bearing on the reverse resolver's `const`-posture, and
21073        // both must migrate together (a downgrade of either surface
21074        // splits the paired `const`-eval-surface pass on the M3
21075        // mesh-slot rate-limit `Duration ↔ Self` bijection).
21076        const fn canonical_unit_via_const_fn(
21077            rl: &super::RateLimit,
21078        ) -> Option<super::RateLimitUnit> {
21079            rl.canonical_unit()
21080        }
21081        for unit in super::RateLimitUnit::ALL {
21082            let rl = super::RateLimit {
21083                rate: 1,
21084                window: unit.window(),
21085            };
21086            let via_wrapper = canonical_unit_via_const_fn(&rl);
21087            let direct = rl.canonical_unit();
21088            assert_eq!(
21089                via_wrapper, direct,
21090                "RateLimit::canonical_unit() via const fn wrapper must \
21091                 agree with direct dispatch for {unit:?}"
21092            );
21093            assert_eq!(
21094                via_wrapper,
21095                Some(*unit),
21096                "RateLimit::canonical_unit() via const fn wrapper must \
21097                 return Some({unit:?}) for a RateLimit whose window is \
21098                 the peer RateLimitUnit::{unit:?}.window() output"
21099            );
21100        }
21101    }
21102
21103    #[test]
21104    fn rate_limit_unit_projections_are_pairwise_distinct() {
21105        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
21106        // [`RateLimitUnit::window`] outputs must be pairwise distinct
21107        // across every arm — an accidental copy-paste flip that
21108        // reroutes one arm's suffix or window to also match another
21109        // silently collapses two arms onto one, so
21110        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
21111        // (both using `find` on `Self::ALL`) would return whichever
21112        // arm the linear scan lands on first — a match-arm-ordering-
21113        // dependent outcome the closed-set typed-enum shape is meant
21114        // to rule out structurally. Peer of the sibling
21115        // `caixa_kind_wire_consts_are_pairwise_distinct` /
21116        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
21117        // other closed-set typed-enum discriminator axes.
21118        let all = super::RateLimitUnit::ALL;
21119        for (i, a) in all.iter().enumerate() {
21120            for (j, b) in all.iter().enumerate() {
21121                if i != j {
21122                    assert_ne!(
21123                        a.as_suffix(),
21124                        b.as_suffix(),
21125                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
21126                         must be distinct — a collision silently collapses two \
21127                         arms onto one under from_suffix's linear scan"
21128                    );
21129                    assert_ne!(
21130                        a.window(),
21131                        b.window(),
21132                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
21133                         must be distinct — a collision silently collapses two \
21134                         arms onto one under from_window's linear scan"
21135                    );
21136                }
21137            }
21138        }
21139    }
21140
21141    #[test]
21142    fn rate_limit_unit_display_routes_through_as_suffix() {
21143        // Route pin: [`std::fmt::Display`] must byte-equal
21144        // [`RateLimitUnit::as_suffix`] on every arm — the single
21145        // source of truth for the canonical suffix. A future
21146        // reimplementation that hand-rolls the arms instead of
21147        // delegating to [`RateLimitUnit::as_suffix`] would silently
21148        // desynchronize `format!("{u}")` from the codec's parse arm
21149        // (which uses `as_suffix` to compare suffixes). Peer of the
21150        // sibling `caixa_kind_display_routes_through_as_str_helper` /
21151        // `placement_strategy_display_routes_through_as_str_helper`
21152        // pins on the peer closed-set typed-enum Display axes.
21153        for unit in super::RateLimitUnit::ALL {
21154            assert_eq!(
21155                unit.to_string(),
21156                unit.as_suffix(),
21157                "RateLimitUnit::{unit:?} Display must route through \
21158                 as_suffix (single source of truth: the canonical suffix \
21159                 the codec parses and renders)"
21160            );
21161        }
21162    }
21163
21164    #[test]
21165    fn rate_limit_unit_as_ref_str_routes_through_as_suffix_accessor() {
21166        // Fail-before-pass-after byte-parity pin on the lifted
21167        // `impl AsRef<str> for RateLimitUnit` — asserts the standard-
21168        // library trait impl and the substrate-primitive
21169        // [`super::RateLimitUnit::as_suffix`] `pub const fn` accessor
21170        // resolve to the same `&str` per instance across the three-arm
21171        // closed set, so any future silent detour that routes the impl
21172        // through a divergent projection (a per-arm inline
21173        // `match self { RateLimitUnit::Second => "s", … }` re-inlining
21174        // that opens a compile-time link to the un-lifted arm-literal,
21175        // a swap onto the second-magnitude
21176        // [`super::RateLimitUnit::window`] axis that would collide the
21177        // canonical-suffix / token-bucket-refill two-axis split) trips
21178        // at caixa-core test time under `PartialEq` rather than at a
21179        // downstream `impl AsRef<str>`-bound consumer's silent split.
21180        // Sweeps every one of the three arms
21181        // [`super::RateLimitUnit::ALL`] carries so no arm's projection
21182        // is covered only by the sibling `Display` path. Peer of the
21183        // sibling
21184        // `placement_strategy_as_ref_str_routes_through_as_str_accessor`
21185        // (d86edd2) on the M3 mesh-placement closed-set typed enum,
21186        // and the peer
21187        // [`crate::kind::tests::caixa_kind_as_ref_str_routes_through_as_str_accessor`]
21188        // (cd2091f) pin on the top-level closed-set typed
21189        // discriminator — the pins together close the substrate
21190        // primitive's `AsRef<str>` projection axis on every closed-set
21191        // typed enum with a `fmt::Display` surface across the M2 / M3
21192        // typed slots plus the top-level `:kind` + `:versao`
21193        // primitives.
21194        for &unit in super::RateLimitUnit::ALL {
21195            assert_eq!(
21196                <super::RateLimitUnit as AsRef<str>>::as_ref(&unit),
21197                unit.as_suffix(),
21198                "AsRef<str> impl on RateLimitUnit::{unit:?} must \
21199                 byte-equal RateLimitUnit::as_suffix on the same \
21200                 instance — divergence signals a silent detour off the \
21201                 substrate-primitive accessor"
21202            );
21203        }
21204    }
21205
21206    #[test]
21207    fn rate_limit_unit_as_ref_str_routes_through_display_via_shared_accessor() {
21208        // Fail-before-pass-after byte-parity pin on the three-path
21209        // convergence discipline the M3 `:politicas :rate-limit`
21210        // canonical-unit primitive now carries on the `&str`-projection
21211        // axis: `<RateLimitUnit as AsRef<str>>::as_ref(&v)` (the newly
21212        // lifted impl), `format!("{v}")` (the pre-existing
21213        // [`fmt::Display`] impl), and `v.as_suffix()` (the substrate-
21214        // primitive `pub const fn` accessor both trait impls delegate
21215        // through) must resolve to the same byte-string on every
21216        // instance across the three-arm closed set. Refuses any future
21217        // divergence between the two trait impls (a stray
21218        // [`fmt::Display::fmt`] rewrite that hand-rolls the arms
21219        // rather than delegating through the shared accessor; a
21220        // hypothetical `AsRef<str>` rewrite that inlines a per-arm
21221        // literal cascade) that would silently split the two
21222        // projection paths of the same closed-set typed enum. Mirrors
21223        // the sibling three-path-convergence discipline the peer
21224        // [`super::PlacementStrategy`] typed enum carries
21225        // (`placement_strategy_as_ref_str_routes_through_display_via_shared_accessor`,
21226        // d86edd2), the peer [`crate::CaixaKind`] triple
21227        // (`caixa_kind_as_ref_str_routes_through_display_via_shared_accessor`,
21228        // cd2091f), and the [`crate::CaixaVersion`] typed newtype
21229        // triple (`caixa_version_as_ref_str_routes_through_display_via_shared_accessor`,
21230        // 16d5c7e).
21231        for &unit in super::RateLimitUnit::ALL {
21232            let via_as_ref: &str = <super::RateLimitUnit as AsRef<str>>::as_ref(&unit);
21233            let via_display: String = format!("{unit}");
21234            let via_accessor: &str = unit.as_suffix();
21235            assert_eq!(via_as_ref, via_accessor);
21236            assert_eq!(via_display, via_accessor);
21237            assert_eq!(via_as_ref, via_display.as_str());
21238        }
21239    }
21240
21241    #[test]
21242    fn rate_limit_unit_from_window_rejects_non_canonical() {
21243        // Rejection pin on the parser's accept-set: any Duration
21244        // outside the three-arm [`RateLimitUnit::window`] output set
21245        // (sub-second residue, or a second-magnitude outside `{1, 60,
21246        // 3600}`) must return `None`. A future accidental widening of
21247        // the accept-set (rounding down sub-second residue to the
21248        // nearest arm, admitting `Duration::from_secs(30)` as a
21249        // half-minute unit) would silently drift the parser's accept-
21250        // set from the emitter's — a validated slot with a
21251        // non-canonical window would then round-trip through the
21252        // codec to a canonical form the author never wrote.
21253        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
21254        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
21255        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
21256        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
21257        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
21258        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
21259        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
21260    }
21261
21262    #[test]
21263    fn rate_limit_unit_from_suffix_rejects_unknown() {
21264        // Rejection pin on the suffix parser's accept-set: any string
21265        // outside the three-arm [`RateLimitUnit::as_suffix`] output
21266        // set must return `None`. Peer of the sibling
21267        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
21268        // the [`crate::CaixaKind`] `from_wire` accept-set.
21269        for bad in [
21270            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
21271            " s",
21272        ] {
21273            assert!(
21274                super::RateLimitUnit::from_suffix(bad).is_none(),
21275                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
21276                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
21277                 outputs"
21278            );
21279        }
21280    }
21281
21282    #[test]
21283    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
21284        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
21285        // every canonical `:window` magnitude the validate gate
21286        // accepts must map to the paired [`RateLimitUnit`] arm through
21287        // this accessor. A future validate-gate rebrand that widened
21288        // the accepted-window set without extending [`RateLimitUnit`]
21289        // would silently split the accessor's `Some`-return set from
21290        // the validate gate's accept-set — a slot that satisfies
21291        // validate would land at the accessor with `None`, so a
21292        // consumer past validate that pattern-matches on the returned
21293        // `Some` would silently miss the newly-accepted magnitude.
21294        for (window_secs, expected) in [
21295            (1u64, super::RateLimitUnit::Second),
21296            (60, super::RateLimitUnit::Minute),
21297            (3600, super::RateLimitUnit::Hour),
21298        ] {
21299            let rl = RateLimit {
21300                rate: 100,
21301                window: Duration::from_secs(window_secs),
21302            };
21303            assert_eq!(
21304                rl.canonical_unit(),
21305                Some(expected),
21306                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
21307                 must return Some({expected:?})"
21308            );
21309        }
21310        // Non-canonical windows the validate gate rejects also return
21311        // None here — the accessor is the typed-enum projection of
21312        // the sibling `is_canonical_rate_limit_window` predicate.
21313        let bad = RateLimit {
21314            rate: 100,
21315            window: Duration::from_secs(30),
21316        };
21317        assert!(
21318            bad.canonical_unit().is_none(),
21319            "RateLimit with a non-canonical window must return None from \
21320             canonical_unit — the validate gate rejects the same set"
21321        );
21322    }
21323
21324    #[test]
21325    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
21326        // Fail-before-pass-after byte-parity pin: for every canonical
21327        // window the [`rate_limit_codec::render`] arm's emitted string
21328        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
21329        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
21330        // the vestigial free helper [`rate_limit_window_unit`] (a
21331        // `find_map`-walked `Duration → &'static str` delegate) onto the
21332        // substrate primitive [`RateLimit::canonical_unit`] typed method
21333        // (a closed-set `match self.window` arm on
21334        // [`RateLimitUnit::from_window`], projected through
21335        // [`RateLimitUnit::as_suffix`] via the enum's
21336        // [`std::fmt::Display`] impl). A future re-routing of the render
21337        // arm through a differently-computed unit projection would break
21338        // this pin at build time rather than as a silent per-consumer
21339        // codec round-trip drift far from the substrate primitive edit.
21340        //
21341        // Sibling to the peer
21342        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
21343        // on the free-helper axis: that pin locks the two projections
21344        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
21345        // on the closed-set arm table; this pin locks the codec's render
21346        // arm reads through the typed accessor rather than the free
21347        // helper. Two production consumers of the canonical-unit axis
21348        // now key off one typed dispatch on the substrate primitive.
21349        for (window_secs, unit) in [
21350            (1u64, super::RateLimitUnit::Second),
21351            (60, super::RateLimitUnit::Minute),
21352            (3600, super::RateLimitUnit::Hour),
21353        ] {
21354            let rl = RateLimit {
21355                rate: 42,
21356                window: Duration::from_secs(window_secs),
21357            };
21358            let policy = MeshPolicy {
21359                rate_limit: Some(rl),
21360                ..Default::default()
21361            };
21362            let json = serde_json::to_string(&policy).unwrap();
21363            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
21364            assert!(
21365                json.contains(&expected),
21366                "rate_limit_codec::render must emit {expected} (via \
21367                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
21368                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
21369            );
21370            // And the accessor route resolves to the same typed unit
21371            // the render arm's Display formatting is asked to produce —
21372            // so a future edit that split the two paths (one through
21373            // the accessor, one through a re-introduced free helper)
21374            // trips this pin.
21375            assert_eq!(
21376                rl.canonical_unit(),
21377                Some(unit),
21378                "RateLimit::canonical_unit must return Some({unit:?}) for a \
21379                 {window_secs}s window; the codec render arm reads the same \
21380                 typed unit through this accessor"
21381            );
21382        }
21383    }
21384
21385    #[test]
21386    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
21387        // Fail-before-pass-after byte-parity pin on the validate gate's
21388        // canonical-window shape probe: every non-canonical `:window`
21389        // the free-helper predicate [`is_canonical_rate_limit_window`]
21390        // rejects is also rejected by the substrate primitive
21391        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
21392        // gate now reads through, and vice versa on the accepted set
21393        // (the three canonical windows). Locks the migration from the
21394        // free helper onto the substrate primitive: a future re-routing
21395        // of one of the two paths through a differently-computed unit
21396        // projection would silently split the codec's accepted set from
21397        // the validate gate's accepted set — a two-consumer drift the
21398        // codec-round-trip pin
21399        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
21400        // above closes on the render arm and this pin closes on the
21401        // validate arm.
21402        for canonical_window_secs in [1u64, 60, 3600] {
21403            let mut s = three_member_spec();
21404            let rl = RateLimit {
21405                rate: 100,
21406                window: Duration::from_secs(canonical_window_secs),
21407            };
21408            s.politicas.rate_limit = Some(rl);
21409            assert!(
21410                s.validate().is_ok(),
21411                "canonical {canonical_window_secs}s window must pass \
21412                 validate_politicas — the validate gate now reads \
21413                 RateLimit::canonical_unit().is_none() and the accessor \
21414                 returns Some on every canonical arm"
21415            );
21416            assert!(
21417                rl.canonical_unit().is_some(),
21418                "canonical {canonical_window_secs}s window must resolve to \
21419                 Some on RateLimit::canonical_unit — the validate gate reads \
21420                 this accessor directly"
21421            );
21422        }
21423        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
21424            let mut s = three_member_spec();
21425            let rl = RateLimit {
21426                rate: 100,
21427                window: Duration::from_secs(non_canonical_window_secs),
21428            };
21429            s.politicas.rate_limit = Some(rl);
21430            assert_eq!(
21431                s.validate().unwrap_err(),
21432                AplicacaoError::PolicyRateLimitWindowNotCanonical {
21433                    window: rl.window(),
21434                },
21435                "non-canonical {non_canonical_window_secs}s window must be \
21436                 rejected by validate_politicas — the validate gate now \
21437                 keys off RateLimit::canonical_unit().is_none()"
21438            );
21439            assert!(
21440                rl.canonical_unit().is_none(),
21441                "non-canonical {non_canonical_window_secs}s window must \
21442                 resolve to None on RateLimit::canonical_unit — the two \
21443                 paths (the free helper the validate gate previously read \
21444                 and the substrate primitive the validate gate now reads) \
21445                 must agree on the same rejected set"
21446            );
21447        }
21448        // And the substrate-primitive [`RateLimit::canonical_unit`]
21449        // accessor's accepted-window set matches the codec's parse arm's
21450        // accepted-suffix set on every canonical / non-canonical shape,
21451        // so a future silent drift between the codec's accepted set and
21452        // the validate gate's accepted set is a build error at test time
21453        // (both consumers key off the same closed-set enum's `match self`
21454        // arms). The predecessor free helper `is_canonical_rate_limit_window`
21455        // — a delegate that composed [`RateLimitUnit::from_window`] with
21456        // `.is_some()` — was deleted after this migration; the
21457        // canonical-window set now lives on exactly one typed dispatch
21458        // on the substrate primitive.
21459        for (secs, expected) in [
21460            (1u64, true),
21461            (60, true),
21462            (3600, true),
21463            (2, false),
21464            (30, false),
21465            (86_400, false),
21466        ] {
21467            let window = Duration::from_secs(secs);
21468            let rl = RateLimit { rate: 1, window };
21469            assert_eq!(
21470                rl.canonical_unit().is_some(),
21471                expected,
21472                "RateLimit::canonical_unit().is_some() must agree with the \
21473                 codec-accepted canonical-window set on {secs}s"
21474            );
21475            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
21476                1 => "s",
21477                60 => "m",
21478                3600 => "h",
21479                _ => return,
21480            })
21481            .is_some_and(|d| d == window);
21482            if expected {
21483                assert!(
21484                    suffix_from_axis,
21485                    "the codec's `&str → Duration` axis \
21486                     ({secs}s) must round-trip to the same Duration the \
21487                     substrate primitive's accessor returns Some on"
21488                );
21489            }
21490        }
21491    }
21492
21493    #[test]
21494    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
21495        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
21496        // derive: for each of the three variants, exactly one of the
21497        // generated `is_second` / `is_minute` / `is_hour` predicates
21498        // returns `true` and the other two return `false`. Peer of
21499        // the sibling
21500        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
21501        // sibling `IsVariant`-derived closed-set typed-enum pins.
21502        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
21503            (super::RateLimitUnit::Second, [true, false, false]),
21504            (super::RateLimitUnit::Minute, [false, true, false]),
21505            (super::RateLimitUnit::Hour, [false, false, true]),
21506        ];
21507        for (variant, expected) in rows {
21508            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
21509            assert_eq!(
21510                observed, expected,
21511                "RateLimitUnit::{variant:?} is_* predicates must partition \
21512                 the arm set (second, minute, hour); got {observed:?}"
21513            );
21514        }
21515    }
21516
21517    #[test]
21518    fn rejects_policy_timeout_sub_millisecond() {
21519        // A purely sub-millisecond `Duration` (`from_micros(500)` =
21520        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
21521        // arm passes — but `as_millis() == 0`, so the shared codec's
21522        // `render` arm returns the literal `"0s"`, which the
21523        // codec's `parse` arm then deserializes as `Duration::ZERO`
21524        // and the `PolicyTimeoutZero` zero-floor gate would reject
21525        // on re-validate. Pin the rejection at the typed slot's
21526        // canonical-floor gate so the round-trip break surfaces at
21527        // validate time, naming the offending `Duration`, rather
21528        // than at the next serialize → deserialize round-trip far
21529        // from the source `caixa.lisp`.
21530        let mut s = three_member_spec();
21531        let timeout = Duration::from_micros(500);
21532        s.politicas.timeout = Some(timeout);
21533        assert_eq!(
21534            s.validate().unwrap_err(),
21535            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
21536        );
21537    }
21538
21539    #[test]
21540    fn rejects_policy_timeout_non_integer_millisecond() {
21541        // A `Duration` with non-integer-millisecond residue
21542        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
21543        // through the shared codec's `render` arm as `"1ms"` (the
21544        // `as_millis()` floor truncates), which the codec's `parse`
21545        // arm then deserializes as `Duration::from_millis(1)` =
21546        // 1_000_000 ns — silently *different* from the original.
21547        // Pin the rejection so this round-trip break surfaces at
21548        // validate time, where the offending `Duration` is named,
21549        // rather than as a silent value-laundered round-trip on the
21550        // next codec round-trip.
21551        let mut s = three_member_spec();
21552        let timeout = Duration::from_micros(1500);
21553        s.politicas.timeout = Some(timeout);
21554        assert_eq!(
21555            s.validate().unwrap_err(),
21556            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
21557        );
21558    }
21559
21560    #[test]
21561    fn accepts_policy_timeout_integer_millisecond_forms() {
21562        // The codec's accepted set — integer multiples of 1ms — is
21563        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
21564        // `1h` all pass the canonical gate. Pin the canonical-forms
21565        // sweep so a future tightening of the codec's grammar (e.g.
21566        // dropping `:ms`) surfaces here as a test failure rather
21567        // than a silent contract narrowing on the typed slot.
21568        for timeout in [
21569            Duration::from_millis(1),
21570            Duration::from_millis(500),
21571            Duration::from_millis(1500),
21572            Duration::from_secs(30),
21573            Duration::from_secs(120),
21574            Duration::from_secs(3600),
21575        ] {
21576            let mut s = three_member_spec();
21577            s.politicas.timeout = Some(timeout);
21578            s.validate()
21579                .expect("integer-millisecond :timeout must validate");
21580        }
21581    }
21582
21583    #[test]
21584    fn policy_timeout_zero_takes_precedence_over_canonical() {
21585        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
21586        // pass the canonical-millisecond gate; the more self-locating
21587        // `PolicyTimeoutZero` arm (which names the omit-axis
21588        // remediation directly) must fire first. Pin the ordering so
21589        // a future refactor that reorders the arms surfaces here as a
21590        // test failure rather than a silent diagnostic regression.
21591        let mut s = three_member_spec();
21592        s.politicas.timeout = Some(Duration::ZERO);
21593        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
21594    }
21595
21596    #[test]
21597    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
21598        // The diagnostic envelope carries the offending `Duration`
21599        // verbatim so the author can grep their `caixa.lisp` for
21600        // `:timeout "<value>"` and fix it in one edit. Same
21601        // diagnostic shape every other typed-slot canonical-form
21602        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
21603        // peer `:rate-limit :window` axis.
21604        let mut s = three_member_spec();
21605        let timeout = Duration::from_nanos(1_000_001);
21606        s.politicas.timeout = Some(timeout);
21607        match s.validate().unwrap_err() {
21608            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
21609                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
21610            }
21611            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
21612        }
21613    }
21614
21615    #[test]
21616    fn rejects_policy_timeout_above_cap() {
21617        // The fail-before-pass-after pin: 3601s = 1h + 1s is
21618        // structurally one canonical-tick past the
21619        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
21620        // integer-millisecond magnitude the canonical-form arm above
21621        // accepts cleanly, that the codec round-trips losslessly as
21622        // `"3601s"`, and that silently passed validate on every
21623        // pre-gate codebase because the typed slot's only checks were
21624        // the zero-floor and canonical-form arms. The mesh-level
21625        // deadline degenerates only at the runtime substrate (Envoy
21626        // / Cilium L7 timeout overlay) far from the source
21627        // `caixa.lisp` with no field naming the offending policy.
21628        let mut s = three_member_spec();
21629        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
21630        s.politicas.timeout = Some(timeout);
21631        assert_eq!(
21632            s.validate().unwrap_err(),
21633            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
21634        );
21635    }
21636
21637    #[test]
21638    fn rejects_policy_timeout_one_millisecond_above_cap() {
21639        // Boundary case: exactly 1ms past the cap (the granularity
21640        // the canonical-form gate enforces). Catches a future
21641        // "strictly less than" half-measure and pins the diagnostic
21642        // to name the offending `Duration` verbatim. Peer of
21643        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
21644        // boundary pin on the sibling `:limits :memory` top edge.
21645        let mut s = three_member_spec();
21646        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
21647        s.politicas.timeout = Some(timeout);
21648        assert_eq!(
21649            s.validate().unwrap_err(),
21650            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
21651        );
21652    }
21653
21654    #[test]
21655    fn rejects_policy_timeout_far_above_cap() {
21656        // The "obvious authoring footgun" case: a `(:timeout "24h")`
21657        // or `(:timeout "86400s")` — values the canonical-form arm
21658        // accepts as integer-millisecond magnitudes, the codec
21659        // round-trips losslessly through serde, but the mesh-level
21660        // policy cannot honor (a 24-hour synchronous-`:contratos`
21661        // deadline is operationally indistinguishable from
21662        // omit-the-axis). Until this gate landed validate accepted
21663        // it. Pin both common above-cap values (24h, 7d) so a future
21664        // relaxation that drops the upper bound surfaces here.
21665        for timeout in [
21666            Duration::from_secs(86_400),    // 24h
21667            Duration::from_secs(604_800),   // 7d
21668            Duration::from_secs(1_000_000), // ~11.5 days
21669        ] {
21670            let mut s = three_member_spec();
21671            s.politicas.timeout = Some(timeout);
21672            assert_eq!(
21673                s.validate().unwrap_err(),
21674                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
21675            );
21676        }
21677    }
21678
21679    #[test]
21680    fn accepts_policy_timeout_at_cap() {
21681        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
21682        // must validate. The cap is inclusive on the top edge,
21683        // matching the [`POLICY_RETRIES_MAX`] /
21684        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
21685        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
21686        // sibling capped axes. Pin the boundary explicitly so a
21687        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
21688        // instead of `>`) surfaces here as a test failure rather
21689        // than a silent contract narrowing.
21690        let mut s = three_member_spec();
21691        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
21692        s.validate()
21693            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
21694    }
21695
21696    #[test]
21697    fn accepts_policy_timeout_typical_values() {
21698        // The documented production-playbook band positive-control
21699        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
21700        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
21701        // plus a sweep through the long-running-workflow band
21702        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
21703        // validated set explicitly so a future tightening of the
21704        // ceiling surfaces here as a deliberate test edit, not a
21705        // silent contract narrowing.
21706        for timeout in [
21707            Duration::from_millis(1),
21708            Duration::from_millis(500),
21709            Duration::from_secs(1),
21710            Duration::from_secs(10),
21711            Duration::from_secs(15), // Envoy default
21712            Duration::from_secs(30),
21713            Duration::from_secs(60), // AWS App Mesh typical
21714            Duration::from_secs(300),
21715            Duration::from_secs(900),
21716            Duration::from_secs(1800),
21717            Duration::from_secs(3600), // exactly 1h, the cap
21718        ] {
21719            let mut s = three_member_spec();
21720            s.politicas.timeout = Some(timeout);
21721            s.validate()
21722                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
21723        }
21724    }
21725
21726    #[test]
21727    fn policy_timeout_zero_takes_precedence_over_cap() {
21728        // The cross-arm ordering pin: `Duration::ZERO` is
21729        // structurally outside both `>= 1ms` (zero-floor) and
21730        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
21731        // diagnostic is the more self-locating one (it directly
21732        // names the omit-axis remediation), so the validate gate
21733        // must fire on zero first. Same shape every other
21734        // zero-then-shape ordering on this surface uses
21735        // ([`AplicacaoError::PolicyRetriesZero`] then
21736        // [`AplicacaoError::PolicyRetriesExceedsCap`];
21737        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
21738        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
21739        let mut s = three_member_spec();
21740        s.politicas.timeout = Some(Duration::ZERO);
21741        assert_eq!(
21742            s.validate().unwrap_err(),
21743            AplicacaoError::PolicyTimeoutZero,
21744            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
21745        );
21746    }
21747
21748    #[test]
21749    fn policy_timeout_canonical_takes_precedence_over_cap() {
21750        // The cross-arm ordering pin: a `Duration` that is *both*
21751        // sub-millisecond (non-canonical-form) and structurally
21752        // above the cap surfaces the canonical-form diagnostic
21753        // first, because the round-trip-shape break is the more
21754        // fundamental issue (the value can't even round-trip
21755        // through the codec, so the cap diagnostic naming
21756        // `1ms..=1h` would be misleading — there's no integer-ms
21757        // form of the offending value). Pin the order so a future
21758        // refactor that reorders the arms surfaces here as a test
21759        // failure rather than a silent diagnostic regression.
21760        let mut s = three_member_spec();
21761        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
21762        // *and* total magnitude above the 1h cap.
21763        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
21764        s.politicas.timeout = Some(timeout);
21765        assert_eq!(
21766            s.validate().unwrap_err(),
21767            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
21768            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
21769        );
21770    }
21771
21772    #[test]
21773    fn policy_timeout_cap_diagnostic_carries_offending_value() {
21774        // The diagnostic-shape pin: the offending `Duration` is
21775        // carried verbatim into the
21776        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
21777        // surfaced error message names the value the author wrote
21778        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
21779        // exceeds the mesh-policy ceiling …"`), not just the cap.
21780        // Same self-locating diagnostic shape every other typed-cap
21781        // arm on this surface carries
21782        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
21783        // offending retry count verbatim).
21784        let mut s = three_member_spec();
21785        let timeout = Duration::from_secs(7200); // 2h
21786        s.politicas.timeout = Some(timeout);
21787        let err = s.validate().unwrap_err();
21788        assert!(
21789            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
21790            "got {err:?}"
21791        );
21792        let msg = err.to_string();
21793        assert!(
21794            msg.contains("7200"),
21795            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
21796        );
21797    }
21798
21799    #[test]
21800    fn policy_timeout_cap_pins_canonical_value() {
21801        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
21802        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
21803        // the shared duration codec emits as a clean canonical
21804        // string (`"<n>h"`). Pinning the literal value here surfaces
21805        // a future drift (a relaxation to 24h, a tightening to 5m)
21806        // as a deliberate test edit, not a silent contract
21807        // narrowing. Same shape every other typed-cap value pin on
21808        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
21809        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
21810        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
21811    }
21812
21813    #[test]
21814    fn policy_timeout_cap_value_round_trips_through_codec() {
21815        // The codec round-trip property the cap arm preserves: the
21816        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
21817        // the shared duration codec — every value at the cap renders
21818        // to a clean canonical string (`"1h"`) and parses back to
21819        // the same `Duration`. Pin this so a future drift between
21820        // the cap constant and the codec's largest emitted unit
21821        // surfaces here. Same shape every other typed boundary pin
21822        // on this surface uses
21823        // (`wasm32_memory_cap_matches_parsed_4_gib`).
21824        let policy = MeshPolicy {
21825            timeout: Some(POLICY_TIMEOUT_MAX),
21826            ..Default::default()
21827        };
21828        let json = serde_json::to_string(&policy).unwrap();
21829        // The codec emits `"1h"` for the canonical 1-hour magnitude.
21830        assert!(
21831            json.contains("\"1h\""),
21832            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
21833        );
21834        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
21835        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
21836    }
21837
21838    #[test]
21839    fn rejects_circuit_breaker_window_sub_millisecond() {
21840        // Peer of the `:timeout` sub-millisecond arm on the second
21841        // typed-`Duration` `:politicas` axis: a purely sub-ms
21842        // `Duration` (`from_micros(500)`) renders through the shared
21843        // codec as `"0s"`, which the codec parses back to
21844        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
21845        // zero-floor gate then rejects on re-validate.
21846        let mut s = three_member_spec();
21847        let window = Duration::from_micros(500);
21848        s.politicas.circuit_breaker = Some(CircuitBreaker {
21849            max_failures: 5,
21850            window,
21851        });
21852        assert_eq!(
21853            s.validate().unwrap_err(),
21854            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
21855        );
21856    }
21857
21858    #[test]
21859    fn rejects_circuit_breaker_window_non_integer_millisecond() {
21860        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
21861        // with non-integer-millisecond residue renders through the
21862        // shared codec as the truncated `"<n>ms"` form, parsing back
21863        // to a *different* `Duration` on the next round-trip.
21864        let mut s = three_member_spec();
21865        let window = Duration::from_micros(1500);
21866        s.politicas.circuit_breaker = Some(CircuitBreaker {
21867            max_failures: 5,
21868            window,
21869        });
21870        assert_eq!(
21871            s.validate().unwrap_err(),
21872            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
21873        );
21874    }
21875
21876    #[test]
21877    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
21878        // The canonical-forms sweep on the breaker axis: every
21879        // integer-ms multiple the codec round-trips losslessly
21880        // passes the canonical gate.
21881        //
21882        // Clears `:timeout` from the fixture so this per-axis sweep
21883        // covers windows shorter than the fixture's 30s timeout
21884        // (1ms, 500ms, 1500ms) — the sub-timeout arm is a
21885        // structurally-inert breaker
21886        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]) that
21887        // the cross-axis gate at the end of
21888        // [`AplicacaoSpec::validate_politicas`] rejects on the paired
21889        // `(:timeout, :window)` shape, not on the per-axis
21890        // integer-millisecond canonical-form shape this test pins.
21891        // The paired shape is covered by
21892        // `rejects_circuit_breaker_window_below_timeout`.
21893        for window in [
21894            Duration::from_millis(1),
21895            Duration::from_millis(500),
21896            Duration::from_millis(1500),
21897            Duration::from_secs(30),
21898            Duration::from_secs(60),
21899            Duration::from_secs(3600),
21900        ] {
21901            let mut s = three_member_spec();
21902            s.politicas.timeout = None;
21903            s.politicas.circuit_breaker = Some(CircuitBreaker {
21904                max_failures: 5,
21905                window,
21906            });
21907            s.validate()
21908                .expect("integer-millisecond :circuit-breaker :window must validate");
21909        }
21910    }
21911
21912    #[test]
21913    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
21914        // `Duration::ZERO` would pass the canonical-ms gate (the
21915        // sub-ns residue is zero) but must surface the narrower
21916        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
21917        // remediation.
21918        let mut s = three_member_spec();
21919        s.politicas.circuit_breaker = Some(CircuitBreaker {
21920            max_failures: 5,
21921            window: Duration::ZERO,
21922        });
21923        assert_eq!(
21924            s.validate().unwrap_err(),
21925            AplicacaoError::PolicyBreakerZeroWindow
21926        );
21927    }
21928
21929    #[test]
21930    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
21931        // Both axes invalid: max_failures == 0 *and* window is
21932        // sub-ms. The validate gate must fire on max_failures first
21933        // (matching the existing ordering pin
21934        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
21935        // the existing diagnostic continues to lead with the simpler
21936        // "zero threshold" framing.
21937        let mut s = three_member_spec();
21938        s.politicas.circuit_breaker = Some(CircuitBreaker {
21939            max_failures: 0,
21940            window: Duration::from_micros(500),
21941        });
21942        assert_eq!(
21943            s.validate().unwrap_err(),
21944            AplicacaoError::PolicyBreakerZeroFailures
21945        );
21946    }
21947
21948    #[test]
21949    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
21950        let mut s = three_member_spec();
21951        let window = Duration::from_nanos(60_000_000_001);
21952        s.politicas.circuit_breaker = Some(CircuitBreaker {
21953            max_failures: 5,
21954            window,
21955        });
21956        match s.validate().unwrap_err() {
21957            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
21958                assert_eq!(w, window, "diagnostic must carry the offending Duration");
21959            }
21960            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
21961        }
21962    }
21963
21964    #[test]
21965    fn rejects_circuit_breaker_window_above_cap() {
21966        // The fail-before-pass-after pin: 3601s = 1h + 1s is
21967        // structurally one canonical-tick past the
21968        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
21969        // integer-millisecond magnitude the canonical-form arm above
21970        // accepts cleanly, that the codec round-trips losslessly as
21971        // `"3601s"`, and that silently passed validate on every
21972        // pre-gate codebase because the typed slot's only checks were
21973        // the zero-floor and canonical-form arms. The
21974        // rolling-window-to-lifetime-counter degeneration surfaces
21975        // only at the runtime substrate (Envoy's outlier_detection
21976        // interval, the future CiliumClusterwideEnvoyConfig overlay)
21977        // far from the source `caixa.lisp` with no field naming the
21978        // offending policy.
21979        let mut s = three_member_spec();
21980        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
21981        s.politicas.circuit_breaker = Some(CircuitBreaker {
21982            max_failures: 5,
21983            window,
21984        });
21985        assert_eq!(
21986            s.validate().unwrap_err(),
21987            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
21988        );
21989    }
21990
21991    #[test]
21992    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
21993        // Boundary case: exactly 1ms past the cap (the granularity the
21994        // canonical-form gate enforces). Catches a future "strictly
21995        // less than" half-measure and pins the diagnostic to name the
21996        // offending `Duration` verbatim. Peer of
21997        // `rejects_policy_timeout_one_millisecond_above_cap` on the
21998        // sibling duration-typed `:politicas :timeout` top edge.
21999        let mut s = three_member_spec();
22000        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
22001        s.politicas.circuit_breaker = Some(CircuitBreaker {
22002            max_failures: 5,
22003            window,
22004        });
22005        assert_eq!(
22006            s.validate().unwrap_err(),
22007            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
22008        );
22009    }
22010
22011    #[test]
22012    fn rejects_circuit_breaker_window_far_above_cap() {
22013        // The "obvious authoring footgun" case: a `(:window "24h")` or
22014        // `(:window "86400s")` — values the canonical-form arm
22015        // accepts as integer-millisecond magnitudes, the codec
22016        // round-trips losslessly through serde, but the
22017        // rolling-window breaker contract cannot honor (a 24-hour
22018        // rolling failure window is operationally a lifetime counter).
22019        // Until this gate landed validate accepted it. Pin both common
22020        // above-cap values (24h, 7d) so a future relaxation that
22021        // drops the upper bound surfaces here.
22022        for window in [
22023            Duration::from_secs(86_400),    // 24h
22024            Duration::from_secs(604_800),   // 7d
22025            Duration::from_secs(1_000_000), // ~11.5 days
22026        ] {
22027            let mut s = three_member_spec();
22028            s.politicas.circuit_breaker = Some(CircuitBreaker {
22029                max_failures: 5,
22030                window,
22031            });
22032            assert_eq!(
22033                s.validate().unwrap_err(),
22034                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
22035            );
22036        }
22037    }
22038
22039    #[test]
22040    fn accepts_circuit_breaker_window_at_cap() {
22041        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
22042        // (1h) — must validate. The cap is inclusive on the top edge,
22043        // matching the [`POLICY_TIMEOUT_MAX`] /
22044        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
22045        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
22046        // sibling capped axes. Pin the boundary explicitly so a
22047        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
22048        // instead of `>`) surfaces here as a test failure rather than
22049        // a silent contract narrowing.
22050        let mut s = three_member_spec();
22051        s.politicas.circuit_breaker = Some(CircuitBreaker {
22052            max_failures: 5,
22053            window: POLICY_BREAKER_WINDOW_MAX,
22054        });
22055        s.validate()
22056            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
22057    }
22058
22059    #[test]
22060    fn accepts_circuit_breaker_window_typical_values() {
22061        // The documented production-playbook band positive-control
22062        // sweep — every value Hystrix / resilience4j / Istio / Envoy
22063        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
22064        // through the long-tail failure-detection band (15m, 30m, 1h)
22065        // the cap accepts. Pin the inclusive validated set explicitly
22066        // so a future tightening of the ceiling surfaces here as a
22067        // deliberate test edit, not a silent contract narrowing.
22068        //
22069        // Clears `:timeout` from the fixture so this per-axis sweep
22070        // covers windows shorter than the fixture's 30s timeout
22071        // (Hystrix's 10s default, resilience4j's 30s, and the
22072        // sub-second warm-up band) — every such value is a
22073        // structurally-inert breaker under the cross-axis gate at the
22074        // end of [`AplicacaoSpec::validate_politicas`]
22075        // ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]), and
22076        // the paired `(:timeout, :window)` shape is covered by
22077        // `rejects_circuit_breaker_window_below_timeout`; this
22078        // per-axis pin ranges only over the per-axis-bracket accept set.
22079        for window in [
22080            Duration::from_millis(1),
22081            Duration::from_millis(500),
22082            Duration::from_secs(1),
22083            Duration::from_secs(10), // Hystrix / Istio / Envoy default
22084            Duration::from_secs(30),
22085            Duration::from_secs(60),  // resilience4j typical
22086            Duration::from_secs(300), // AWS App Mesh typical
22087            Duration::from_secs(900),
22088            Duration::from_secs(1800),
22089            Duration::from_secs(3600), // exactly 1h, the cap
22090        ] {
22091            let mut s = three_member_spec();
22092            s.politicas.timeout = None;
22093            s.politicas.circuit_breaker = Some(CircuitBreaker {
22094                max_failures: 5,
22095                window,
22096            });
22097            s.validate()
22098                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
22099        }
22100    }
22101
22102    #[test]
22103    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
22104        // The cross-arm ordering pin: `Duration::ZERO` is structurally
22105        // outside both `>= 1ms` (zero-floor) and
22106        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
22107        // diagnostic is the more self-locating one (it directly names
22108        // the omit-axis remediation), so the validate gate must fire
22109        // on zero first. Same shape every other zero-then-cap
22110        // ordering on this surface uses
22111        // ([`AplicacaoError::PolicyTimeoutZero`] then
22112        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
22113        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
22114        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
22115        let mut s = three_member_spec();
22116        s.politicas.circuit_breaker = Some(CircuitBreaker {
22117            max_failures: 5,
22118            window: Duration::ZERO,
22119        });
22120        assert_eq!(
22121            s.validate().unwrap_err(),
22122            AplicacaoError::PolicyBreakerZeroWindow,
22123            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
22124        );
22125    }
22126
22127    #[test]
22128    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
22129        // The cross-arm ordering pin: a `Duration` that is *both*
22130        // sub-millisecond (non-canonical-form) and structurally above
22131        // the cap surfaces the canonical-form diagnostic first,
22132        // because the round-trip-shape break is the more fundamental
22133        // issue (the value can't even round-trip through the codec, so
22134        // the cap diagnostic naming `1ms..=1h` would be misleading —
22135        // there's no integer-ms form of the offending value). Pin the
22136        // order so a future refactor that reorders the arms surfaces
22137        // here as a test failure rather than a silent diagnostic
22138        // regression. Peer of
22139        // `policy_timeout_canonical_takes_precedence_over_cap` on the
22140        // sibling duration-typed `:politicas :timeout` axis.
22141        let mut s = three_member_spec();
22142        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
22143        s.politicas.circuit_breaker = Some(CircuitBreaker {
22144            max_failures: 5,
22145            window,
22146        });
22147        assert_eq!(
22148            s.validate().unwrap_err(),
22149            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
22150            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
22151        );
22152    }
22153
22154    #[test]
22155    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
22156        // The cross-arm ordering pin between the two breaker axes: a
22157        // `CircuitBreaker` whose *both* `max_failures` is above its
22158        // cap *and* `window` is above its cap surfaces the
22159        // max-failures cap diagnostic first, because the validate
22160        // gate visits the failures arm before the window arm. Pin the
22161        // order so a future refactor that reorders the breaker arms
22162        // surfaces here.
22163        let mut s = three_member_spec();
22164        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
22165        s.politicas.circuit_breaker = Some(CircuitBreaker {
22166            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
22167            window,
22168        });
22169        assert_eq!(
22170            s.validate().unwrap_err(),
22171            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
22172                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
22173            },
22174            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
22175        );
22176    }
22177
22178    #[test]
22179    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
22180        // The diagnostic-shape pin: the offending `Duration` is
22181        // carried verbatim into the
22182        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
22183        // the surfaced error message names the value the author wrote
22184        // (`":politicas :circuit-breaker :window (Duration { secs:
22185        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
22186        // just the cap. Same self-locating diagnostic shape every
22187        // other typed-cap arm on this surface carries
22188        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
22189        // offending `Duration` verbatim).
22190        let mut s = three_member_spec();
22191        let window = Duration::from_secs(7200); // 2h
22192        s.politicas.circuit_breaker = Some(CircuitBreaker {
22193            max_failures: 5,
22194            window,
22195        });
22196        let err = s.validate().unwrap_err();
22197        assert!(
22198            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
22199            "got {err:?}"
22200        );
22201        let msg = err.to_string();
22202        assert!(
22203            msg.contains("7200"),
22204            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
22205        );
22206    }
22207
22208    #[test]
22209    fn circuit_breaker_window_cap_pins_canonical_value() {
22210        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
22211        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
22212        // shared duration codec emits as a clean canonical string
22213        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
22214        // the sibling duration-typed `:politicas :timeout` axis (the
22215        // two duration-typed `:politicas` axes share a uniform top
22216        // edge). Pinning the literal value here surfaces a future
22217        // drift (a relaxation to 24h, a tightening to 5m) as a
22218        // deliberate test edit, not a silent contract narrowing. Same
22219        // shape every other typed-cap value pin on this surface uses
22220        // (`policy_timeout_cap_pins_canonical_value`).
22221        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
22222        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
22223        assert_eq!(
22224            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
22225            "the two duration-typed `:politicas` caps share the same top edge"
22226        );
22227    }
22228
22229    #[test]
22230    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
22231        // The codec round-trip property the cap arm preserves: the
22232        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
22233        // through the shared duration codec — every value at the cap
22234        // renders to a clean canonical string (`"1h"`) and parses back
22235        // to the same `Duration`. Pin this so a future drift between
22236        // the cap constant and the codec's largest emitted unit
22237        // surfaces here. Same shape every other typed boundary pin on
22238        // this surface uses
22239        // (`policy_timeout_cap_value_round_trips_through_codec`).
22240        let policy = MeshPolicy {
22241            circuit_breaker: Some(CircuitBreaker {
22242                max_failures: 5,
22243                window: POLICY_BREAKER_WINDOW_MAX,
22244            }),
22245            ..Default::default()
22246        };
22247        let json = serde_json::to_string(&policy).unwrap();
22248        // The codec emits `"1h"` for the canonical 1-hour magnitude.
22249        assert!(
22250            json.contains("\"1h\""),
22251            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
22252        );
22253        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
22254        assert_eq!(
22255            back.circuit_breaker.unwrap().window,
22256            POLICY_BREAKER_WINDOW_MAX
22257        );
22258    }
22259
22260    #[test]
22261    fn is_integer_millisecond_duration_predicate_tracks_codec() {
22262        // Pin the predicate's accepted set against the codec's
22263        // accepted set explicitly. The codec parses
22264        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
22265        // accepted value is an integer-millisecond multiple — so the
22266        // predicate must accept exactly that set. Same shape every
22267        // other predicate-on-the-typed-slot helper carries
22268        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
22269        // Read directly from the codec-owned predicate — the crate's
22270        // single source of truth every typed-`Duration` axis now routes
22271        // through via
22272        // [`crate::render::require_positive_canonical_bounded_duration`].
22273        use super::supervisor::duration_codec::is_integer_millisecond_duration;
22274        assert!(is_integer_millisecond_duration(Duration::ZERO));
22275        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
22276        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
22277        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
22278        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
22279        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
22280        // Non-integer-millisecond residue: rejected.
22281        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
22282        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
22283        assert!(!is_integer_millisecond_duration(Duration::from_micros(
22284            1500
22285        )));
22286        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
22287        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
22288            999_999
22289        )));
22290        // The 1-ns-past-1ms boundary: rejected (no longer a clean
22291        // integer-millisecond multiple).
22292        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
22293            1_000_001
22294        )));
22295    }
22296
22297    #[test]
22298    fn policy_timeout_validated_value_round_trips_through_codec() {
22299        // The structural property the canonical-ms gate enforces:
22300        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
22301        // round-trips losslessly through the shared `duration_codec`
22302        // (serialize → string → deserialize → equal value). Pin this
22303        // end-to-end so a future change to either side (the validate
22304        // gate's accepted granularity, the codec's parse/render unit
22305        // set) that breaks the alignment surfaces here. The
22306        // previous-state shape (typed slot accepts arbitrary
22307        // `Duration`, codec only round-trips integer-ms) would fail
22308        // this test for any `Duration::from_micros(1500)` timeout —
22309        // the validate gate now forecloses that.
22310        for timeout in [
22311            Duration::from_millis(1),
22312            Duration::from_millis(1500),
22313            Duration::from_secs(30),
22314            Duration::from_secs(3600),
22315        ] {
22316            let mut s = three_member_spec();
22317            s.politicas.timeout = Some(timeout);
22318            s.validate().unwrap();
22319            let json = serde_json::to_string(&s.politicas).unwrap();
22320            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
22321            assert_eq!(
22322                back.timeout, s.politicas.timeout,
22323                "every validated :timeout must round-trip losslessly through the codec"
22324            );
22325        }
22326    }
22327
22328    #[test]
22329    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
22330        // Peer of the `:timeout` round-trip property on the breaker
22331        // axis.
22332        //
22333        // Clears `:timeout` from the fixture so the round-trip pin
22334        // ranges over sub-timeout `Duration` values (1ms, 1500ms) the
22335        // cross-axis gate would otherwise reject as structurally-inert
22336        // breakers ([`AplicacaoError::PolicyBreakerWindowBelowTimeout`]);
22337        // the paired `(:timeout, :window)` cross-axis relation is
22338        // pinned separately by
22339        // `rejects_circuit_breaker_window_below_timeout`, and this
22340        // property is a pure serde-codec round-trip on the per-axis
22341        // slot.
22342        for window in [
22343            Duration::from_millis(1),
22344            Duration::from_millis(1500),
22345            Duration::from_secs(30),
22346            Duration::from_secs(3600),
22347        ] {
22348            let mut s = three_member_spec();
22349            s.politicas.timeout = None;
22350            s.politicas.circuit_breaker = Some(CircuitBreaker {
22351                max_failures: 5,
22352                window,
22353            });
22354            s.validate().unwrap();
22355            let json = serde_json::to_string(&s.politicas).unwrap();
22356            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
22357            assert_eq!(
22358                back.circuit_breaker.unwrap().window,
22359                window,
22360                "every validated :circuit-breaker :window must round-trip losslessly"
22361            );
22362        }
22363    }
22364
22365    #[test]
22366    fn rejects_circuit_breaker_window_below_timeout() {
22367        // The fail-before-pass-after pin on the cross-axis
22368        // `(:timeout, :circuit-breaker :window)` invariant. Each axis
22369        // is individually well-formed under its own per-axis bracket
22370        // (both integer-millisecond, both above the zero floor, both
22371        // below the cap), but the pair is a structurally-inert
22372        // breaker: a call dispatched at t=0 is declared failed at
22373        // t=30s, by which point the 10s rolling window open at
22374        // dispatch has already rolled twice, so no window can hold
22375        // a timeout-derived failure however high the call volume.
22376        //
22377        // Envoy's `outlier_detection.interval` against the per-route
22378        // request timeout carries the identical relation; Hystrix
22379        // ships the canonical ratio in its defaults (10s window
22380        // against a 1s timeout — a 10× ratio, not a 3× under-ratio).
22381        //
22382        // Pin both the diagnostic arm and the payload values so a
22383        // future re-shape of the arm surfaces here as a deliberate
22384        // test edit.
22385        let mut s = three_member_spec();
22386        s.politicas.timeout = Some(Duration::from_secs(30));
22387        s.politicas.circuit_breaker = Some(CircuitBreaker {
22388            max_failures: 5,
22389            window: Duration::from_secs(10),
22390        });
22391        assert_eq!(
22392            s.validate().unwrap_err(),
22393            AplicacaoError::PolicyBreakerWindowBelowTimeout {
22394                window: Duration::from_secs(10),
22395                timeout: Duration::from_secs(30),
22396            }
22397        );
22398    }
22399
22400    #[test]
22401    fn accepts_circuit_breaker_window_equal_to_timeout() {
22402        // Boundary pin: `:window == :timeout` is the smallest window
22403        // that structurally admits at least one full timeout-derived
22404        // failure before the rolling interval closes (the invariant
22405        // is `:window >= :timeout`, not strict inequality). Catches
22406        // a future off-by-one tightening that would drift the accept
22407        // set away from the codified [`MeshPolicy::breaker_window_
22408        // observes_timeout`] predicate.
22409        let mut s = three_member_spec();
22410        s.politicas.timeout = Some(Duration::from_secs(30));
22411        s.politicas.circuit_breaker = Some(CircuitBreaker {
22412            max_failures: 5,
22413            window: Duration::from_secs(30),
22414        });
22415        s.validate()
22416            .expect("window == timeout is the boundary accept case");
22417    }
22418
22419    #[test]
22420    fn accepts_circuit_breaker_window_above_timeout() {
22421        // Positive-control sweep across the production-playbook band —
22422        // Hystrix (1s timeout / 10s window, 10× ratio), Istio (5s /
22423        // 30s, 6×), Envoy (10s / 60s, 6×), resilience4j (30s / 300s,
22424        // 10×), AWS App Mesh (60s / 300s, 5×). Every pair a real
22425        // playbook recommends must validate under the cross-axis gate.
22426        for (timeout, window) in [
22427            (Duration::from_secs(1), Duration::from_secs(10)),
22428            (Duration::from_secs(5), Duration::from_secs(30)),
22429            (Duration::from_secs(10), Duration::from_secs(60)),
22430            (Duration::from_secs(30), Duration::from_secs(300)),
22431            (Duration::from_secs(60), Duration::from_secs(300)),
22432        ] {
22433            let mut s = three_member_spec();
22434            s.politicas.timeout = Some(timeout);
22435            s.politicas.circuit_breaker = Some(CircuitBreaker {
22436                max_failures: 5,
22437                window,
22438            });
22439            s.validate().unwrap_or_else(|e| {
22440                panic!(
22441                    "production-playbook pair timeout={timeout:?}/window={window:?} must \
22442                     validate; got {e:?}"
22443                )
22444            });
22445        }
22446    }
22447
22448    #[test]
22449    fn circuit_breaker_window_below_timeout_by_one_millisecond_rejected() {
22450        // Off-by-one boundary pin: a window exactly 1ms shy of the
22451        // timeout is still structurally inert under the invariant
22452        // (the dispatch-to-report lag is `timeout`, so the window
22453        // must span at least one such lag). Catches a future
22454        // strict-inequality relaxation that would silently drift
22455        // the accept boundary.
22456        let timeout = Duration::from_secs(30);
22457        let window = Duration::from_millis(29_999);
22458        let mut s = three_member_spec();
22459        s.politicas.timeout = Some(timeout);
22460        s.politicas.circuit_breaker = Some(CircuitBreaker {
22461            max_failures: 5,
22462            window,
22463        });
22464        assert_eq!(
22465            s.validate().unwrap_err(),
22466            AplicacaoError::PolicyBreakerWindowBelowTimeout { window, timeout }
22467        );
22468    }
22469
22470    #[test]
22471    fn cross_axis_gate_vacuous_when_timeout_absent() {
22472        // The predicate is vacuously `true` when `:timeout` is None —
22473        // a `:circuit-breaker` alone declares no relation to a
22474        // substrate-imposed deadline (the failure signal reaches the
22475        // breaker from the transport's own error surface, so no
22476        // dispatch-to-report lag is knowable at author time). Pin so
22477        // a future tightening that made the gate opinionated on
22478        // half-declared pairs surfaces here.
22479        let mut s = three_member_spec();
22480        s.politicas.timeout = None;
22481        s.politicas.circuit_breaker = Some(CircuitBreaker {
22482            max_failures: 5,
22483            window: Duration::from_millis(1),
22484        });
22485        s.validate().expect(
22486            "cross-axis gate must be vacuous when :timeout is None, however small :window is",
22487        );
22488    }
22489
22490    #[test]
22491    fn cross_axis_gate_vacuous_when_circuit_breaker_absent() {
22492        // Peer of the sibling `:timeout`-absent case: a `:timeout`
22493        // without a `:circuit-breaker` declares a per-call deadline
22494        // without any rolling-window failure accounting, so the pair
22495        // is undeclared and the cross-axis gate has nothing to check.
22496        let mut s = three_member_spec();
22497        s.politicas.timeout = Some(Duration::from_secs(3600));
22498        s.politicas.circuit_breaker = None;
22499        s.validate().expect(
22500            "cross-axis gate must be vacuous when :circuit-breaker is None, \
22501             however large :timeout is",
22502        );
22503    }
22504
22505    #[test]
22506    fn cross_axis_gate_runs_after_per_axis_brackets() {
22507        // Ordering pin: a pair whose window is *both* zero-floor-
22508        // violating and structurally below the timeout must surface
22509        // the per-axis zero-floor arm first — the zero-floor
22510        // diagnostic is more self-locating (its omit-axis remediation
22511        // is directly named), where the cross-axis arm would send the
22512        // author to reconcile two values one of which is not a
22513        // meaningful window at all. Same ordering discipline every
22514        // per-axis bracket carries internally (zero-floor before
22515        // canonical-form before cap).
22516        let mut s = three_member_spec();
22517        s.politicas.timeout = Some(Duration::from_secs(30));
22518        s.politicas.circuit_breaker = Some(CircuitBreaker {
22519            max_failures: 5,
22520            window: Duration::ZERO,
22521        });
22522        assert_eq!(
22523            s.validate().unwrap_err(),
22524            AplicacaoError::PolicyBreakerZeroWindow,
22525            "per-axis zero-floor arm must fire before the cross-axis gate"
22526        );
22527    }
22528
22529    #[test]
22530    fn breaker_window_observes_timeout_predicate_matches_gate_semantic() {
22531        // Equivalence pin: the substrate-canonical
22532        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
22533        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
22534        // arm must discriminate the same set on every pair covered
22535        // by their shared invariant. A future refactor of either
22536        // side that breaks the equivalence trips here rather than as
22537        // a divergence between the predicate's Boolean answer and
22538        // the validate gate's Ok/Err arm — the same
22539        // predicate-vs-gate coherence discipline the peer
22540        // [`PlacementStrategy::is_shard_keyed`] predicate carries
22541        // against `AplicacaoSpec::validate_placement`. The sweep
22542        // covers both arms of the invariant (below, equal, above)
22543        // and both vacuous arms (None `:timeout`, None
22544        // `:circuit-breaker`), so the equivalence holds
22545        // exhaustively over the axis-covered accept and reject sets.
22546        let cases: &[(Option<Duration>, Option<Duration>)] = &[
22547            (Some(Duration::from_secs(30)), Some(Duration::from_secs(10))),
22548            (Some(Duration::from_secs(30)), Some(Duration::from_secs(29))),
22549            (Some(Duration::from_secs(30)), Some(Duration::from_secs(30))),
22550            (Some(Duration::from_secs(30)), Some(Duration::from_secs(60))),
22551            (Some(Duration::from_secs(1)), Some(Duration::from_secs(10))),
22552            (None, Some(Duration::from_secs(1))),
22553            (Some(Duration::from_secs(30)), None),
22554            (None, None),
22555        ];
22556        for (timeout, window) in cases.iter().copied() {
22557            let politicas = MeshPolicy {
22558                timeout,
22559                circuit_breaker: window.map(|w| CircuitBreaker {
22560                    max_failures: 5,
22561                    window: w,
22562                }),
22563                ..Default::default()
22564            };
22565            let predicate = politicas.breaker_window_observes_timeout();
22566
22567            let mut s = three_member_spec();
22568            s.politicas = politicas.clone();
22569            let gate_ok = !matches!(
22570                s.validate(),
22571                Err(AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })
22572            );
22573
22574            assert_eq!(
22575                predicate, gate_ok,
22576                "predicate must agree with validate arm on pair \
22577                 (timeout={timeout:?}, window={window:?})"
22578            );
22579        }
22580    }
22581
22582    #[test]
22583    fn rejects_rate_limit_starves_circuit_breaker() {
22584        // The fail-before-pass-after pin on the cross-axis
22585        // `(:rate-limit, :circuit-breaker)` invariant. Each axis is
22586        // individually well-formed under its own per-axis bracket
22587        // (both above the zero floor, both below the cap, rate-limit
22588        // window canonical), but the pair is a structurally-inert
22589        // breaker: the token bucket admits `1 × 10s / 3600s` ≈ 0
22590        // calls per rolling breaker window, so no window can
22591        // accumulate five failures however catastrophic the upstream
22592        // failure rate.
22593        //
22594        // Envoy's `outlier_detection.consecutive_5xx` paired against
22595        // `local_rate_limit.token_bucket.max_tokens` /
22596        // `fill_interval` carries the identical relation; every
22597        // production playbook that pairs the two axes (Envoy, Istio,
22598        // AWS App Mesh, Kong) sizes the rate at or above the
22599        // breaker's minimum-request-volume threshold for exactly this
22600        // reason.
22601        //
22602        // Pin both the diagnostic arm and the payload values so a
22603        // future re-shape of the arm surfaces here as a deliberate
22604        // test edit. Clears `:timeout` so the sibling
22605        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] gate
22606        // does not fire first on the ordering-precedent it holds
22607        // over this arm.
22608        let mut s = three_member_spec();
22609        s.politicas.timeout = None;
22610        s.politicas.circuit_breaker = Some(CircuitBreaker {
22611            max_failures: 5,
22612            window: Duration::from_secs(10),
22613        });
22614        s.politicas.rate_limit = Some(RateLimit {
22615            rate: 1,
22616            window: Duration::from_secs(3600),
22617        });
22618        assert_eq!(
22619            s.validate().unwrap_err(),
22620            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22621                rate: 1,
22622                rl_window: Duration::from_secs(3600),
22623                max_failures: 5,
22624                cb_window: Duration::from_secs(10),
22625            }
22626        );
22627    }
22628
22629    #[test]
22630    fn accepts_rate_limit_can_trip_circuit_breaker() {
22631        // Positive-control sweep across the production-playbook band
22632        // — every pair a real playbook recommends where the rate
22633        // clearly admits enough calls per breaker window to reach
22634        // `:max-failures` must validate. Envoy default 5 failures
22635        // in 10s with 100/s (1000 calls / window, 200× the threshold),
22636        // Istio 5 in 30s with 50/s (1500 calls, 300×), Hystrix 20 in
22637        // 10s with 1000/s (10000 calls, 500×), AWS App Mesh 5 in
22638        // 300s with 10/s (3000 calls, 600×). Clears `:timeout` so
22639        // the sibling cross-axis arm is vacuous on this sweep.
22640        for (rate, rl_window, max_failures, cb_window) in [
22641            (
22642                100u32,
22643                Duration::from_secs(1),
22644                5u32,
22645                Duration::from_secs(10),
22646            ),
22647            (50, Duration::from_secs(1), 5, Duration::from_secs(30)),
22648            (1000, Duration::from_secs(1), 20, Duration::from_secs(10)),
22649            (10, Duration::from_secs(1), 5, Duration::from_secs(300)),
22650            (5000, Duration::from_secs(60), 50, Duration::from_secs(60)),
22651        ] {
22652            let mut s = three_member_spec();
22653            s.politicas.timeout = None;
22654            s.politicas.circuit_breaker = Some(CircuitBreaker {
22655                max_failures,
22656                window: cb_window,
22657            });
22658            s.politicas.rate_limit = Some(RateLimit {
22659                rate,
22660                window: rl_window,
22661            });
22662            s.validate().unwrap_or_else(|e| {
22663                panic!(
22664                    "production-playbook pair rate={rate}/{rl_window:?} \
22665                     max_failures={max_failures}/{cb_window:?} must validate; got {e:?}"
22666                )
22667            });
22668        }
22669    }
22670
22671    #[test]
22672    fn accepts_rate_limit_exactly_at_trip_threshold_per_cb_window() {
22673        // Boundary pin: `rate × cb_window == max_failures × rl_window`
22674        // is the smallest bucket capacity that structurally admits
22675        // exactly `max_failures` calls per rolling breaker window
22676        // (the invariant is `≥`, not strict inequality). Catches a
22677        // future off-by-one tightening to strict inequality that
22678        // would drift the accept set away from the codified
22679        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate.
22680        // 5 calls/s over a 1s breaker window == 5 max_failures.
22681        let mut s = three_member_spec();
22682        s.politicas.timeout = None;
22683        s.politicas.circuit_breaker = Some(CircuitBreaker {
22684            max_failures: 5,
22685            window: Duration::from_secs(1),
22686        });
22687        s.politicas.rate_limit = Some(RateLimit {
22688            rate: 5,
22689            window: Duration::from_secs(1),
22690        });
22691        s.validate()
22692            .expect("rate × cb_window == max_failures × rl_window is the boundary accept case");
22693    }
22694
22695    #[test]
22696    fn rejects_rate_limit_one_call_short_per_cb_window() {
22697        // Off-by-one boundary pin: exactly one call short of the trip
22698        // threshold per breaker window is still structurally inert
22699        // (the invariant is `≥`, so `<` refuses even a one-call
22700        // shortfall). 4 calls/s over a 1s window == 4 admissible
22701        // failures, one shy of the 5-`max_failures` threshold.
22702        // Catches a future strict-inequality relaxation that would
22703        // silently drift the accept boundary.
22704        let mut s = three_member_spec();
22705        s.politicas.timeout = None;
22706        s.politicas.circuit_breaker = Some(CircuitBreaker {
22707            max_failures: 5,
22708            window: Duration::from_secs(1),
22709        });
22710        s.politicas.rate_limit = Some(RateLimit {
22711            rate: 4,
22712            window: Duration::from_secs(1),
22713        });
22714        assert_eq!(
22715            s.validate().unwrap_err(),
22716            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
22717                rate: 4,
22718                rl_window: Duration::from_secs(1),
22719                max_failures: 5,
22720                cb_window: Duration::from_secs(1),
22721            }
22722        );
22723    }
22724
22725    #[test]
22726    fn cross_axis_starve_gate_vacuous_when_rate_limit_absent() {
22727        // The predicate is vacuously `true` when `:rate-limit` is
22728        // None — a `:circuit-breaker` alone declares no relation to
22729        // a substrate-imposed call rate (the failure signal reaches
22730        // the breaker from the transport's own error surface, at
22731        // whatever rate upstream callers push traffic). Pin so a
22732        // future tightening that made the gate opinionated on
22733        // half-declared pairs surfaces here.
22734        let mut s = three_member_spec();
22735        s.politicas.timeout = None;
22736        s.politicas.circuit_breaker = Some(CircuitBreaker {
22737            max_failures: 1000,
22738            window: Duration::from_millis(1),
22739        });
22740        s.politicas.rate_limit = None;
22741        s.validate().expect(
22742            "cross-axis starve gate must be vacuous when :rate-limit is None, \
22743             however high :max-failures and however small :window are",
22744        );
22745    }
22746
22747    #[test]
22748    fn cross_axis_starve_gate_vacuous_when_circuit_breaker_absent() {
22749        // Peer of the sibling `:rate-limit`-absent case: a
22750        // `:rate-limit` without a `:circuit-breaker` declares a
22751        // per-edge token-bucket rate without any failure counter to
22752        // starve, so the pair is undeclared and the cross-axis gate
22753        // has nothing to check.
22754        //
22755        // Also clears the fixture's `:retries` (which is `Some(3)`) so
22756        // the sibling cross-axis
22757        // [`AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst`] arm
22758        // (which reasons across the paired `(:retries, :rate-limit)`
22759        // pair independent of `:circuit-breaker`) is vacuous on this
22760        // pin — this test names the *starve* arm's vacuity on the
22761        // `:circuit-breaker`-absent case, not the burst arm's.
22762        let mut s = three_member_spec();
22763        s.politicas.timeout = None;
22764        s.politicas.retries = None;
22765        s.politicas.circuit_breaker = None;
22766        s.politicas.rate_limit = Some(RateLimit {
22767            rate: 1,
22768            window: Duration::from_secs(3600),
22769        });
22770        s.validate().expect(
22771            "cross-axis starve gate must be vacuous when :circuit-breaker is None, \
22772             however low :rate is",
22773        );
22774    }
22775
22776    #[test]
22777    fn cross_axis_starve_gate_runs_after_per_axis_brackets() {
22778        // Ordering pin: a pair whose rate is *both* zero-floor-
22779        // violating and structurally below the trip threshold must
22780        // surface the per-axis zero-floor arm first — the zero-floor
22781        // diagnostic is more self-locating (its omit-axis remediation
22782        // is directly named), where the cross-axis arm would send the
22783        // author to reconcile four values one of which is not a
22784        // meaningful rate at all. Same ordering discipline every
22785        // per-axis bracket carries internally (zero-floor before
22786        // canonical-form before cap), and the sibling cross-axis
22787        // `PolicyBreakerZeroWindow`-before-`PolicyBreakerWindowBelowTimeout`
22788        // ordering pins on the `(:timeout, :window)` pair.
22789        let mut s = three_member_spec();
22790        s.politicas.timeout = None;
22791        s.politicas.circuit_breaker = Some(CircuitBreaker {
22792            max_failures: 5,
22793            window: Duration::from_secs(10),
22794        });
22795        s.politicas.rate_limit = Some(RateLimit {
22796            rate: 0,
22797            window: Duration::from_secs(1),
22798        });
22799        assert_eq!(
22800            s.validate().unwrap_err(),
22801            AplicacaoError::PolicyRateLimitZero,
22802            "per-axis rate zero-floor arm must fire before the cross-axis starve gate"
22803        );
22804    }
22805
22806    #[test]
22807    fn cross_axis_starve_gate_runs_after_sibling_window_below_timeout_gate() {
22808        // Cross-axis ordering pin: a `:politicas` whose axes trip
22809        // BOTH cross-axis arms — `:window < :timeout` (the sibling
22810        // `PolicyBreakerWindowBelowTimeout` invariant) AND
22811        // `:rate-limit` starves the breaker within `:window` (this
22812        // arm) — must surface the timeout-relation diagnostic first.
22813        // The timeout arm is the per-call-deadline invariant every
22814        // synchronous edge carries whether or not `:rate-limit` is
22815        // declared, so its diagnostic is more self-locating; the
22816        // starve arm needs the reader to reason across three axes,
22817        // where the timeout arm names only two.
22818        //
22819        // A `{ timeout: 30s, window: 10s, rate: 1/h, max_failures: 5 }`
22820        // pair trips both: the window is below the timeout, and the
22821        // rate (1 call/hour) admits far fewer than 5 calls per 10s
22822        // breaker window.
22823        let mut s = three_member_spec();
22824        s.politicas.timeout = Some(Duration::from_secs(30));
22825        s.politicas.circuit_breaker = Some(CircuitBreaker {
22826            max_failures: 5,
22827            window: Duration::from_secs(10),
22828        });
22829        s.politicas.rate_limit = Some(RateLimit {
22830            rate: 1,
22831            window: Duration::from_secs(3600),
22832        });
22833        assert_eq!(
22834            s.validate().unwrap_err(),
22835            AplicacaoError::PolicyBreakerWindowBelowTimeout {
22836                window: Duration::from_secs(10),
22837                timeout: Duration::from_secs(30),
22838            },
22839            "sibling :window<:timeout cross-axis arm must fire before the \
22840             starve arm when both apply"
22841        );
22842    }
22843
22844    #[test]
22845    fn breaker_can_trip_under_rate_limit_predicate_matches_gate_semantic() {
22846        // Equivalence pin: the substrate-canonical
22847        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicate
22848        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
22849        // arm must discriminate the same set on every pair covered
22850        // by their shared invariant. A future refactor of either
22851        // side that breaks the equivalence trips here rather than as
22852        // a divergence between the predicate's Boolean answer and
22853        // the validate gate's Ok/Err arm — the same
22854        // predicate-vs-gate coherence discipline the sibling
22855        // [`MeshPolicy::breaker_window_observes_timeout`] predicate
22856        // carries against `AplicacaoSpec::validate_politicas`. The
22857        // sweep covers both arms of the invariant (strictly below,
22858        // exactly at, strictly above) and both vacuous arms (None
22859        // `:rate-limit`, None `:circuit-breaker`), so the
22860        // equivalence holds exhaustively over the axis-covered
22861        // accept and reject sets. Clears `:timeout` throughout so
22862        // the sibling `:window<:timeout` gate is vacuous on every
22863        // input.
22864        let rl = |rate: u32, secs: u64| {
22865            Some(RateLimit {
22866                rate,
22867                window: Duration::from_secs(secs),
22868            })
22869        };
22870        let cb = |max_failures: u32, secs: u64| {
22871            Some(CircuitBreaker {
22872                max_failures,
22873                window: Duration::from_secs(secs),
22874            })
22875        };
22876        let cases: &[(Option<RateLimit>, Option<CircuitBreaker>)] = &[
22877            // starving pairs (predicate = false, gate = Err)
22878            (rl(1, 3600), cb(5, 10)),
22879            (rl(4, 1), cb(5, 1)),
22880            // boundary + coherent pairs (predicate = true, gate = Ok)
22881            (rl(5, 1), cb(5, 1)),
22882            (rl(100, 1), cb(5, 10)),
22883            // vacuous arms
22884            (None, cb(5, 10)),
22885            (rl(1, 3600), None),
22886            (None, None),
22887        ];
22888        for (rate_limit, circuit_breaker) in cases.iter().copied() {
22889            let politicas = MeshPolicy {
22890                circuit_breaker,
22891                rate_limit,
22892                ..Default::default()
22893            };
22894            let predicate = politicas.breaker_can_trip_under_rate_limit();
22895
22896            let mut s = three_member_spec();
22897            s.politicas = politicas.clone();
22898            s.politicas.timeout = None;
22899            let gate_ok = !matches!(
22900                s.validate(),
22901                Err(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })
22902            );
22903
22904            assert_eq!(
22905                predicate, gate_ok,
22906                "predicate must agree with validate arm on pair \
22907                 (rate_limit={rate_limit:?}, circuit_breaker={circuit_breaker:?})"
22908            );
22909        }
22910    }
22911
22912    #[test]
22913    fn rejects_retries_saturate_breaker_trip_threshold() {
22914        // The fail-before-pass-after pin on the cross-axis
22915        // `(:retries, :circuit-breaker :max-failures)` invariant. Each
22916        // axis is individually well-formed under its own per-axis
22917        // bracket (both above the zero floor, both below the cap), but
22918        // the pair is a structurally-truncated retry policy: one
22919        // client's `retries + 1 = 4` failing attempts hit the trip
22920        // threshold on the third attempt, the breaker opens, and the
22921        // fourth attempt (the last declared retry) is blocked by the
22922        // open breaker — the substrate declared four attempts and
22923        // structurally allows three.
22924        //
22925        // Envoy's `retry_policy.num_retries` paired against
22926        // `outlier_detection.consecutive_5xx` carries the identical
22927        // relation; every production playbook that pairs the two axes
22928        // (Envoy, Istio, resilience4j, Hystrix) sizes the breaker's
22929        // trip threshold strictly above any single client's retry
22930        // budget so the breaker distinguishes one persistently-failing
22931        // client from sustained multi-client failure.
22932        //
22933        // Pin both the diagnostic arm and the payload values so a
22934        // future re-shape of the arm surfaces here as a deliberate
22935        // test edit. Clears `:timeout` and `:rate-limit` so the
22936        // sibling cross-axis
22937        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
22938        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`]
22939        // arms do not fire first on the ordering-precedent they hold
22940        // over this arm.
22941        let mut s = three_member_spec();
22942        s.politicas.timeout = None;
22943        s.politicas.retries = Some(3);
22944        s.politicas.circuit_breaker = Some(CircuitBreaker {
22945            max_failures: 3,
22946            window: Duration::from_secs(1),
22947        });
22948        s.politicas.rate_limit = None;
22949        assert_eq!(
22950            s.validate().unwrap_err(),
22951            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
22952                retries: 3,
22953                max_failures: 3,
22954            }
22955        );
22956    }
22957
22958    #[test]
22959    fn accepts_retries_below_breaker_trip_threshold() {
22960        // Positive-control sweep across the production-playbook band
22961        // — every pair a real playbook recommends where the breaker's
22962        // trip threshold is strictly above the client's retry budget
22963        // must validate. Envoy default `num_retries: 3` with
22964        // `consecutive_5xx: 5` (breaker admits one client's 4 attempts,
22965        // opens on multi-client failures beyond that); Istio
22966        // `attempts: 3` with `consecutive5xxErrors: 5`; Hystrix
22967        // `execution.isolation.thread.timeoutInMilliseconds` + 3
22968        // retries with `requestVolumeThreshold: 20`; AWS App Mesh
22969        // `maxRetries: 5` with a `maxEjectionPercent`-derived threshold
22970        // of 10; resilience4j 2 retries with `slidingWindowSize: 10`.
22971        // Clears `:timeout` and `:rate-limit` so the sibling cross-axis
22972        // arms are vacuous on this sweep.
22973        for (retries, max_failures) in [(1u32, 5u32), (3, 5), (3, 20), (5, 10), (2, 10), (10, 1000)]
22974        {
22975            let mut s = three_member_spec();
22976            s.politicas.timeout = None;
22977            s.politicas.retries = Some(retries);
22978            s.politicas.circuit_breaker = Some(CircuitBreaker {
22979                max_failures,
22980                window: Duration::from_secs(60),
22981            });
22982            s.politicas.rate_limit = None;
22983            s.validate().unwrap_or_else(|e| {
22984                panic!(
22985                    "production-playbook pair retries={retries} \
22986                     max_failures={max_failures} must validate; got {e:?}"
22987                )
22988            });
22989        }
22990    }
22991
22992    #[test]
22993    fn accepts_retries_exactly_at_boundary_below_trip_threshold() {
22994        // Boundary pin: `max_failures == retries + 1` is the smallest
22995        // trip threshold that admits one client's exhausted retries
22996        // through completion (the R+1th failure — the last declared
22997        // retry — trips the breaker exactly as it completes, so
22998        // retries fully executed). The invariant is `>`, not `>=`,
22999        // stated in the coherent direction `max_failures > retries`.
23000        // Catches a future off-by-one tightening to
23001        // `max_failures > retries + 1` that would drift the accept set
23002        // away from the codified
23003        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
23004        // predicate.
23005        let mut s = three_member_spec();
23006        s.politicas.timeout = None;
23007        s.politicas.retries = Some(3);
23008        s.politicas.circuit_breaker = Some(CircuitBreaker {
23009            max_failures: 4,
23010            window: Duration::from_secs(60),
23011        });
23012        s.politicas.rate_limit = None;
23013        s.validate()
23014            .expect("max_failures == retries + 1 is the boundary accept case");
23015    }
23016
23017    #[test]
23018    fn rejects_retries_equal_to_breaker_trip_threshold() {
23019        // Off-by-one boundary pin: exactly at the trip threshold is
23020        // still structurally truncating (the invariant is `>`, so `<=`
23021        // refuses even the tight boundary). `retries = 3` with
23022        // `max_failures = 3` means the breaker trips on the third
23023        // failure — the last declared retry attempt is blocked.
23024        // Catches a future relaxation to `>=` that would silently
23025        // drift the accept boundary.
23026        let mut s = three_member_spec();
23027        s.politicas.timeout = None;
23028        s.politicas.retries = Some(3);
23029        s.politicas.circuit_breaker = Some(CircuitBreaker {
23030            max_failures: 3,
23031            window: Duration::from_secs(60),
23032        });
23033        s.politicas.rate_limit = None;
23034        assert_eq!(
23035            s.validate().unwrap_err(),
23036            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23037                retries: 3,
23038                max_failures: 3,
23039            }
23040        );
23041    }
23042
23043    #[test]
23044    fn cross_axis_retries_gate_vacuous_when_retries_absent() {
23045        // The predicate is vacuously `true` when `:retries` is None —
23046        // a `:circuit-breaker` alone declares a failure counter whose
23047        // per-client attempt count is unconstrained by the substrate,
23048        // so no per-client saturation bound on failures-per-client-call
23049        // is knowable at author time. The substrate takes no position
23050        // on whether an omitted `:retries` axis means zero retries or
23051        // "the client picks its own retry policy" — either way, the
23052        // pair is undeclared and the cross-axis gate has nothing to
23053        // check. Pin so a future tightening that made the gate
23054        // opinionated on half-declared pairs surfaces here.
23055        let mut s = three_member_spec();
23056        s.politicas.timeout = None;
23057        s.politicas.retries = None;
23058        s.politicas.circuit_breaker = Some(CircuitBreaker {
23059            max_failures: 1,
23060            window: Duration::from_secs(60),
23061        });
23062        s.politicas.rate_limit = None;
23063        s.validate().expect(
23064            "cross-axis retries gate must be vacuous when :retries is None, \
23065             however low :max-failures is",
23066        );
23067    }
23068
23069    #[test]
23070    fn cross_axis_retries_gate_vacuous_when_circuit_breaker_absent() {
23071        // Peer of the sibling `:retries`-absent case: a `:retries`
23072        // without a `:circuit-breaker` declares a client-retry policy
23073        // with no failure counter to trip, so the pair is undeclared
23074        // and the cross-axis gate has nothing to check.
23075        let mut s = three_member_spec();
23076        s.politicas.timeout = None;
23077        s.politicas.retries = Some(POLICY_RETRIES_MAX);
23078        s.politicas.circuit_breaker = None;
23079        s.politicas.rate_limit = None;
23080        s.validate().expect(
23081            "cross-axis retries gate must be vacuous when :circuit-breaker is None, \
23082             however high :retries is",
23083        );
23084    }
23085
23086    #[test]
23087    fn cross_axis_retries_gate_runs_after_per_axis_brackets() {
23088        // Ordering pin: a pair whose retries is *both* zero-floor-
23089        // violating and structurally at-or-below the trip threshold
23090        // must surface the per-axis zero-floor arm first — the
23091        // zero-floor diagnostic is more self-locating (its omit-axis
23092        // remediation is directly named), where the cross-axis arm
23093        // would send the author to reconcile two values one of which
23094        // is not a meaningful retry count at all. Same ordering
23095        // discipline every per-axis bracket carries internally
23096        // (zero-floor before canonical-form before cap), and the
23097        // sibling cross-axis
23098        // `PolicyRateLimitZero`-before-`PolicyBreakerCannotTripUnderRateLimit`
23099        // ordering pins on the `(:rate-limit, :circuit-breaker)` pair.
23100        let mut s = three_member_spec();
23101        s.politicas.timeout = None;
23102        s.politicas.retries = Some(0);
23103        s.politicas.circuit_breaker = Some(CircuitBreaker {
23104            max_failures: 3,
23105            window: Duration::from_secs(60),
23106        });
23107        s.politicas.rate_limit = None;
23108        assert_eq!(
23109            s.validate().unwrap_err(),
23110            AplicacaoError::PolicyRetriesZero,
23111            "per-axis retries zero-floor arm must fire before the cross-axis retries gate"
23112        );
23113    }
23114
23115    #[test]
23116    fn cross_axis_retries_gate_runs_after_sibling_starve_gate() {
23117        // Cross-axis ordering pin: a `:politicas` whose axes trip
23118        // BOTH cross-axis arms — `:rate-limit` starves the breaker
23119        // within `:window` (the sibling
23120        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
23121        // `:retries + 1` saturates `:max-failures` (this arm) — must
23122        // surface the rate-limit-starve diagnostic first. The
23123        // rate-limit-starve arm reasons across the token-bucket
23124        // admission axis every rate-limited edge carries whether or
23125        // not `:retries` is declared, so its diagnostic is more
23126        // self-locating; the retries-saturate arm reasons across a
23127        // per-client retry-policy budget the starve arm does not
23128        // touch.
23129        //
23130        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
23131        // pair trips both: the rate structurally cannot deliver 5
23132        // failures per 10s breaker window, and simultaneously
23133        // one client's `retries + 1 = 6` attempts alone would
23134        // saturate the 5-`max_failures` threshold.
23135        let mut s = three_member_spec();
23136        s.politicas.timeout = None;
23137        s.politicas.retries = Some(5);
23138        s.politicas.circuit_breaker = Some(CircuitBreaker {
23139            max_failures: 5,
23140            window: Duration::from_secs(10),
23141        });
23142        s.politicas.rate_limit = Some(RateLimit {
23143            rate: 1,
23144            window: Duration::from_secs(3600),
23145        });
23146        assert_eq!(
23147            s.validate().unwrap_err(),
23148            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23149                rate: 1,
23150                rl_window: Duration::from_secs(3600),
23151                max_failures: 5,
23152                cb_window: Duration::from_secs(10),
23153            },
23154            "sibling :rate-limit-starve cross-axis arm must fire before the \
23155             retries-saturate arm when both apply"
23156        );
23157    }
23158
23159    #[test]
23160    fn retries_fit_under_breaker_trip_threshold_predicate_matches_gate_semantic() {
23161        // Equivalence pin: the substrate-canonical
23162        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`]
23163        // predicate and the [`AplicacaoSpec::validate_politicas`]
23164        // cross-axis arm must discriminate the same set on every pair
23165        // covered by their shared invariant. A future refactor of
23166        // either side that breaks the equivalence trips here rather
23167        // than as a divergence between the predicate's Boolean answer
23168        // and the validate gate's Ok/Err arm — the same
23169        // predicate-vs-gate coherence discipline the sibling
23170        // [`MeshPolicy::breaker_window_observes_timeout`] and
23171        // [`MeshPolicy::breaker_can_trip_under_rate_limit`] predicates
23172        // carry against `AplicacaoSpec::validate_politicas`. The
23173        // sweep covers both arms of the invariant (strictly below,
23174        // exactly at the boundary, strictly above) and both vacuous
23175        // arms (None `:retries`, None `:circuit-breaker`), so the
23176        // equivalence holds exhaustively over the axis-covered accept
23177        // and reject sets. Clears `:timeout` and `:rate-limit`
23178        // throughout so the sibling cross-axis arms are vacuous on
23179        // every input.
23180        let cb = |max_failures: u32| {
23181            Some(CircuitBreaker {
23182                max_failures,
23183                window: Duration::from_secs(60),
23184            })
23185        };
23186        let cases: &[(Option<u32>, Option<CircuitBreaker>)] = &[
23187            // saturating pairs (predicate = false, gate = Err)
23188            (Some(3), cb(3)),
23189            (Some(3), cb(1)),
23190            (Some(10), cb(5)),
23191            // boundary + coherent pairs (predicate = true, gate = Ok)
23192            (Some(3), cb(4)),
23193            (Some(1), cb(5)),
23194            (Some(3), cb(20)),
23195            // vacuous arms
23196            (None, cb(1)),
23197            (Some(10), None),
23198            (None, None),
23199        ];
23200        for (retries, circuit_breaker) in cases.iter().copied() {
23201            let politicas = MeshPolicy {
23202                retries,
23203                circuit_breaker,
23204                ..Default::default()
23205            };
23206            let predicate = politicas.retries_fit_under_breaker_trip_threshold();
23207
23208            let mut s = three_member_spec();
23209            s.politicas = politicas.clone();
23210            let gate_ok = !matches!(
23211                s.validate(),
23212                Err(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })
23213            );
23214
23215            assert_eq!(
23216                predicate, gate_ok,
23217                "predicate must agree with validate arm on pair \
23218                 (retries={retries:?}, circuit_breaker={circuit_breaker:?})"
23219            );
23220        }
23221    }
23222
23223    #[test]
23224    fn rejects_rate_limit_cannot_admit_retry_burst() {
23225        // The fail-before-pass-after pin on the cross-axis
23226        // `(:retries, :rate-limit)` invariant. Each axis is
23227        // individually well-formed under its own per-axis bracket (both
23228        // above the zero floor, both below the cap), but the pair is a
23229        // structurally-truncated retry policy: one client's
23230        // `retries + 1 = 6` failing attempts consume 6 tokens from a
23231        // bucket that admits at most 3 per refill window, so the fourth
23232        // attempt onward is 429ed by the local rate limiter and the
23233        // declared retry policy is silently truncated by the same rate
23234        // limiter it feeds through — the substrate declared six
23235        // attempts and structurally allows three.
23236        //
23237        // Envoy's `local_rate_limit.token_bucket.max_tokens` paired
23238        // against `retry_policy.num_retries` carries the identical
23239        // relation; every production playbook that pairs the two axes
23240        // (Envoy, Istio, resilience4j, AWS App Mesh) sizes the bucket
23241        // capacity strictly above any single client's retry budget so
23242        // the limiter distinguishes one client's declared retries from
23243        // sustained multi-client load.
23244        //
23245        // Pin both the diagnostic arm and the payload values so a
23246        // future re-shape of the arm surfaces here as a deliberate
23247        // test edit. Clears `:timeout` and `:circuit-breaker` so the
23248        // sibling cross-axis
23249        // [`AplicacaoError::PolicyBreakerWindowBelowTimeout`] /
23250        // [`AplicacaoError::PolicyBreakerCannotTripUnderRateLimit`] /
23251        // [`AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted`]
23252        // arms do not fire first on the ordering-precedent they hold
23253        // over this arm.
23254        let mut s = three_member_spec();
23255        s.politicas.timeout = None;
23256        s.politicas.retries = Some(5);
23257        s.politicas.circuit_breaker = None;
23258        s.politicas.rate_limit = Some(RateLimit {
23259            rate: 3,
23260            window: Duration::from_secs(1),
23261        });
23262        assert_eq!(
23263            s.validate().unwrap_err(),
23264            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
23265                retries: 5,
23266                rate: 3,
23267            }
23268        );
23269    }
23270
23271    #[test]
23272    fn accepts_rate_limit_admits_retry_burst() {
23273        // Positive-control sweep across the production-playbook band
23274        // — every pair a real playbook recommends where the bucket
23275        // capacity is strictly above the client's retry budget must
23276        // validate. Envoy default `num_retries: 3` with 100/s (100
23277        // tokens per window admits 4 attempts per client with 96 to
23278        // spare); Istio `attempts: 3` with 50/s (50 admits 4);
23279        // resilience4j 2 retries with 10/s (10 admits 3); AWS App
23280        // Mesh `maxRetries: 5` with 1000/s (1000 admits 6); Cloudflare
23281        // Enterprise 3 retries with 1_000_000/h (1M admits 4). Clears
23282        // `:timeout` and `:circuit-breaker` so the sibling cross-axis
23283        // arms are vacuous on this sweep.
23284        for (retries, rate, secs) in [
23285            (3u32, 100u32, 1u64),
23286            (3, 50, 1),
23287            (2, 10, 1),
23288            (5, 1000, 1),
23289            (3, 1_000_000, 3600),
23290            (10, POLICY_RATE_LIMIT_MAX, 1),
23291        ] {
23292            let mut s = three_member_spec();
23293            s.politicas.timeout = None;
23294            s.politicas.retries = Some(retries);
23295            s.politicas.circuit_breaker = None;
23296            s.politicas.rate_limit = Some(RateLimit {
23297                rate,
23298                window: Duration::from_secs(secs),
23299            });
23300            s.validate().unwrap_or_else(|e| {
23301                panic!(
23302                    "production-playbook pair retries={retries} rate={rate}/{secs}s \
23303                     must validate; got {e:?}"
23304                )
23305            });
23306        }
23307    }
23308
23309    #[test]
23310    fn accepts_rate_exactly_at_boundary_admits_retry_burst() {
23311        // Boundary pin: `rate == retries + 1` is the smallest bucket
23312        // capacity that structurally admits one client's exhausted
23313        // retries through completion (each attempt draws exactly one
23314        // token; `retries + 1` tokens available admits `retries + 1`
23315        // attempts, retries fully executed). The invariant is `>=`,
23316        // stated in the coherent direction `rate >= retries + 1`.
23317        // Catches a future off-by-one tightening to `rate > retries + 1`
23318        // that would drift the accept set away from the codified
23319        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate.
23320        let mut s = three_member_spec();
23321        s.politicas.timeout = None;
23322        s.politicas.retries = Some(3);
23323        s.politicas.circuit_breaker = None;
23324        s.politicas.rate_limit = Some(RateLimit {
23325            rate: 4,
23326            window: Duration::from_secs(1),
23327        });
23328        s.validate()
23329            .expect("rate == retries + 1 is the boundary accept case");
23330    }
23331
23332    #[test]
23333    fn rejects_rate_one_below_retry_burst() {
23334        // Off-by-one boundary pin: exactly one token short of the
23335        // retry burst is still structurally truncating (the invariant
23336        // is `>=`, so `<` refuses even a one-token shortfall).
23337        // `retries = 3` with `rate = 3` means one client's four
23338        // attempts consume four tokens from a three-token bucket —
23339        // the fourth attempt is 429ed. Catches a future relaxation to
23340        // `>` on the wrong side (`rate > retries`, accepting equal)
23341        // that would silently drift the accept boundary and admit a
23342        // structurally-truncated retry policy at the emit boundary.
23343        let mut s = three_member_spec();
23344        s.politicas.timeout = None;
23345        s.politicas.retries = Some(3);
23346        s.politicas.circuit_breaker = None;
23347        s.politicas.rate_limit = Some(RateLimit {
23348            rate: 3,
23349            window: Duration::from_secs(1),
23350        });
23351        assert_eq!(
23352            s.validate().unwrap_err(),
23353            AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
23354                retries: 3,
23355                rate: 3,
23356            }
23357        );
23358    }
23359
23360    #[test]
23361    fn cross_axis_burst_gate_vacuous_when_retries_absent() {
23362        // The predicate is vacuously `true` when `:retries` is None —
23363        // a `:rate-limit` alone declares a token-bucket rate whose
23364        // per-client attempt count is unconstrained by the substrate,
23365        // so no per-client saturation bound on tokens-per-client-call
23366        // is knowable at author time. The substrate takes no position
23367        // on whether an omitted `:retries` axis means zero retries or
23368        // "the client picks its own retry policy" — either way, the
23369        // pair is undeclared and the cross-axis gate has nothing to
23370        // check. Pin so a future tightening that made the gate
23371        // opinionated on half-declared pairs surfaces here.
23372        let mut s = three_member_spec();
23373        s.politicas.timeout = None;
23374        s.politicas.retries = None;
23375        s.politicas.circuit_breaker = None;
23376        s.politicas.rate_limit = Some(RateLimit {
23377            rate: 1,
23378            window: Duration::from_secs(1),
23379        });
23380        s.validate().expect(
23381            "cross-axis burst gate must be vacuous when :retries is None, \
23382             however low :rate is",
23383        );
23384    }
23385
23386    #[test]
23387    fn cross_axis_burst_gate_vacuous_when_rate_limit_absent() {
23388        // Peer of the sibling `:retries`-absent case: a `:retries`
23389        // without a `:rate-limit` declares a client-retry policy with
23390        // no rate limiter to saturate, so the pair is undeclared and
23391        // the cross-axis gate has nothing to check. Uses
23392        // [`POLICY_RETRIES_MAX`] to pin the vacuity across the widest
23393        // authored retry budget the per-axis cap admits — a `:retries
23394        // POLICY_RETRIES_MAX` alone must remain a clean pass whether
23395        // or not `:rate-limit` is declared.
23396        let mut s = three_member_spec();
23397        s.politicas.timeout = None;
23398        s.politicas.retries = Some(POLICY_RETRIES_MAX);
23399        s.politicas.circuit_breaker = None;
23400        s.politicas.rate_limit = None;
23401        s.validate().expect(
23402            "cross-axis burst gate must be vacuous when :rate-limit is None, \
23403             however high :retries is",
23404        );
23405    }
23406
23407    #[test]
23408    fn cross_axis_burst_gate_runs_after_per_axis_brackets() {
23409        // Ordering pin: a pair whose retries is *both* zero-floor-
23410        // violating and structurally below the retry-burst threshold
23411        // must surface the per-axis zero-floor arm first — the
23412        // zero-floor diagnostic is more self-locating (its omit-axis
23413        // remediation is directly named), where the cross-axis arm
23414        // would send the author to reconcile two values one of which
23415        // is not a meaningful retry count at all. Same ordering
23416        // discipline every per-axis bracket carries internally
23417        // (zero-floor before canonical-form before cap), and the
23418        // sibling cross-axis
23419        // `PolicyRetriesZero`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
23420        // ordering pin on the `(:retries, :max-failures)` pair.
23421        let mut s = three_member_spec();
23422        s.politicas.timeout = None;
23423        s.politicas.retries = Some(0);
23424        s.politicas.circuit_breaker = None;
23425        s.politicas.rate_limit = Some(RateLimit {
23426            rate: 1,
23427            window: Duration::from_secs(1),
23428        });
23429        assert_eq!(
23430            s.validate().unwrap_err(),
23431            AplicacaoError::PolicyRetriesZero,
23432            "per-axis retries zero-floor arm must fire before the cross-axis burst gate"
23433        );
23434    }
23435
23436    #[test]
23437    fn cross_axis_burst_gate_runs_after_sibling_starve_gate() {
23438        // Cross-axis ordering pin: a `:politicas` whose axes trip
23439        // BOTH cross-axis arms — `:rate-limit` starves the breaker
23440        // within `:window` (the sibling
23441        // `PolicyBreakerCannotTripUnderRateLimit` invariant) AND
23442        // `:retries + 1` exceeds the bucket capacity (this arm) —
23443        // must surface the rate-limit-starve diagnostic first. The
23444        // starve arm is the token-bucket admission invariant every
23445        // rate-limited edge carries against the breaker whether or
23446        // not `:retries` is declared, so its diagnostic is more
23447        // self-locating; the burst arm reasons across a per-client
23448        // retry-policy budget the starve arm does not touch. Same
23449        // "more foundational cross-axis first" ordering discipline the
23450        // sibling
23451        // `PolicyBreakerCannotTripUnderRateLimit`-before-`PolicyBreakerTripsBeforeRetriesExhausted`
23452        // pin on the peer pair carries.
23453        //
23454        // A `{ retries: 5, rate: 1/h, max_failures: 5, cb_window: 10s }`
23455        // pair trips both: the rate structurally cannot deliver 5
23456        // failures per 10s breaker window (starve arm), and
23457        // simultaneously one client's `retries + 1 = 6` attempts alone
23458        // would exhaust the 1-token bucket (burst arm).
23459        let mut s = three_member_spec();
23460        s.politicas.timeout = None;
23461        s.politicas.retries = Some(5);
23462        s.politicas.circuit_breaker = Some(CircuitBreaker {
23463            max_failures: 5,
23464            window: Duration::from_secs(10),
23465        });
23466        s.politicas.rate_limit = Some(RateLimit {
23467            rate: 1,
23468            window: Duration::from_secs(3600),
23469        });
23470        assert_eq!(
23471            s.validate().unwrap_err(),
23472            AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23473                rate: 1,
23474                rl_window: Duration::from_secs(3600),
23475                max_failures: 5,
23476                cb_window: Duration::from_secs(10),
23477            },
23478            "sibling :rate-limit-starve cross-axis arm must fire before the \
23479             burst arm when both apply"
23480        );
23481    }
23482
23483    #[test]
23484    fn cross_axis_burst_gate_runs_after_sibling_retries_saturate_gate() {
23485        // Cross-axis ordering pin: a `:politicas` whose axes trip
23486        // BOTH the retries-saturate arm and this burst arm — one
23487        // client's `retries + 1` failures saturate the breaker's trip
23488        // threshold (the sibling
23489        // `PolicyBreakerTripsBeforeRetriesExhausted` invariant) AND
23490        // `retries + 1` exceeds the bucket capacity (this arm) —
23491        // must surface the retries-saturate diagnostic first. The
23492        // saturate arm is the per-client-vs-breaker relation every
23493        // retry-with-breaker pair carries whether or not `:rate-limit`
23494        // is declared, so its diagnostic is more self-locating; the
23495        // burst arm reasons across the rate-limit token-bucket
23496        // admission axis the saturate arm does not touch. Same
23497        // "more foundational cross-axis first" ordering discipline
23498        // carries here.
23499        //
23500        // A `{ retries: 5, max_failures: 3, cb_window: 60s,
23501        // rate: 3/s }` pair trips both: the breaker's `max_failures
23502        // = 3` is `<= retries = 5` (saturate arm), and simultaneously
23503        // one client's `retries + 1 = 6` attempts alone would exhaust
23504        // the 3-token bucket (burst arm). Clears `:timeout` so the
23505        // sibling `:window<:timeout` gate is vacuous, and the
23506        // `(rate=3/s, max_failures=3, cb_window=60s)` triple keeps
23507        // the starve arm coherent (`3 × 60s >= 3 × 1s`) so it is not
23508        // the arm that fires first.
23509        let mut s = three_member_spec();
23510        s.politicas.timeout = None;
23511        s.politicas.retries = Some(5);
23512        s.politicas.circuit_breaker = Some(CircuitBreaker {
23513            max_failures: 3,
23514            window: Duration::from_secs(60),
23515        });
23516        s.politicas.rate_limit = Some(RateLimit {
23517            rate: 3,
23518            window: Duration::from_secs(1),
23519        });
23520        assert_eq!(
23521            s.validate().unwrap_err(),
23522            AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23523                retries: 5,
23524                max_failures: 3,
23525            },
23526            "sibling :retries-saturate cross-axis arm must fire before the \
23527             burst arm when both apply"
23528        );
23529    }
23530
23531    #[test]
23532    fn rate_limit_admits_retry_burst_predicate_matches_gate_semantic() {
23533        // Equivalence pin: the substrate-canonical
23534        // [`MeshPolicy::rate_limit_admits_retry_burst`] predicate and
23535        // the [`AplicacaoSpec::validate_politicas`] cross-axis arm
23536        // must discriminate the same set on every pair covered by
23537        // their shared invariant. A future refactor of either side
23538        // that breaks the equivalence trips here rather than as a
23539        // divergence between the predicate's Boolean answer and the
23540        // validate gate's Ok/Err arm — the same predicate-vs-gate
23541        // coherence discipline the three sibling cross-axis
23542        // predicates ([`MeshPolicy::breaker_window_observes_timeout`],
23543        // [`MeshPolicy::breaker_can_trip_under_rate_limit`],
23544        // [`MeshPolicy::retries_fit_under_breaker_trip_threshold`])
23545        // carry against `AplicacaoSpec::validate_politicas`. The sweep
23546        // covers both arms of the invariant (strictly below, exactly
23547        // at the boundary, strictly above) and both vacuous arms
23548        // (None `:retries`, None `:rate-limit`), so the equivalence
23549        // holds exhaustively over the axis-covered accept and reject
23550        // sets. Clears `:timeout` and `:circuit-breaker` throughout
23551        // so the three sibling cross-axis arms are vacuous on every
23552        // input.
23553        let rl = |rate: u32, secs: u64| {
23554            Some(RateLimit {
23555                rate,
23556                window: Duration::from_secs(secs),
23557            })
23558        };
23559        let cases: &[(Option<u32>, Option<RateLimit>)] = &[
23560            // burst-exceeding pairs (predicate = false, gate = Err)
23561            (Some(3), rl(3, 1)),
23562            (Some(5), rl(1, 1)),
23563            (Some(10), rl(5, 1)),
23564            // boundary + coherent pairs (predicate = true, gate = Ok)
23565            (Some(3), rl(4, 1)),
23566            (Some(1), rl(5, 1)),
23567            (Some(3), rl(1_000_000, 3600)),
23568            // vacuous arms
23569            (None, rl(1, 1)),
23570            (Some(10), None),
23571            (None, None),
23572        ];
23573        for (retries, rate_limit) in cases.iter().copied() {
23574            let politicas = MeshPolicy {
23575                retries,
23576                rate_limit,
23577                ..Default::default()
23578            };
23579            let predicate = politicas.rate_limit_admits_retry_burst();
23580
23581            let mut s = three_member_spec();
23582            s.politicas = politicas.clone();
23583            let gate_ok = !matches!(
23584                s.validate(),
23585                Err(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { .. })
23586            );
23587
23588            assert_eq!(
23589                predicate, gate_ok,
23590                "predicate must agree with validate arm on pair \
23591                 (retries={retries:?}, rate_limit={rate_limit:?})"
23592            );
23593        }
23594    }
23595
23596    /// Sweep body shared by every `first_cross_axis_violation` ≡ gate
23597    /// equivalence pin — assert that on each `(label, politicas,
23598    /// expected)` case the substrate-canonical fold and the validate
23599    /// cascade agree byte-for-byte. Extracted so each pin's own body
23600    /// stays under `clippy::too_many_lines`.
23601    fn assert_first_cross_axis_violation_agrees_with_gate(
23602        cases: &[(&str, MeshPolicy, Option<AplicacaoError>)],
23603    ) {
23604        for (label, politicas, expected) in cases {
23605            let fold = politicas.first_cross_axis_violation();
23606            assert_eq!(
23607                fold.as_ref(),
23608                expected.as_ref(),
23609                "fold must return {expected:?} on `{label}`; got {fold:?}"
23610            );
23611
23612            let mut s = three_member_spec();
23613            s.politicas = politicas.clone();
23614            let gate = s.validate();
23615            match expected {
23616                None => {
23617                    // No cross-axis violation: validate must pass (the
23618                    // per-axis brackets pass by construction on every
23619                    // fixture above; every fixture's non-`:politicas`
23620                    // slots come from `three_member_spec`).
23621                    gate.as_ref()
23622                        .unwrap_or_else(|e| panic!("`{label}` must validate cleanly; got {e:?}"));
23623                }
23624                Some(want) => {
23625                    let got =
23626                        gate.expect_err(&format!("`{label}` must surface a cross-axis violation"));
23627                    assert_eq!(
23628                        &got, want,
23629                        "validate cross-axis cascade must return {want:?} on `{label}`; got {got:?}"
23630                    );
23631                }
23632            }
23633        }
23634    }
23635
23636    #[test]
23637    fn first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes() {
23638        // Equivalence pin on the compound cross-axis fold: the
23639        // substrate-canonical [`MeshPolicy::first_cross_axis_violation`]
23640        // and the [`AplicacaoSpec::validate_politicas`] cross-axis
23641        // cascade must return identical `AplicacaoError` variants on
23642        // every axis-covered input — the "compound-fold ≡ gate"
23643        // contract that generalizes the four sibling per-arm pins
23644        // onto the compound primitive that folds all four. A future
23645        // refactor of either side that breaks the equivalence trips
23646        // here rather than as a divergence between what the substrate
23647        // primitive answers and what `feira build` accepts.
23648        //
23649        // Half-A of the sweep: every single-arm violation (one arm
23650        // fires with the three sibling arms vacuous), the vacuous
23651        // shape (empty policy — no arm fires), and the fully-coherent
23652        // shape (every axis declared inside the coherence surface —
23653        // no arm fires). Half-B (pairwise-ordering coverage — the
23654        // "which arm wins when two apply" contract) lives in the
23655        // sibling `first_cross_axis_violation_matches_gate_on_pairwise_orderings`
23656        // pin; splitting keeps each pin's body under
23657        // `clippy::too_many_lines`.
23658        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
23659            max_failures,
23660            window: Duration::from_secs(secs),
23661        };
23662        let rl = |rate: u32, secs: u64| RateLimit {
23663            rate,
23664            window: Duration::from_secs(secs),
23665        };
23666        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23667            (
23668                "window-below-timeout only",
23669                MeshPolicy {
23670                    timeout: Some(Duration::from_secs(30)),
23671                    circuit_breaker: Some(cb(5, 10)),
23672                    ..Default::default()
23673                },
23674                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23675                    window: Duration::from_secs(10),
23676                    timeout: Duration::from_secs(30),
23677                }),
23678            ),
23679            (
23680                "starve only",
23681                MeshPolicy {
23682                    rate_limit: Some(rl(1, 3600)),
23683                    circuit_breaker: Some(cb(5, 10)),
23684                    ..Default::default()
23685                },
23686                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23687                    rate: 1,
23688                    rl_window: Duration::from_secs(3600),
23689                    max_failures: 5,
23690                    cb_window: Duration::from_secs(10),
23691                }),
23692            ),
23693            (
23694                "retries-saturate only",
23695                MeshPolicy {
23696                    retries: Some(3),
23697                    circuit_breaker: Some(cb(3, 60)),
23698                    ..Default::default()
23699                },
23700                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23701                    retries: 3,
23702                    max_failures: 3,
23703                }),
23704            ),
23705            (
23706                "retries-burst only",
23707                MeshPolicy {
23708                    retries: Some(5),
23709                    rate_limit: Some(rl(3, 1)),
23710                    ..Default::default()
23711                },
23712                Some(AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
23713                    retries: 5,
23714                    rate: 3,
23715                }),
23716            ),
23717            ("empty policy", MeshPolicy::default(), None),
23718            (
23719                "fully-coherent policy",
23720                MeshPolicy {
23721                    timeout: Some(Duration::from_secs(30)),
23722                    retries: Some(3),
23723                    circuit_breaker: Some(cb(5, 60)),
23724                    mtls_required: Some(true),
23725                    rate_limit: Some(rl(100, 1)),
23726                },
23727                None,
23728            ),
23729        ];
23730        assert_first_cross_axis_violation_agrees_with_gate(cases);
23731    }
23732
23733    #[test]
23734    fn first_cross_axis_violation_matches_gate_on_pairwise_orderings() {
23735        // Half-B of the compound-fold ≡ gate equivalence pin: the
23736        // load-bearing pairwise-ordering coverage. Every ordered pair
23737        // of the four cross-axis arms — six combinations — where two
23738        // arms are simultaneously eligible must surface the
23739        // more-foundational arm's diagnostic verbatim. Pins the fold's
23740        // arm-ordering byte-for-byte against the validate cascade's
23741        // arm-ordering, so a future reshuffle of either side that
23742        // silently drifts the ordering trips here rather than as a
23743        // per-arm miss the sibling per-arm `_predicate_matches_gate_semantic`
23744        // pins cannot catch (they clear every sibling arm, so their
23745        // sweeps are pairwise-ordering-agnostic by construction).
23746        //
23747        // The six pairs the four-arm cascade admits:
23748        // window-before-starve, window-before-saturate,
23749        // window-before-burst, starve-before-saturate,
23750        // starve-before-burst, saturate-before-burst.
23751        let cb = |max_failures: u32, secs: u64| CircuitBreaker {
23752            max_failures,
23753            window: Duration::from_secs(secs),
23754        };
23755        let rl = |rate: u32, secs: u64| RateLimit {
23756            rate,
23757            window: Duration::from_secs(secs),
23758        };
23759        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23760            (
23761                "window+starve → window wins",
23762                MeshPolicy {
23763                    timeout: Some(Duration::from_secs(30)),
23764                    rate_limit: Some(rl(1, 3600)),
23765                    circuit_breaker: Some(cb(5, 10)),
23766                    ..Default::default()
23767                },
23768                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23769                    window: Duration::from_secs(10),
23770                    timeout: Duration::from_secs(30),
23771                }),
23772            ),
23773            (
23774                "window+retries-saturate → window wins",
23775                MeshPolicy {
23776                    timeout: Some(Duration::from_secs(30)),
23777                    retries: Some(5),
23778                    circuit_breaker: Some(cb(3, 10)),
23779                    ..Default::default()
23780                },
23781                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23782                    window: Duration::from_secs(10),
23783                    timeout: Duration::from_secs(30),
23784                }),
23785            ),
23786            (
23787                "window+retries-burst → window wins",
23788                MeshPolicy {
23789                    timeout: Some(Duration::from_secs(30)),
23790                    retries: Some(5),
23791                    rate_limit: Some(rl(3, 1)),
23792                    circuit_breaker: Some(cb(5, 10)),
23793                    ..Default::default()
23794                },
23795                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23796                    window: Duration::from_secs(10),
23797                    timeout: Duration::from_secs(30),
23798                }),
23799            ),
23800            (
23801                "starve+retries-saturate → starve wins",
23802                MeshPolicy {
23803                    retries: Some(5),
23804                    rate_limit: Some(rl(1, 3600)),
23805                    circuit_breaker: Some(cb(5, 10)),
23806                    ..Default::default()
23807                },
23808                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23809                    rate: 1,
23810                    rl_window: Duration::from_secs(3600),
23811                    max_failures: 5,
23812                    cb_window: Duration::from_secs(10),
23813                }),
23814            ),
23815            (
23816                "starve+retries-burst → starve wins",
23817                MeshPolicy {
23818                    retries: Some(5),
23819                    rate_limit: Some(rl(1, 3600)),
23820                    circuit_breaker: Some(cb(10, 10)),
23821                    ..Default::default()
23822                },
23823                Some(AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
23824                    rate: 1,
23825                    rl_window: Duration::from_secs(3600),
23826                    max_failures: 10,
23827                    cb_window: Duration::from_secs(10),
23828                }),
23829            ),
23830            (
23831                "retries-saturate+retries-burst → saturate wins",
23832                MeshPolicy {
23833                    retries: Some(5),
23834                    rate_limit: Some(rl(3, 1)),
23835                    circuit_breaker: Some(cb(3, 60)),
23836                    ..Default::default()
23837                },
23838                Some(AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
23839                    retries: 5,
23840                    max_failures: 3,
23841                }),
23842            ),
23843        ];
23844        assert_first_cross_axis_violation_agrees_with_gate(cases);
23845    }
23846
23847    /// Sweep body shared by every `MeshPolicy::validate` ≡ gate
23848    /// equivalence pin — assert that on each `(label, politicas,
23849    /// expected)` case both the substrate primitive
23850    /// [`MeshPolicy::validate`] and the [`AplicacaoSpec::validate_politicas`]
23851    /// cascade (reached through `AplicacaoSpec::validate`, keying off the
23852    /// same `three_member_spec` fixture whose non-`:politicas` slots
23853    /// always validate cleanly) return identical `AplicacaoError` variants.
23854    /// Peer of [`assert_first_cross_axis_violation_agrees_with_gate`] on
23855    /// the sibling cross-axis-only surface — extended here onto the
23856    /// compound per-axis + cross-axis entry gate. Extracted so each pin's
23857    /// own body stays under `clippy::too_many_lines`.
23858    fn assert_validate_matches_gate(cases: &[(&str, MeshPolicy, Option<AplicacaoError>)]) {
23859        for (label, politicas, expected) in cases {
23860            let direct = politicas.validate();
23861            match (expected, &direct) {
23862                (None, Ok(())) => {}
23863                (None, Err(got)) => {
23864                    panic!("`{label}`: MeshPolicy::validate must pass; got {got:?}")
23865                }
23866                (Some(want), Ok(())) => {
23867                    panic!("`{label}`: MeshPolicy::validate must return {want:?}; got Ok")
23868                }
23869                (Some(want), Err(got)) => assert_eq!(
23870                    got, want,
23871                    "`{label}`: MeshPolicy::validate must return {want:?}; got {got:?}"
23872                ),
23873            }
23874
23875            let mut s = three_member_spec();
23876            s.politicas = politicas.clone();
23877            let gate = s.validate();
23878            match (expected, &gate) {
23879                (None, Ok(())) => {}
23880                (None, Err(got)) => {
23881                    panic!("`{label}`: validate_politicas gate must pass; got {got:?}")
23882                }
23883                (Some(want), Ok(())) => {
23884                    panic!("`{label}`: validate_politicas gate must return {want:?}; got Ok")
23885                }
23886                (Some(want), Err(got)) => assert_eq!(
23887                    got, want,
23888                    "`{label}`: validate_politicas gate must return {want:?}; got {got:?}"
23889                ),
23890            }
23891        }
23892    }
23893
23894    #[test]
23895    fn validate_matches_gate_on_per_axis_and_phase_boundary_shapes() {
23896        // Half-A of the compound-per-axis-+-cross-axis-fold ≡ gate
23897        // equivalence pin on [`MeshPolicy::validate`]: the four per-axis
23898        // zero-floor arms (`:timeout`, `:retries`, `:circuit-breaker
23899        // :max-failures`, `:rate-limit` rate) that discriminate the
23900        // "per-axis phase fires" arm of the compound gate, plus one
23901        // per-axis-before-cross-axis case (`{ timeout: 30s, cb.window:
23902        // ZERO }`) that pins the phase-boundary ordering — the per-axis
23903        // `PolicyBreakerZeroWindow` arm strictly precedes the cross-axis
23904        // `PolicyBreakerWindowBelowTimeout` arm, so the zero-window
23905        // diagnostic wins over the window-below-timeout diagnostic. Peer
23906        // of the sibling
23907        // `first_cross_axis_violation_matches_gate_on_single_arm_and_vacuous_shapes`
23908        // + `_on_pairwise_orderings` pins on the compound cross-axis
23909        // fold, extended here onto the outer compound entry gate that
23910        // folds per-axis + cross-axis surfaces. Half-B (cross-axis and
23911        // clean-pass surfaces) lives in the sibling
23912        // `validate_matches_gate_on_cross_axis_and_clean_pass_shapes`
23913        // pin; splitting keeps each pin's body under
23914        // `clippy::too_many_lines`.
23915        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23916            (
23917                "per-axis: timeout zero",
23918                MeshPolicy {
23919                    timeout: Some(Duration::ZERO),
23920                    ..Default::default()
23921                },
23922                Some(AplicacaoError::PolicyTimeoutZero),
23923            ),
23924            (
23925                "per-axis: retries zero",
23926                MeshPolicy {
23927                    retries: Some(0),
23928                    ..Default::default()
23929                },
23930                Some(AplicacaoError::PolicyRetriesZero),
23931            ),
23932            (
23933                "per-axis: breaker max-failures zero",
23934                MeshPolicy {
23935                    circuit_breaker: Some(CircuitBreaker {
23936                        max_failures: 0,
23937                        window: Duration::from_secs(60),
23938                    }),
23939                    ..Default::default()
23940                },
23941                Some(AplicacaoError::PolicyBreakerZeroFailures),
23942            ),
23943            (
23944                "per-axis: rate-limit rate zero",
23945                MeshPolicy {
23946                    rate_limit: Some(RateLimit {
23947                        rate: 0,
23948                        window: Duration::from_secs(1),
23949                    }),
23950                    ..Default::default()
23951                },
23952                Some(AplicacaoError::PolicyRateLimitZero),
23953            ),
23954            (
23955                "per-axis before cross-axis: zero-window wins over window-below-timeout",
23956                MeshPolicy {
23957                    timeout: Some(Duration::from_secs(30)),
23958                    circuit_breaker: Some(CircuitBreaker {
23959                        max_failures: 5,
23960                        window: Duration::ZERO,
23961                    }),
23962                    ..Default::default()
23963                },
23964                Some(AplicacaoError::PolicyBreakerZeroWindow),
23965            ),
23966        ];
23967        assert_validate_matches_gate(cases);
23968    }
23969
23970    #[test]
23971    fn validate_matches_gate_on_cross_axis_and_clean_pass_shapes() {
23972        // Half-B of the compound-per-axis-+-cross-axis-fold ≡ gate
23973        // equivalence pin on [`MeshPolicy::validate`]: the cross-axis
23974        // arm that discriminates the "cross-axis phase fires" arm of
23975        // the compound gate (window-below-timeout — sibling per-arm
23976        // coverage lives in the two
23977        // `first_cross_axis_violation_matches_gate_on_*` pins above),
23978        // plus the two clean-pass shapes (empty policy — every axis
23979        // absent — and fully-coherent — every axis inside the coherence
23980        // surface) that pin the compound gate's `Ok(())` arm. Half-A
23981        // (per-axis + phase-boundary surfaces) lives in the sibling
23982        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
23983        // pin; splitting keeps each pin's body under
23984        // `clippy::too_many_lines`.
23985        let cases: &[(&str, MeshPolicy, Option<AplicacaoError>)] = &[
23986            (
23987                "cross-axis: window-below-timeout",
23988                MeshPolicy {
23989                    timeout: Some(Duration::from_secs(30)),
23990                    circuit_breaker: Some(CircuitBreaker {
23991                        max_failures: 5,
23992                        window: Duration::from_secs(10),
23993                    }),
23994                    ..Default::default()
23995                },
23996                Some(AplicacaoError::PolicyBreakerWindowBelowTimeout {
23997                    window: Duration::from_secs(10),
23998                    timeout: Duration::from_secs(30),
23999                }),
24000            ),
24001            ("clean pass: empty policy", MeshPolicy::default(), None),
24002            (
24003                "clean pass: every axis coherent",
24004                MeshPolicy {
24005                    timeout: Some(Duration::from_secs(30)),
24006                    retries: Some(3),
24007                    circuit_breaker: Some(CircuitBreaker {
24008                        max_failures: 5,
24009                        window: Duration::from_secs(60),
24010                    }),
24011                    mtls_required: Some(true),
24012                    rate_limit: Some(RateLimit {
24013                        rate: 100,
24014                        window: Duration::from_secs(1),
24015                    }),
24016                },
24017                None,
24018            ),
24019        ];
24020        assert_validate_matches_gate(cases);
24021    }
24022
24023    #[test]
24024    fn empty_politicas_validates() {
24025        // Omitting every policy axis is fine — defaults express "no
24026        // policy on this axis", not "policy = 0". The fixture's typical
24027        // values continue to validate; this test pins that
24028        // MeshPolicy::default() is a clean pass through validate().
24029        let mut s = three_member_spec();
24030        s.politicas = MeshPolicy::default();
24031        s.validate().unwrap();
24032    }
24033
24034    #[test]
24035    fn typical_politicas_validates_with_every_axis_set() {
24036        // The full §III.1 example block (timeout + retries + breaker +
24037        // mtls + rate-limit) — every axis nonzero — must remain a
24038        // clean pass.
24039        let mut s = three_member_spec();
24040        s.politicas = MeshPolicy {
24041            timeout: Some(Duration::from_secs(30)),
24042            retries: Some(3),
24043            circuit_breaker: Some(CircuitBreaker {
24044                max_failures: 5,
24045                window: Duration::from_secs(60),
24046            }),
24047            mtls_required: Some(true),
24048            rate_limit: Some(RateLimit {
24049                rate: 100,
24050                window: Duration::from_secs(1),
24051            }),
24052        };
24053        s.validate().unwrap();
24054    }
24055
24056    #[test]
24057    fn rejects_empty_cluster_name() {
24058        let mut s = three_member_spec();
24059        s.placement.clusters = vec!["rio".into(), String::new()];
24060        assert_eq!(
24061            s.validate().unwrap_err(),
24062            AplicacaoError::PlacementClusterEmpty
24063        );
24064    }
24065
24066    #[test]
24067    fn rejects_duplicate_cluster_names() {
24068        let mut s = three_member_spec();
24069        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
24070        let err = s.validate().unwrap_err();
24071        assert!(
24072            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
24073            "got {err:?}"
24074        );
24075    }
24076
24077    #[test]
24078    fn rejects_placement_cluster_with_uppercase() {
24079        // The canonical "I copied the cluster's display name verbatim"
24080        // typo — K8s context names are lowercase per DNS-1123 label
24081        // rule, but org docs often round-trip a TitleCase identifier
24082        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
24083        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
24084        // on the peer name axis.
24085        let mut s = three_member_spec();
24086        s.placement.clusters = vec!["Rio".into(), "mar".into()];
24087        let err = s.validate().unwrap_err();
24088        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
24089            panic!("expected PlacementClusterInvalid, got other variant");
24090        };
24091        assert_eq!(cluster, "Rio");
24092        assert!(
24093            reason.contains("uppercase"),
24094            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
24095        );
24096        assert!(
24097            reason.contains("\"rio\""),
24098            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
24099        );
24100    }
24101
24102    #[test]
24103    fn rejects_placement_cluster_with_underscore() {
24104        // The canonical "I'm thinking of an env var / hostname slug"
24105        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
24106        // schema. K8s context filtering on `my_cluster` silently misses
24107        // the cluster the author intended; the gate moves it to caixa-
24108        // build time. Same shape as `rejects_membro_caixa_with_underscore`
24109        // (3f9d7a0).
24110        let mut s = three_member_spec();
24111        s.placement.clusters = vec!["my_cluster".into()];
24112        let err = s.validate().unwrap_err();
24113        assert!(
24114            matches!(
24115                err,
24116                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
24117                    if cluster == "my_cluster" && reason.contains('_')
24118            ),
24119            "got {err:?}"
24120        );
24121    }
24122
24123    #[test]
24124    fn rejects_placement_cluster_with_dot() {
24125        // A `:placement :clusters` entry is a single DNS-1123 *label*,
24126        // not a subdomain — even though K8s context names sometimes
24127        // carry a dotted form via kubeconfig conventions, the strictest
24128        // floor among the use sites (DNS-1035 cluster.x-k8s.io
24129        // `metadata.name`, Cilium identity label values) wins. The "I
24130        // want to namespace my cluster names with `.`" intent is
24131        // expressed via `-` (`mar-east`).
24132        let mut s = three_member_spec();
24133        s.placement.clusters = vec!["team.rio".into()];
24134        let err = s.validate().unwrap_err();
24135        assert!(
24136            matches!(
24137                err,
24138                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
24139                    if cluster == "team.rio" && reason.contains('.')
24140            ),
24141            "got {err:?}"
24142        );
24143    }
24144
24145    #[test]
24146    fn rejects_placement_cluster_with_leading_hyphen() {
24147        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
24148        // with an alphanumeric. The K8s apiserver rejects `-rio`
24149        // outright; the rendered fan-out would emit a `metadata.name:
24150        // "-rio"` that fails admission far from the source caixa.lisp.
24151        let mut s = three_member_spec();
24152        s.placement.clusters = vec!["-rio".into()];
24153        let err = s.validate().unwrap_err();
24154        assert!(
24155            matches!(
24156                err,
24157                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
24158                    if cluster == "-rio" && reason.contains("start and end")
24159            ),
24160            "got {err:?}"
24161        );
24162    }
24163
24164    #[test]
24165    fn rejects_placement_cluster_with_trailing_hyphen() {
24166        // The symmetric arm of the boundary rule. Pin separately so
24167        // both ends are covered against a future relaxation that only
24168        // checks one boundary (parallel to
24169        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
24170        let mut s = three_member_spec();
24171        s.placement.clusters = vec!["rio-".into()];
24172        let err = s.validate().unwrap_err();
24173        assert!(
24174            matches!(
24175                err,
24176                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
24177                    if cluster == "rio-"
24178            ),
24179            "got {err:?}"
24180        );
24181    }
24182
24183    #[test]
24184    fn rejects_placement_cluster_with_unicode() {
24185        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
24186        // before it reaches K8s. The byte-by-byte ASCII validity check
24187        // rejects multi-byte UTF-8 sequences by the first byte that
24188        // fails `[a-z0-9-]`.
24189        let mut s = three_member_spec();
24190        s.placement.clusters = vec!["rió".into()];
24191        let err = s.validate().unwrap_err();
24192        assert!(
24193            matches!(
24194                err,
24195                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
24196                    if cluster == "rió"
24197            ),
24198            "got {err:?}"
24199        );
24200    }
24201
24202    #[test]
24203    fn rejects_placement_cluster_with_whitespace() {
24204        // Whitespace is the canonical "I pasted from a sketch / doc"
24205        // footgun. The apiserver rejects every cluster `metadata.name`
24206        // value carrying whitespace.
24207        let mut s = three_member_spec();
24208        s.placement.clusters = vec!["rio cluster".into()];
24209        let err = s.validate().unwrap_err();
24210        assert!(
24211            matches!(
24212                err,
24213                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
24214                    if cluster == "rio cluster"
24215            ),
24216            "got {err:?}"
24217        );
24218    }
24219
24220    #[test]
24221    fn rejects_placement_cluster_too_long() {
24222        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
24223        // pin. The diagnostic names both the cap (63) and the actual
24224        // length so the author can shorten in one edit. Mirrors
24225        // `rejects_membro_caixa_too_long` (3f9d7a0).
24226        let mut s = three_member_spec();
24227        let too_long = "a".repeat(64);
24228        s.placement.clusters = vec![too_long.clone()];
24229        let err = s.validate().unwrap_err();
24230        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
24231            panic!("expected PlacementClusterInvalid");
24232        };
24233        assert_eq!(cluster, too_long);
24234        assert!(
24235            reason.contains("63") && reason.contains("64"),
24236            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
24237        );
24238    }
24239
24240    #[test]
24241    fn placement_cluster_max_length_validates() {
24242        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
24243        // future tightening (e.g. dropping to 62) surfaces here as a
24244        // regression, mirroring `membro_caixa_max_length_validates`
24245        // (3f9d7a0).
24246        let mut s = three_member_spec();
24247        s.placement.clusters = vec!["a".repeat(63)];
24248        s.validate().unwrap();
24249    }
24250
24251    #[test]
24252    fn accepts_canonical_placement_cluster_forms() {
24253        // The DNS-1123 label shapes a caixa author is realistically
24254        // going to write for cluster names: single-word lowercase
24255        // (`rio`), regional hyphen-joined (`mar-east`), single
24256        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
24257        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
24258        // Pin every leg so a future tightening that bans (e.g.) digit-
24259        // start identifiers surfaces here.
24260        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
24261            let mut s = three_member_spec();
24262            s.placement.clusters = vec![form.into()];
24263            s.validate().unwrap_or_else(|e| {
24264                panic!("canonical cluster form {form:?} must validate, got {e:?}")
24265            });
24266        }
24267    }
24268
24269    #[test]
24270    fn placement_cluster_empty_takes_precedence_over_invalid() {
24271        // Order pin: the existing `PlacementClusterEmpty` diagnostic
24272        // (which doesn't try to parse) fires before the new
24273        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
24274        // `:clusters` entry keeps its narrower error message — the new
24275        // gate would also reject `""`, but the empty-string arm is the
24276        // more self-locating diagnostic. Mirrors the
24277        // `membro_caixa_empty_takes_precedence_over_invalid` pin
24278        // (3f9d7a0).
24279        let mut s = three_member_spec();
24280        s.placement.clusters = vec!["rio".into(), String::new()];
24281        let err = s.validate().unwrap_err();
24282        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
24283    }
24284
24285    #[test]
24286    fn placement_cluster_invalid_fires_before_duplicate_check() {
24287        // Order pin: a malformed-shape `:clusters` entry surfaces *its
24288        // own* diagnostic, even when a later entry would otherwise
24289        // collapse onto a duplicate name. The per-entry shape gate runs
24290        // inline before the duplicate-key insert, parallel to
24291        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
24292        let mut s = three_member_spec();
24293        s.placement.clusters = vec!["Rio".into(), "rio".into()];
24294        let err = s.validate().unwrap_err();
24295        assert!(
24296            matches!(
24297                err,
24298                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
24299            ),
24300            "got {err:?}"
24301        );
24302    }
24303
24304    #[test]
24305    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
24306        // The diagnostic-shape pin: the error names the offending
24307        // `:clusters` value verbatim so the author can grep their
24308        // caixa.lisp without re-running the build, and carries a
24309        // non-empty `reason` naming the specific violation. Same shape
24310        // every typed-shape gate enshrines
24311        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
24312        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
24313        let mut s = three_member_spec();
24314        s.placement.clusters = vec!["BAD_CLUSTER".into()];
24315        let err = s.validate().unwrap_err();
24316        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
24317            panic!("expected PlacementClusterInvalid");
24318        };
24319        assert_eq!(cluster, "BAD_CLUSTER");
24320        assert!(
24321            !reason.is_empty(),
24322            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
24323        );
24324    }
24325
24326    #[test]
24327    fn rejects_sharded_with_empty_clusters() {
24328        // §III.1: Sharded uses :clusters as the shard pool. An empty
24329        // pool means "shard across no clusters" — meaningless, same as
24330        // Replicated with no hosts.
24331        let mut s = three_member_spec();
24332        s.placement.estrategia = PlacementStrategy::Sharded;
24333        s.placement.shard_key = Some("$tenantId".into());
24334        s.placement.clusters = vec![];
24335        assert!(matches!(
24336            s.validate().unwrap_err(),
24337            AplicacaoError::PlacementWithoutClusters {
24338                estrategia: PlacementStrategy::Sharded
24339            }
24340        ));
24341    }
24342
24343    #[test]
24344    fn rejects_sharded_with_empty_shard_key() {
24345        let mut s = three_member_spec();
24346        s.placement.estrategia = PlacementStrategy::Sharded;
24347        s.placement.shard_key = Some(String::new());
24348        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
24349    }
24350
24351    #[test]
24352    fn rejects_shard_key_under_replicated_strategy() {
24353        // The fail-before-pass-after pin: a `:placement (:estrategia
24354        // Replicated :shard-key "tenantId")` manifest carries the
24355        // hash-keyed-distribution slot on a strategy that never consumes
24356        // it. Before the gate the typed slot's value silently vanished
24357        // at the renderer layer (caixa-mesh emits `placement.shardKey`
24358        // verbatim regardless of strategy; the Akka-style cluster-
24359        // sharding reconciler keys off `estrategia == Sharded` and
24360        // ignores the slot otherwise), with no diagnostic. Lifting the
24361        // rejection to a build-time gate makes the
24362        // `shard_key.is_some() == matches!(estrategia, Sharded)`
24363        // partition a structural property of every validated
24364        // [`Placement`].
24365        let mut s = three_member_spec();
24366        // The fixture already uses Replicated; just add a shard-key.
24367        s.placement.shard_key = Some("$tenantId".into());
24368        let err = s.validate().unwrap_err();
24369        let AplicacaoError::ShardKeyOnNonSharded {
24370            estrategia,
24371            shard_key,
24372        } = err
24373        else {
24374            panic!("expected ShardKeyOnNonSharded, got {err:?}");
24375        };
24376        assert_eq!(estrategia, PlacementStrategy::Replicated);
24377        assert_eq!(shard_key, "$tenantId");
24378    }
24379
24380    #[test]
24381    fn rejects_shard_key_under_singlenode_strategy() {
24382        // Peer of the Replicated case above on the SingleNode arm: OTP
24383        // distributed-app takeover (one cluster runs at a time) has no
24384        // hash-keyed routing axis to consume `:shard-key` either, so
24385        // the rejection fires on both non-Sharded arms uniformly.
24386        let mut s = three_member_spec();
24387        s.placement.estrategia = PlacementStrategy::SingleNode;
24388        s.placement.shard_key = Some("$tenantId".into());
24389        let err = s.validate().unwrap_err();
24390        let AplicacaoError::ShardKeyOnNonSharded {
24391            estrategia,
24392            shard_key,
24393        } = err
24394        else {
24395            panic!("expected ShardKeyOnNonSharded, got {err:?}");
24396        };
24397        assert_eq!(estrategia, PlacementStrategy::SingleNode);
24398        assert_eq!(shard_key, "$tenantId");
24399    }
24400
24401    #[test]
24402    fn rejects_empty_shard_key_under_replicated_strategy() {
24403        // The `Some("")` case under non-Sharded is rejected by
24404        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
24405        // fires before the empty-value gate), not
24406        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
24407        // the `Sharded` arm). Pin the partition so a future reorder of
24408        // the validate_placement match arms doesn't silently swap which
24409        // diagnostic the author sees — both are author errors, but
24410        // ShardKeyOnNonSharded names which strategy is the actual fix
24411        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
24412        // only says "pick a non-empty key".
24413        let mut s = three_member_spec();
24414        s.placement.shard_key = Some(String::new());
24415        let err = s.validate().unwrap_err();
24416        assert!(
24417            matches!(
24418                err,
24419                AplicacaoError::ShardKeyOnNonSharded {
24420                    estrategia: PlacementStrategy::Replicated,
24421                    ref shard_key,
24422                } if shard_key.is_empty()
24423            ),
24424            "got {err:?}"
24425        );
24426    }
24427
24428    #[test]
24429    fn replicated_without_shard_key_validates() {
24430        // The complement of the rejection: `:placement :estrategia
24431        // Replicated` with `:shard-key None` is the canonical happy
24432        // path on every existing fixture. Pin the no-shard-key case so
24433        // the new gate doesn't accidentally fire on `None`.
24434        let mut s = three_member_spec();
24435        assert!(matches!(
24436            s.placement.estrategia,
24437            PlacementStrategy::Replicated
24438        ));
24439        s.placement.shard_key = None;
24440        s.validate().unwrap();
24441    }
24442
24443    #[test]
24444    fn singlenode_without_shard_key_validates() {
24445        // Peer of the Replicated no-shard-key case on the SingleNode
24446        // arm — both non-Sharded strategies must validate cleanly when
24447        // the slot is omitted.
24448        let mut s = three_member_spec();
24449        s.placement.estrategia = PlacementStrategy::SingleNode;
24450        s.placement.shard_key = None;
24451        s.validate().unwrap();
24452    }
24453
24454    #[test]
24455    fn shard_key_on_non_sharded_ctor_matches_struct_literal_wrap() {
24456        // Fail-before-pass-after pin on
24457        // [`AplicacaoError::shard_key_on_non_sharded`]'s
24458        // substrate-primitive posture: byte-identity + `Display`
24459        // byte-string parity against the open-coded struct-literal
24460        // for every non-`Sharded` [`PlacementStrategy`] arm across a
24461        // representative `:shard-key` value the sole in-crate wire-up
24462        // site (`AplicacaoSpec::validate_placement`'s
24463        // `PlacementStrategy::Replicated | PlacementStrategy::SingleNode`
24464        // arm) emits. Any wrapper-side silent normalization, `.into()`
24465        // divergence, or accidental field rebrand on the ctor body
24466        // surfaces at assert time rather than at a downstream consumer
24467        // that reads `err.estrategia` / `err.shard_key` back and gets a
24468        // different value than the one it stored.
24469        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
24470            let placement = Placement {
24471                estrategia,
24472                clusters: vec!["cluster-a".to_string()],
24473                shard_key: Some("$tenantId".to_string()),
24474                affinity: None,
24475            };
24476            let via_ctor = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
24477            let via_literal = AplicacaoError::ShardKeyOnNonSharded {
24478                estrategia,
24479                shard_key: "$tenantId".to_string(),
24480            };
24481            assert_eq!(
24482                via_ctor, via_literal,
24483                "shard_key_on_non_sharded(&placement, k) must byte-equal the \
24484                 open-coded ShardKeyOnNonSharded struct-literal for {estrategia:?}"
24485            );
24486            assert_eq!(
24487                via_ctor.to_string(),
24488                via_literal.to_string(),
24489                "Display byte-string must byte-equal the open-coded struct-literal \
24490                 for {estrategia:?}"
24491            );
24492        }
24493    }
24494
24495    #[test]
24496    fn shard_key_on_non_sharded_routes_estrategia_through_placement_accessor() {
24497        // Boundary-sweep pin on the ctor's substrate-primitive
24498        // projection: the `estrategia` slot is stored verbatim from
24499        // [`Placement::estrategia`] on every arm the accessor can
24500        // return, and the `shard_key` slot preserves the caller-side
24501        // `&str` byte-for-byte. Sweeping every arm of
24502        // [`PlacementStrategy::ALL`] (including the `Sharded` arm the
24503        // current caller never reaches, since the ctor is a substrate
24504        // primitive independent of any single caller's dispatch gate)
24505        // catches a future silent field-rebrand or per-arm ctor
24506        // divergence at caixa-core build time rather than at a
24507        // downstream consumer far from the wire-up commit.
24508        for &estrategia in PlacementStrategy::ALL {
24509            let placement = Placement {
24510                estrategia,
24511                clusters: vec!["cluster-a".to_string()],
24512                shard_key: Some("$tenantId".to_string()),
24513                affinity: None,
24514            };
24515            let err = AplicacaoError::shard_key_on_non_sharded(&placement, "$tenantId");
24516            let AplicacaoError::ShardKeyOnNonSharded {
24517                estrategia: stored_estrategia,
24518                shard_key: stored_shard_key,
24519            } = err
24520            else {
24521                panic!(
24522                    "shard_key_on_non_sharded must construct ShardKeyOnNonSharded for {estrategia:?}"
24523                );
24524            };
24525            assert_eq!(
24526                stored_estrategia, estrategia,
24527                "estrategia slot must round-trip verbatim through Placement::estrategia \
24528                 for {estrategia:?}"
24529            );
24530            assert_eq!(
24531                stored_shard_key, "$tenantId",
24532                "shard_key slot must preserve the caller-side &str byte-for-byte \
24533                 for {estrategia:?}"
24534            );
24535        }
24536    }
24537
24538    #[test]
24539    fn validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor() {
24540        // End-to-end pin: the sole in-crate wire-up site
24541        // (`AplicacaoSpec::validate_placement`'s non-`Sharded`-arm
24542        // refusal) routes through
24543        // [`AplicacaoError::shard_key_on_non_sharded`] and the observed
24544        // `Err` byte-equals the ctor's output on the same non-`Sharded`
24545        // fixture. A future silent de-lift of the wire-up back to the
24546        // open-coded struct-literal trips this test at caixa-core build
24547        // time rather than at a downstream diagnostic consumer far from
24548        // the wire-up commit.
24549        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
24550            let mut s = three_member_spec();
24551            s.placement.estrategia = estrategia;
24552            s.placement.shard_key = Some("$tenantId".to_string());
24553            let observed = s.validate().unwrap_err();
24554            let expected = AplicacaoError::shard_key_on_non_sharded(&s.placement, "$tenantId");
24555            assert_eq!(
24556                observed, expected,
24557                "validate_placement's non-Sharded-arm Err must byte-equal \
24558                 shard_key_on_non_sharded(&placement, k) for {estrategia:?}"
24559            );
24560            assert_eq!(
24561                observed.to_string(),
24562                expected.to_string(),
24563                "Display byte-string parity for {estrategia:?}"
24564            );
24565        }
24566    }
24567
24568    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
24569        // Fixture builder for the `:placement :shard-key` shape gate
24570        // tests: a three-member Aplicacao on the `Sharded` strategy
24571        // with the supplied `:shard-key` slot. Co-locates the
24572        // arm-construction so every test below carries one line of
24573        // setup (the offending `:shard-key` value) and the assertion.
24574        let mut s = three_member_spec();
24575        s.placement.estrategia = PlacementStrategy::Sharded;
24576        s.placement.shard_key = Some(key.into());
24577        s
24578    }
24579
24580    #[test]
24581    fn rejects_shard_key_with_embedded_space() {
24582        // The canonical paste-from-aligned-doc footgun:
24583        // `:shard-key "$tenant Id"` — the Akka-style entity-id
24584        // extractor reads the slot as a single-token reference, and an
24585        // embedded space breaks the token boundary at the runtime
24586        // hash-extractor pass with no diagnostic naming the offending
24587        // entry.
24588        let s = sharded_spec_with_key("$tenant Id");
24589        let err = s.validate().unwrap_err();
24590        assert!(
24591            matches!(
24592                err,
24593                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24594                    if shard_key == "$tenant Id" && reason.contains("space")
24595            ),
24596            "got {err:?}"
24597        );
24598    }
24599
24600    #[test]
24601    fn rejects_shard_key_with_leading_space() {
24602        // Leading-space arm of the embedded-whitespace footgun — the
24603        // paste-from-aligned-doc / paste-from-CSV-cell variant where
24604        // the leading column-padding leaked into the slot.
24605        let s = sharded_spec_with_key(" $tenantId");
24606        let err = s.validate().unwrap_err();
24607        assert!(
24608            matches!(
24609                err,
24610                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
24611                    if shard_key == " $tenantId"
24612            ),
24613            "got {err:?}"
24614        );
24615    }
24616
24617    #[test]
24618    fn rejects_shard_key_with_trailing_newline() {
24619        // The canonical paste-from-shell-heredoc footgun — every
24620        // `<<EOF` heredoc terminator paste leaves a trailing newline
24621        // the YAML emitter then folds away inconsistently across
24622        // emitter implementations.
24623        let s = sharded_spec_with_key("$tenantId\n");
24624        let err = s.validate().unwrap_err();
24625        assert!(
24626            matches!(
24627                err,
24628                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24629                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
24630            ),
24631            "got {err:?}"
24632        );
24633    }
24634
24635    #[test]
24636    fn rejects_shard_key_with_embedded_tab() {
24637        // The paste-from-aligned-doc tab-stop variant — tabs land
24638        // alongside spaces in copy-paste from formatted columns.
24639        let s = sharded_spec_with_key("$tenant\tId");
24640        let err = s.validate().unwrap_err();
24641        assert!(
24642            matches!(
24643                err,
24644                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24645                    if shard_key == "$tenant\tId" && reason.contains("tab")
24646            ),
24647            "got {err:?}"
24648        );
24649    }
24650
24651    #[test]
24652    fn rejects_shard_key_with_control_character() {
24653        // The paste-from-binary / paste-from-screen-cleared-terminal
24654        // footgun — an embedded `\x01` (SOH) byte that some YAML
24655        // emitters silently strip and others escape as ``,
24656        // breaking round-trip across emitter implementations.
24657        let s = sharded_spec_with_key("$tenant\u{0001}Id");
24658        let err = s.validate().unwrap_err();
24659        assert!(
24660            matches!(
24661                err,
24662                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24663                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
24664            ),
24665            "got {err:?}"
24666        );
24667    }
24668
24669    #[test]
24670    fn rejects_shard_key_with_non_ascii() {
24671        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
24672        // footgun — non-ASCII bytes normalize differently between the
24673        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
24674        // YAML parser, the same entity ID can silently map to two
24675        // distinct shards on a re-render.
24676        let s = sharded_spec_with_key("$tenàntId");
24677        let err = s.validate().unwrap_err();
24678        assert!(
24679            matches!(
24680                err,
24681                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
24682                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
24683            ),
24684            "got {err:?}"
24685        );
24686    }
24687
24688    #[test]
24689    fn rejects_shard_key_too_long() {
24690        // Length cap pin: 64 bytes — one byte over the
24691        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
24692        // here is a paste-from-doc multi-line blob landing in
24693        // `:shard-key` instead of a single-token extractor expression.
24694        let too_long = "a".repeat(64);
24695        let s = sharded_spec_with_key(&too_long);
24696        let err = s.validate().unwrap_err();
24697        let AplicacaoError::ShardKeyInvalid {
24698            ref shard_key,
24699            ref reason,
24700        } = err
24701        else {
24702            panic!("expected ShardKeyInvalid, got {err:?}");
24703        };
24704        assert_eq!(shard_key, &too_long);
24705        assert!(
24706            reason.contains("63") && reason.contains("64"),
24707            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
24708        );
24709    }
24710
24711    #[test]
24712    fn shard_key_max_length_validates() {
24713        // Boundary pin: 63 bytes exactly — the
24714        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
24715        // dropping to 62) surfaces here as a regression, mirroring
24716        // `placement_cluster_max_length_validates` /
24717        // `placement_affinity_max_length_validates` on the peer
24718        // identifier-shaped slots.
24719        let s = sharded_spec_with_key(&"a".repeat(63));
24720        s.validate().unwrap();
24721    }
24722
24723    #[test]
24724    fn accepts_canonical_shard_key_forms() {
24725        // The Akka-style entity-id extractor shapes a caixa author is
24726        // realistically going to write — pin every leg so a future
24727        // tightening that bans (e.g.) the `${...}` interpolation
24728        // variant or the `metadata.<field>` JSONPath form surfaces
24729        // here as a regression. The canonical forms span:
24730        //
24731        //   - bare property name (`tenantId`, `customerId`)
24732        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
24733        //   - JSONPath-style nested reference (`metadata.tenantId`,
24734        //     `$.user.id`)
24735        //   - interpolation-style template (`${tenant}`)
24736        //   - snake_case property name (`customer_id`)
24737        //   - kebab-case property name (`customer-id` — accepted
24738        //     because the slot is a printable-ASCII single-token
24739        //     reference, not a DNS-1123 label like
24740        //     `:placement :affinity` / `:clusters`)
24741        //   - single character (`a`, `$` — boundary)
24742        for form in [
24743            "tenantId",
24744            "customerId",
24745            "$tenantId",
24746            "metadata.tenantId",
24747            "$.user.id",
24748            "${tenant}",
24749            "customer_id",
24750            "customer-id",
24751            "a",
24752            "$",
24753        ] {
24754            let s = sharded_spec_with_key(form);
24755            s.validate().unwrap_or_else(|e| {
24756                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
24757            });
24758        }
24759    }
24760
24761    #[test]
24762    fn shard_key_empty_takes_precedence_over_invalid() {
24763        // Order pin: the existing `ShardedKeyEmpty` diagnostic
24764        // (reserved for the `Sharded` `Some("")` arm) fires before the
24765        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
24766        // `:shard-key` keeps its narrower error message — the new gate
24767        // would also reject `""` defensively, but the empty-string arm
24768        // is the more self-locating diagnostic. Mirrors the
24769        // `placement_cluster_empty_takes_precedence_over_invalid` pin
24770        // on the peer identifier-shaped slot.
24771        let s = sharded_spec_with_key("");
24772        let err = s.validate().unwrap_err();
24773        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
24774    }
24775
24776    #[test]
24777    fn shard_key_invalid_diagnostic_carries_offending_value() {
24778        // The diagnostic-shape pin: the error names the offending
24779        // `:shard-key` value verbatim so the author can grep their
24780        // caixa.lisp without re-running the build, and carries a
24781        // parser-shaped `reason:` naming the specific violation —
24782        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
24783        // on the peer identifier-shaped slot.
24784        let s = sharded_spec_with_key("$tenant Id");
24785        let err = s.validate().unwrap_err();
24786        let AplicacaoError::ShardKeyInvalid {
24787            ref shard_key,
24788            ref reason,
24789        } = err
24790        else {
24791            panic!("expected ShardKeyInvalid, got {err:?}");
24792        };
24793        assert_eq!(shard_key, "$tenant Id");
24794        assert!(
24795            !reason.is_empty(),
24796            "reason must name the specific violation, got empty string"
24797        );
24798    }
24799
24800    #[test]
24801    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
24802        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
24803        // `:shard-key` carried on non-Sharded strategies) fires before
24804        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
24805        // a `Replicated` strategy surfaces the more self-locating
24806        // strategy-mismatch diagnostic (naming the actual fix — drop
24807        // the slot, or switch to Sharded) rather than the shape
24808        // diagnostic. The strategy-mismatch arm is the more actionable
24809        // diagnostic: a malformed shard-key on Replicated is "you
24810        // shouldn't have a :shard-key here at all", not "your
24811        // :shard-key value is malformed".
24812        let mut s = three_member_spec();
24813        // Replicated is the default fixture strategy.
24814        s.placement.shard_key = Some("$tenant Id".into());
24815        let err = s.validate().unwrap_err();
24816        assert!(
24817            matches!(
24818                err,
24819                AplicacaoError::ShardKeyOnNonSharded {
24820                    estrategia: PlacementStrategy::Replicated,
24821                    ..
24822                }
24823            ),
24824            "got {err:?}"
24825        );
24826    }
24827
24828    #[test]
24829    fn rejects_empty_affinity_hint() {
24830        let mut s = three_member_spec();
24831        s.placement.affinity = Some(String::new());
24832        assert_eq!(
24833            s.validate().unwrap_err(),
24834            AplicacaoError::PlacementAffinityEmpty
24835        );
24836    }
24837
24838    #[test]
24839    fn placement_without_affinity_validates() {
24840        // Omitting :affinity is fine — the placement engine falls back
24841        // to the default heuristic. Pin the no-hint case so the
24842        // affinity-empty rejection doesn't accidentally fire on `None`.
24843        let mut s = three_member_spec();
24844        s.placement.affinity = None;
24845        s.validate().unwrap();
24846    }
24847
24848    #[test]
24849    fn rejects_placement_affinity_with_uppercase() {
24850        // The canonical "I copied the ADR's display name verbatim" typo
24851        // — placement hints land verbatim in K8s label-selector
24852        // territory, where the apiserver enforces the DNS-1123 label
24853        // rule (lowercase-only) on every identity-keyed admission axis.
24854        // Mirrors `rejects_placement_cluster_with_uppercase` on the
24855        // sibling slot.
24856        let mut s = three_member_spec();
24857        s.placement.affinity = Some("DataLocality".into());
24858        let err = s.validate().unwrap_err();
24859        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
24860            panic!("expected PlacementAffinityInvalid, got other variant");
24861        };
24862        assert_eq!(affinity, "DataLocality");
24863        assert!(
24864            reason.contains("uppercase"),
24865            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
24866        );
24867        assert!(
24868            reason.contains("\"datalocality\""),
24869            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
24870        );
24871    }
24872
24873    #[test]
24874    fn rejects_placement_affinity_with_underscore() {
24875        // The canonical "I'm thinking of an env var / Python identifier"
24876        // leak — `_` is forbidden by every DNS-1123 label schema. Same
24877        // shape as `rejects_placement_cluster_with_underscore` on the
24878        // sibling slot.
24879        let mut s = three_member_spec();
24880        s.placement.affinity = Some("data_locality".into());
24881        let err = s.validate().unwrap_err();
24882        assert!(
24883            matches!(
24884                err,
24885                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
24886                    if affinity == "data_locality" && reason.contains('_')
24887            ),
24888            "got {err:?}"
24889        );
24890    }
24891
24892    #[test]
24893    fn rejects_placement_affinity_with_dot() {
24894        // A `:placement :affinity` value is a single DNS-1123 *label*
24895        // (it lands as a K8s label value selector key), not a subdomain.
24896        // The "I want to namespace my hint with `.`" intent is expressed
24897        // via `-` (`data-locality-east`).
24898        let mut s = three_member_spec();
24899        s.placement.affinity = Some("data.locality".into());
24900        let err = s.validate().unwrap_err();
24901        assert!(
24902            matches!(
24903                err,
24904                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
24905                    if affinity == "data.locality" && reason.contains('.')
24906            ),
24907            "got {err:?}"
24908        );
24909    }
24910
24911    #[test]
24912    fn rejects_placement_affinity_with_unicode() {
24913        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
24914        // before it reaches K8s. The byte-by-byte ASCII validity check
24915        // rejects multi-byte UTF-8 sequences by the first byte that
24916        // fails `[a-z0-9-]`.
24917        let mut s = three_member_spec();
24918        s.placement.affinity = Some("data-localité".into());
24919        let err = s.validate().unwrap_err();
24920        assert!(
24921            matches!(
24922                err,
24923                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
24924                    if affinity == "data-localité"
24925            ),
24926            "got {err:?}"
24927        );
24928    }
24929
24930    #[test]
24931    fn rejects_placement_affinity_with_leading_hyphen() {
24932        // DNS-1123 boundary rule: labels must start with an
24933        // alphanumeric. Pin separately from the trailing-hyphen arm so
24934        // a future relaxation that only checks one boundary surfaces
24935        // here as a regression (parallel to
24936        // `rejects_placement_cluster_with_leading_hyphen`).
24937        let mut s = three_member_spec();
24938        s.placement.affinity = Some("-data-locality".into());
24939        let err = s.validate().unwrap_err();
24940        assert!(
24941            matches!(
24942                err,
24943                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
24944                    if affinity == "-data-locality" && reason.contains("start and end")
24945            ),
24946            "got {err:?}"
24947        );
24948    }
24949
24950    #[test]
24951    fn rejects_placement_affinity_with_trailing_hyphen() {
24952        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
24953        // ends are covered against a future relaxation.
24954        let mut s = three_member_spec();
24955        s.placement.affinity = Some("data-locality-".into());
24956        let err = s.validate().unwrap_err();
24957        assert!(
24958            matches!(
24959                err,
24960                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
24961                    if affinity == "data-locality-"
24962            ),
24963            "got {err:?}"
24964        );
24965    }
24966
24967    #[test]
24968    fn rejects_placement_affinity_with_whitespace() {
24969        // Whitespace is the canonical "I pasted from a sketch / doc"
24970        // footgun. The apiserver rejects every label-selector value
24971        // carrying whitespace.
24972        let mut s = three_member_spec();
24973        s.placement.affinity = Some("data locality".into());
24974        let err = s.validate().unwrap_err();
24975        assert!(
24976            matches!(
24977                err,
24978                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
24979                    if affinity == "data locality"
24980            ),
24981            "got {err:?}"
24982        );
24983    }
24984
24985    #[test]
24986    fn rejects_placement_affinity_too_long() {
24987        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
24988        // pin. The diagnostic names both the cap (63) and the actual
24989        // length so the author can shorten in one edit. Mirrors
24990        // `rejects_placement_cluster_too_long`.
24991        let mut s = three_member_spec();
24992        let too_long = "a".repeat(64);
24993        s.placement.affinity = Some(too_long.clone());
24994        let err = s.validate().unwrap_err();
24995        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
24996            panic!("expected PlacementAffinityInvalid");
24997        };
24998        assert_eq!(affinity, too_long);
24999        assert!(
25000            reason.contains("63") && reason.contains("64"),
25001            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
25002        );
25003    }
25004
25005    #[test]
25006    fn placement_affinity_max_length_validates() {
25007        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
25008        // future tightening (e.g. dropping to 62) surfaces here as a
25009        // regression, mirroring `placement_cluster_max_length_validates`.
25010        let mut s = three_member_spec();
25011        s.placement.affinity = Some("a".repeat(63));
25012        s.validate().unwrap();
25013    }
25014
25015    #[test]
25016    fn accepts_canonical_placement_affinity_forms() {
25017        // The DNS-1123 label shapes a caixa author is realistically
25018        // going to write for placement hints: the M3 canonical examples
25019        // (`data-locality`, `low-latency`, `anti-affinity`), the
25020        // single-token form (`affinity`), the single-character boundary
25021        // (`a`), the digit-start (DNS-1123 allows this, unlike
25022        // DNS-1035), and a regional-suffixed form. Pin every leg so a
25023        // future tightening that bans (e.g.) digit-start identifiers
25024        // surfaces here.
25025        for form in [
25026            "data-locality",
25027            "low-latency",
25028            "anti-affinity",
25029            "affinity",
25030            "a",
25031            "3-tier",
25032            "locality-east",
25033        ] {
25034            let mut s = three_member_spec();
25035            s.placement.affinity = Some(form.into());
25036            s.validate().unwrap_or_else(|e| {
25037                panic!("canonical affinity form {form:?} must validate, got {e:?}")
25038            });
25039        }
25040    }
25041
25042    #[test]
25043    fn placement_affinity_empty_takes_precedence_over_invalid() {
25044        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
25045        // (which doesn't try to parse) fires before the new
25046        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
25047        // `:affinity` keeps its narrower error message — the new gate
25048        // would also reject `""`, but the empty-string arm is the more
25049        // self-locating diagnostic. Mirrors the
25050        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
25051        let mut s = three_member_spec();
25052        s.placement.affinity = Some(String::new());
25053        let err = s.validate().unwrap_err();
25054        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
25055    }
25056
25057    #[test]
25058    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
25059        // The diagnostic shape pin: every rejection carries the offending
25060        // `affinity:` verbatim plus a parser-shaped `reason:` so the
25061        // author can grep their caixa.lisp for `:affinity "<hint>"` and
25062        // fix it in one edit. Mirrors the
25063        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
25064        // pin on the sibling slot.
25065        let mut s = three_member_spec();
25066        s.placement.affinity = Some("Data_Locality".into());
25067        let err = s.validate().unwrap_err();
25068        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
25069            panic!("expected PlacementAffinityInvalid");
25070        };
25071        assert_eq!(affinity, "Data_Locality");
25072        assert!(
25073            !reason.is_empty(),
25074            "diagnostic reason must not be empty (got: {reason:?})"
25075        );
25076    }
25077
25078    #[test]
25079    fn singlenode_with_takeover_candidates_validates() {
25080        // OTP distributed-application convention (MESH-COMPOSITION
25081        // §II.1): SingleNode runs on one cluster at a time but the
25082        // :clusters list enumerates the takeover candidates. Multiple
25083        // entries are not a contradiction — they are the failover pool.
25084        let mut s = three_member_spec();
25085        s.placement.estrategia = PlacementStrategy::SingleNode;
25086        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
25087        s.validate().unwrap();
25088    }
25089
25090    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
25091
25092    #[test]
25093    fn mesh_policy_default_is_empty() {
25094        // The Default impl carries None on every axis — the typed
25095        // analog of an unset `:politicas (())` slot. Renderers that
25096        // overlay the policy onto a cluster artifact key off this
25097        // predicate to skip the slot entirely; pinning so a future
25098        // axis added to MeshPolicy can't silently break the contract
25099        // (a new field whose Default is non-None would flip is_empty
25100        // to false on every existing caixa, surfacing here).
25101        assert!(MeshPolicy::default().is_empty());
25102    }
25103
25104    #[test]
25105    fn mesh_policy_with_only_timeout_is_not_empty() {
25106        let p = MeshPolicy {
25107            timeout: Some(Duration::from_secs(30)),
25108            ..Default::default()
25109        };
25110        assert!(!p.is_empty());
25111    }
25112
25113    #[test]
25114    fn mesh_policy_with_only_retries_is_not_empty() {
25115        let p = MeshPolicy {
25116            retries: Some(3),
25117            ..Default::default()
25118        };
25119        assert!(!p.is_empty());
25120    }
25121
25122    #[test]
25123    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
25124        let p = MeshPolicy {
25125            circuit_breaker: Some(CircuitBreaker {
25126                max_failures: 5,
25127                window: Duration::from_secs(60),
25128            }),
25129            ..Default::default()
25130        };
25131        assert!(!p.is_empty());
25132    }
25133
25134    #[test]
25135    fn mesh_policy_with_only_mtls_required_is_not_empty() {
25136        // Even `mtls_required: Some(false)` (an explicit opt-out) is
25137        // not empty — the author *named* the axis, the renderer needs
25138        // to honor that vs. fall back to the cluster default.
25139        let p = MeshPolicy {
25140            mtls_required: Some(false),
25141            ..Default::default()
25142        };
25143        assert!(!p.is_empty());
25144    }
25145
25146    #[test]
25147    fn mesh_policy_with_only_rate_limit_is_not_empty() {
25148        let p = MeshPolicy {
25149            rate_limit: Some(RateLimit {
25150                rate: 100,
25151                window: Duration::from_secs(1),
25152            }),
25153            ..Default::default()
25154        };
25155        assert!(!p.is_empty());
25156    }
25157
25158    #[test]
25159    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
25160        // The three-member happy-path fixture sets timeout + retries +
25161        // mtls_required — every populated axis must read non-empty.
25162        // Pin the round-trip so the M3.x per-:politicas emitter (the
25163        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
25164        // on is_empty() to decide whether to emit at all without
25165        // re-deriving the contract from inline field probes.
25166        assert!(!three_member_spec().politicas.is_empty());
25167    }
25168
25169    #[test]
25170    fn mesh_policy_empty_is_the_all_none_arm_and_is_empty() {
25171        // Fail-before-pass-after round-trip pin on the paired
25172        // ([`MeshPolicy::empty`], [`MeshPolicy::is_empty`]) constructor /
25173        // predicate on the [`MeshPolicy`] typed slot: the lifted
25174        // constructor must materialize a value whose every one of the
25175        // five `Option<_>`-carrying per-axis fields is `None`, so the
25176        // paired [`MeshPolicy::is_empty`] predicate returns `true` on
25177        // the constructor's output by construction. A future silent
25178        // regression that omits a `None` arm from the constructor's
25179        // struct-literal (a sixth axis added to the type whose
25180        // constructor arm is forgotten, an accidental `Some(0)` on the
25181        // `retries` arm that would silently violate the
25182        // [`AplicacaoError::PolicyRetriesZero`] admission floor) trips
25183        // here at caixa-core test time rather than surfacing as a
25184        // downstream consumer's per-`:politicas` overlay-emit path
25185        // reading a `MeshPolicy::empty()` output that fails the
25186        // emptiness predicate and lands an unexpected `spec.policies.
25187        // <axis>` field in the emitted Cilium/Envoy overlay. Peer of
25188        // the sibling
25189        // [`crate::limits::tests::limits_spec_empty_is_the_all_none_arm_and_is_empty`]
25190        // pin on the M2 `:limits` typed slot — extends the same
25191        // "the canonical unset baseline satisfies the paired
25192        // emptiness predicate" round-trip discipline onto the M3
25193        // `:politicas` slot.
25194        let empty = MeshPolicy::empty();
25195        assert!(
25196            empty.is_empty(),
25197            "MeshPolicy::empty() must return a value whose is_empty() \
25198             predicate is true — got {empty:?}",
25199        );
25200        assert_eq!(empty.timeout(), None);
25201        assert_eq!(empty.retries(), None);
25202        assert_eq!(empty.circuit_breaker(), None);
25203        assert_eq!(empty.mtls_required(), None);
25204        assert_eq!(empty.rate_limit(), None);
25205    }
25206
25207    #[test]
25208    fn mesh_policy_empty_byte_equals_default() {
25209        // Fail-before-pass-after byte-parity pin on the two-path
25210        // convergence: the lifted `pub const fn` [`MeshPolicy::empty`]
25211        // constructor must byte-equal the derived (non-`const`)
25212        // [`Default::default`] on every one of the five
25213        // `Option<_>`-carrying per-axis fields under `PartialEq`. The
25214        // two paths are semantically identical (both name the
25215        // "canonical unset [`MeshPolicy`]" shape) but structurally
25216        // distinct (the derived [`Default::default`] threads through
25217        // the derive-generated per-field `<Option<_> as Default>::default`
25218        // cascade, resolving to `None` on each; the lifted
25219        // constructor's struct-literal names each `None` arm
25220        // verbatim). A future regression on either path — an
25221        // accidental `Some(0)` on the constructor's `retries` arm
25222        // that would silently drift the constructor's output from the
25223        // derived default (surfacing here as the pin's first-arm
25224        // inequality), a future substrate-wide field-default rebrand
25225        // that lands on the derived path's per-field
25226        // `<Option<_> as Default>::default` but forgets to extend the
25227        // constructor's struct-literal (surfacing here as the pin's
25228        // per-arm inequality on the newly rebranded axis) — trips
25229        // here at caixa-core test time. The `const` binding on the
25230        // LHS forces the lifted constructor through the `const`-eval
25231        // surface at compile time, so any future accidental downgrade
25232        // to `pub fn` fires E0015 at the binding rather than at a
25233        // downstream `const`-context consumer's dispatch site. Peer
25234        // of the sibling
25235        // [`crate::limits::tests::limits_spec_empty_byte_equals_default`]
25236        // pin on the M2 `:limits` typed slot.
25237        const EMPTY: MeshPolicy = MeshPolicy::empty();
25238        assert_eq!(
25239            EMPTY,
25240            MeshPolicy::default(),
25241            "MeshPolicy::empty() must byte-equal MeshPolicy::default() on \
25242             every per-axis field — the two paths name the same canonical \
25243             unset baseline; a mismatch means one path drifted from the \
25244             other on some per-axis default",
25245        );
25246    }
25247
25248    #[test]
25249    fn mesh_policy_empty_ctor_is_const_fn() {
25250        // Const-eval-surface pin on the lifted [`MeshPolicy::empty`]
25251        // constructor: the constructor must remain `pub const fn` so
25252        // downstream consumers can materialize a canonical unset
25253        // baseline in `const` context (a `const EMPTY: MeshPolicy =
25254        // MeshPolicy::empty();` module-scope binding for a
25255        // fixture-builder table, a `const`-context per-arm predicate
25256        // that folds emptiness over the constructor's output at
25257        // compile time, a compile-time lookup table the LSP hover
25258        // renderer materializes per typed-slot fixture). A future
25259        // accidental downgrade to non-`const` (an added runtime
25260        // helper reachable only from a non-`const` context in the
25261        // body, a manual hand-rolled `impl` that shadows this method)
25262        // trips at caixa-core build time — E0015 at the `const EMPTY`
25263        // binding below — rather than surfacing as a downstream
25264        // `const`-context regression far from the constructor's
25265        // declaration. The paired [`Self::is_empty`] predicate call
25266        // inside the `const { assert!(..) }` block enforces both
25267        // halves of the round-trip (constructor is `const`-callable
25268        // AND its output satisfies the paired emptiness predicate at
25269        // `const`-eval time) at caixa-core compile time. Peer of the
25270        // sibling
25271        // [`crate::limits::tests::limits_spec_empty_ctor_is_const_fn`]
25272        // pin on the M2 `:limits` typed slot.
25273        const EMPTY: MeshPolicy = MeshPolicy::empty();
25274        const {
25275            assert!(EMPTY.is_empty());
25276        }
25277    }
25278
25279    #[test]
25280    fn mesh_policy_default_routes_through_empty_ctor() {
25281        // Fail-before-pass-after byte-parity pin on the two-path
25282        // convergence discipline lifted onto the [`Default`] impl:
25283        // pre-fold the derive-generated [`Default::default`] and the
25284        // `pub const fn` [`MeshPolicy::empty`] constructor were
25285        // byte-equal by *coincidence* (each hand-authored or derive-
25286        // authored `None` per axis, pinned load-bearing by the
25287        // pre-existing [`mesh_policy_empty_byte_equals_default`]
25288        // sibling pin), while the folded impl now routes
25289        // [`Default::default`] through the substrate-canonical
25290        // [`Self::empty`] constructor — the two paths are byte-equal
25291        // by *construction*, one delegates to the other. This pin
25292        // sharpens the pre-existing byte-parity invariant into a
25293        // structural-delegation invariant: any future silent regression
25294        // that re-derives [`Default`] on the type (a `#[derive(Default)]`
25295        // re-addition that shadows the manual impl, a swap of the
25296        // manual impl's body onto a divergent struct-literal that
25297        // diverges from [`Self::empty`]'s output on a new field's
25298        // non-`None` canonical baseline) trips here at caixa-core test
25299        // time under `PartialEq` rather than at a downstream consumer
25300        // of the derived-until-now [`Default::default`] surface (the
25301        // five per-axis-only `..Default::default()` fixtures at
25302        // [`mesh_policy_with_only_timeout_is_not_empty`] /
25303        // [`mesh_policy_with_only_retries_is_not_empty`] /
25304        // [`mesh_policy_with_only_circuit_breaker_is_not_empty`] /
25305        // [`mesh_policy_with_only_mtls_required_is_not_empty`] /
25306        // [`mesh_policy_with_only_rate_limit_is_not_empty`], the
25307        // `MeshPolicy::default().is_empty()` round-trip at
25308        // [`mesh_policy_default_is_empty`], every future consumer of
25309        // a hypothetical `..MeshPolicy::default()` overlay-elision
25310        // arm). Peer of the sibling
25311        // [`crate::limits::tests::limits_spec_default_routes_through_empty_ctor`]
25312        // pin on the M2 `:limits` typed slot (abd52c2).
25313        assert_eq!(
25314            MeshPolicy::default(),
25315            MeshPolicy::empty(),
25316            "MeshPolicy::default() must delegate through MeshPolicy::empty() \
25317             on every per-axis field — a mismatch means the manual Default \
25318             impl drifted off the substrate-canonical empty() constructor \
25319             (or the constructor drifted off the impl's expected shape)",
25320        );
25321    }
25322
25323    #[test]
25324    fn mesh_policy_empty_validates_ok() {
25325        // Fail-before-pass-after invariant pin on the empty-baseline
25326        // validate composition: the canonical unset [`MeshPolicy`]
25327        // (every one of the five `Option<_>`-carrying per-axis fields
25328        // set to `None`) must pass every gate on
25329        // [`MeshPolicy::validate`]. The invariant is structurally
25330        // guaranteed today — every per-axis value-shape gate on the
25331        // validate dispatch is `if let Some(_) = self.<axis>()` guarded
25332        // and every cross-axis arm on
25333        // [`MeshPolicy::first_cross_axis_violation`] is a
25334        // `let (Some(_), Some(_))` pattern, so an all-`None` input
25335        // short-circuits every arm before any zero-floor / canonical-
25336        // form / cap / pairwise-ordering check fires. Pinning the
25337        // composition here makes the invariant load-bearing so a
25338        // future extension of the validate surface that adds a
25339        // non-`Option`-guarded gate (a hypothetical cross-slot
25340        // coherence gate a future per-axis / per-slot fold on the M3
25341        // `:politicas` slot establishes on top of the current
25342        // pairwise-cross-axis composition per
25343        // `theory/MESH-COMPOSITION.md` §III.2, a per-arm
25344        // `mtls_required`-defaults-to-`true` admission overlay a
25345        // future admission webhook lands) that fires on the all-`None`
25346        // input trips here at caixa-core test time rather than at a
25347        // downstream consumer that composed [`MeshPolicy::default`]
25348        // (which now routes through [`MeshPolicy::empty`]) with
25349        // [`MeshPolicy::validate`] as its "no-op axis short-circuit"
25350        // and observed a spurious rejection on the canonical unset
25351        // baseline. Peer of the sibling
25352        // [`crate::limits::tests::limits_spec_empty_validates_ok`] pin
25353        // on the M2 `:limits` typed slot (abd52c2) — that one anchors
25354        // the invariant on the folded [`Default`] impl the
25355        // [`crate::LimitsSpec::empty`] constructor now backs; this one
25356        // extends it onto the M3 `:politicas` slot's folded impl.
25357        MeshPolicy::empty().validate().expect(
25358            "MeshPolicy::empty() must satisfy MeshPolicy::validate — \
25359             every per-axis value-shape gate is `if let Some(_)` guarded \
25360             and every cross-axis arm is a `let (Some(_), Some(_))` pattern, \
25361             so an all-`None` input short-circuits every arm; a spurious \
25362             rejection on the canonical unset baseline means a future \
25363             validate-side extension added a non-`Option`-guarded gate that \
25364             fires on empty input",
25365        );
25366    }
25367
25368    // ── shared duration codec: cross-slot integer-magnitude gate ──
25369    //
25370    // The integer-magnitude discipline applied to
25371    // `supervisor::duration_codec::parse` lifts onto every typed slot
25372    // that routes through the shared codec — `MeshPolicy::timeout`
25373    // (`:politicas :timeout`) and `CircuitBreaker::window`
25374    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
25375    // These cross-slot tests pin that the gate fires at the serde
25376    // layer for both typed slots, not just for the supervisor side.
25377
25378    #[test]
25379    fn policy_timeout_serde_rejects_fractional_seconds() {
25380        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
25381        // so the shared codec's integer-magnitude gate applies on
25382        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
25383        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
25384        // deserialize with the canonical-form diagnostic naming the
25385        // offending `"1.5"` and the remediation `"1500ms"`.
25386        let payload = r#"{"timeout":"1.5s"}"#;
25387        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25388        let msg = err.to_string();
25389        assert!(
25390            msg.contains("not a non-negative integer"),
25391            "expected integer-magnitude diagnostic in {msg:?}"
25392        );
25393        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
25394        assert!(
25395            msg.contains("\"1500ms\""),
25396            "missing canonical-form remediation in {msg:?}"
25397        );
25398    }
25399
25400    #[test]
25401    fn policy_timeout_serde_rejects_leading_plus_sign() {
25402        // Pin the leading-`+` arm cross-slot — the prior f64 parser
25403        // accepted `"+30s"` silently and round-tripped to `"30s"`.
25404        let payload = r#"{"timeout":"+30s"}"#;
25405        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25406        let msg = err.to_string();
25407        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
25408    }
25409
25410    #[test]
25411    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
25412        // `CircuitBreaker::window` uses `with =
25413        // "supervisor::duration_codec_required"` (the required-Duration
25414        // variant that delegates to the same shared parser). `"0.5m"`
25415        // parsed to 30s and round-tripped to `"30s"` on next emit —
25416        // DRIFT closed.
25417        let payload = format!(
25418            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
25419            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25420            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
25421        );
25422        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
25423        let msg = err.to_string();
25424        assert!(
25425            msg.contains("not a non-negative integer"),
25426            "expected integer-magnitude diagnostic in {msg:?}"
25427        );
25428        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
25429        assert!(
25430            msg.contains("\"30s\""),
25431            "missing canonical-form remediation in {msg:?}"
25432        );
25433    }
25434
25435    #[test]
25436    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
25437        // Pin the happy-path on the cross-slot side: every canonical
25438        // author shape `render` ever emits parses cleanly through the
25439        // shared codec on the `CircuitBreaker` slot. The
25440        // codec's accepted set (post-gate) is exactly its emitted set
25441        // for the integer-magnitude class.
25442        for window_lit in ["30s", "500ms", "2m", "1h"] {
25443            let payload = format!(
25444                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
25445                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
25446                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
25447            );
25448            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
25449                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
25450            });
25451            assert_eq!(cb.max_failures, 5);
25452        }
25453    }
25454
25455    // ── rate_limit_codec: integer-magnitude gate ──
25456    //
25457    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
25458    // / 737a676 / d53c922 trajectory landed on every typed-duration /
25459    // typed-byte-size codec in caixa-core lifts onto the fifth typed
25460    // codec — `rate_limit_codec` — through the digit-only magnitude
25461    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
25462    // These tests pin the gate at the serde layer for `:politicas
25463    // :rate-limit` (the only typed slot the codec backs), and at the
25464    // codec-internal `parse` layer for the canonical positive cases.
25465
25466    #[test]
25467    fn rate_limit_serde_rejects_fractional_rate() {
25468        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
25469        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
25470        // wording, which didn't name the canonical-form remediation or
25471        // the round-trip drift the next emit would produce. Now refused
25472        // at deserialize with the canonical-form diagnostic naming the
25473        // offending `"1.5"` magnitude and the round-trip drift wording.
25474        let payload = r#"{"rateLimit":"1.5/s"}"#;
25475        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25476        let msg = err.to_string();
25477        assert!(
25478            msg.contains("not a non-negative integer"),
25479            "expected integer-magnitude diagnostic in {msg:?}"
25480        );
25481        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
25482        assert!(
25483            msg.contains("THEORY.md"),
25484            "missing render-determinism contract citation in {msg:?}"
25485        );
25486    }
25487
25488    #[test]
25489    fn rate_limit_serde_rejects_leading_plus_sign() {
25490        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
25491        // permissive-`+` parse), so `"+100/s"` silently parsed to
25492        // `RateLimit { 100, 1s }` and round-tripped through `render` to
25493        // `"100/s"` — a *different* canonical string on the next emit,
25494        // breaking the THEORY.md Part V render-determinism contract
25495        // exactly the way the peer duration codecs' `"+30s"` case did.
25496        // This is the load-bearing class the digit-only gate closes
25497        // beyond what `u32::from_str`'s strictness covers on its own.
25498        let payload = r#"{"rateLimit":"+100/s"}"#;
25499        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25500        let msg = err.to_string();
25501        assert!(
25502            msg.contains("not a non-negative integer"),
25503            "expected integer-magnitude diagnostic in {msg:?}"
25504        );
25505        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
25506    }
25507
25508    #[test]
25509    fn rate_limit_serde_rejects_leading_minus_sign() {
25510        // The signed-negative arm: `"-1/s"` lands on the
25511        // non-canonical-but-numeric branch via the `i64` fallback (the
25512        // `f64` parse also succeeds), surfacing the canonical-form
25513        // diagnostic. Replaces the prior value-laundered "not a u32"
25514        // wording with the unified diagnostic across signs.
25515        let payload = r#"{"rateLimit":"-1/s"}"#;
25516        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25517        let msg = err.to_string();
25518        assert!(
25519            msg.contains("not a non-negative integer"),
25520            "expected integer-magnitude diagnostic in {msg:?}"
25521        );
25522        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
25523    }
25524
25525    #[test]
25526    fn rate_limit_serde_rejects_decimal_shaped_integer() {
25527        // `"100.0/s"` is integer-valued numerically but not in the
25528        // codec's accepted set — `render` emits `"100/s"`, so the
25529        // round-trip would drift. Lifted to the canonical-form
25530        // diagnostic peer with the duration codec's `"1.0s"` case
25531        // (1c55a2a).
25532        let payload = r#"{"rateLimit":"100.0/s"}"#;
25533        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25534        let msg = err.to_string();
25535        assert!(
25536            msg.contains("not a non-negative integer"),
25537            "expected integer-magnitude diagnostic in {msg:?}"
25538        );
25539        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
25540    }
25541
25542    #[test]
25543    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
25544        // Non-numeric, non-digit-only input lands on the existing
25545        // narrower `"not a u32"` arm (preserved for diagnostic-shape
25546        // stability on the parser-shape footgun case). Pin this so a
25547        // future relaxation of the numeric-fallback predicate doesn't
25548        // silently collapse garbage onto the canonical-form arm — same
25549        // partition the peer duration codecs draw between
25550        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
25551        let payload = r#"{"rateLimit":"abc/s"}"#;
25552        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25553        let msg = err.to_string();
25554        assert!(
25555            msg.contains("not a u32"),
25556            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
25557        );
25558        assert!(
25559            !msg.contains("not a non-negative integer"),
25560            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
25561        );
25562    }
25563
25564    #[test]
25565    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
25566        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
25567        // u32's range. The digit-only gate passes; `u32::from_str`
25568        // fails on overflow. Surface that with the overflow-shaped
25569        // diagnostic naming the offending magnitude verbatim, peer
25570        // with `supervisor::duration_codec`'s overflow arm. Pinning
25571        // the wording so a future refactor doesn't silently collapse
25572        // overflow onto the canonical-form arm.
25573        let payload = r#"{"rateLimit":"4294967296/s"}"#;
25574        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25575        let msg = err.to_string();
25576        assert!(
25577            msg.contains("overflows u32"),
25578            "expected overflow diagnostic in {msg:?}"
25579        );
25580        assert!(
25581            msg.contains("\"4294967296\""),
25582            "missing offending magnitude in {msg:?}"
25583        );
25584    }
25585
25586    #[test]
25587    fn rate_limit_serde_rejects_leading_zero_magnitude() {
25588        // `"0100/s"` is digit-only, so the existing
25589        // non-digit-only / sign / fractional arm doesn't catch it —
25590        // `u32::from_str("0100")` returns `Ok(100)`, so before this
25591        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
25592        // round-tripped through `render` to `"100/s"` — a *different*
25593        // canonical string on the next emit, breaking the THEORY.md
25594        // Part V render-determinism contract exactly the way the
25595        // peer `"+100/s"` case did before the leading-`+` arm landed.
25596        // This is the load-bearing class the leading-zero gate closes
25597        // beyond what the existing digit-only / sign / fractional
25598        // gates cover, and the peer arm to the leading-`+` test
25599        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
25600        // canonical-form-drift axis.
25601        let payload = r#"{"rateLimit":"0100/s"}"#;
25602        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25603        let msg = err.to_string();
25604        assert!(
25605            msg.contains("non-canonical leading zero"),
25606            "expected leading-zero diagnostic in {msg:?}"
25607        );
25608        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
25609        assert!(
25610            msg.contains("THEORY.md"),
25611            "missing render-determinism contract citation in {msg:?}"
25612        );
25613    }
25614
25615    #[test]
25616    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
25617        // `"00/s"` is the degenerate leading-zero case — every byte
25618        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
25619        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
25620        // a *different* canonical string, same render-determinism
25621        // violation. The single-byte `"0/s"` itself is in the
25622        // accepted set (round-trips losslessly through `render`,
25623        // refused downstream by `PolicyRateLimitZero`); the
25624        // multi-byte `"00/s"` is not. Pins the boundary between the
25625        // accepted single-`0` and the rejected leading-zero class.
25626        let payload = r#"{"rateLimit":"00/s"}"#;
25627        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25628        let msg = err.to_string();
25629        assert!(
25630            msg.contains("non-canonical leading zero"),
25631            "expected leading-zero diagnostic in {msg:?}"
25632        );
25633        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
25634    }
25635
25636    #[test]
25637    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
25638        // Cross-window pin — the gate is window-agnostic; the
25639        // leading-zero class is a property of the magnitude, not the
25640        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
25641        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
25642        // single-window coverage extended across the three canonical
25643        // windows the codec accepts.
25644        let payload = r#"{"rateLimit":"007/h"}"#;
25645        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25646        let msg = err.to_string();
25647        assert!(
25648            msg.contains("non-canonical leading zero"),
25649            "expected leading-zero diagnostic in {msg:?}"
25650        );
25651        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
25652    }
25653
25654    #[test]
25655    fn rate_limit_serde_rejects_leading_whitespace() {
25656        // `" 100/s"` — the canonical paste-from-aligned-doc /
25657        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
25658        // the top-level `s.trim()` silently ate the leading space and
25659        // parsed the value to `RateLimit { 100, 1s }`, which then
25660        // round-tripped through `render` to `"100/s"` (a *different*
25661        // canonical string on the next emit) — the exact
25662        // canonical-form-drift class the leading-`+` / leading-zero
25663        // arms already close, extended to the whitespace byte class.
25664        let payload = r#"{"rateLimit":" 100/s"}"#;
25665        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25666        let msg = err.to_string();
25667        assert!(
25668            msg.contains("contains whitespace byte"),
25669            "expected whitespace diagnostic in {msg:?}"
25670        );
25671        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
25672        assert!(
25673            msg.contains("THEORY.md"),
25674            "missing render-determinism contract citation in {msg:?}"
25675        );
25676    }
25677
25678    #[test]
25679    fn rate_limit_serde_rejects_trailing_whitespace() {
25680        // `"100/s "` — the canonical shell-history / trailing-space
25681        // paste footgun. Before this gate the top-level `s.trim()`
25682        // silently ate the trailing space and parsed to
25683        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
25684        // next emit — same canonical-form drift as the leading-space
25685        // sibling, closed on the same whitespace-byte arm.
25686        let payload = r#"{"rateLimit":"100/s "}"#;
25687        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25688        let msg = err.to_string();
25689        assert!(
25690            msg.contains("contains whitespace byte"),
25691            "expected whitespace diagnostic in {msg:?}"
25692        );
25693        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
25694    }
25695
25696    #[test]
25697    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
25698        // `"100 / s"` — the canonical typographically-spaced author
25699        // shape (the same idiom every prose reference to a rate limit
25700        // renders as, mistakenly retained when the value is pasted
25701        // into a codec-shaped slot). Before this gate the per-part
25702        // `rate_str.trim()` / `unit.trim()` calls silently ate both
25703        // spaces on either side of `/` and parsed to
25704        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
25705        // codec's *internal* whitespace-tolerance vector, orthogonal
25706        // to the leading / trailing surface but the same canonical-
25707        // form-drift class. Pins the arm as strictly stronger than the
25708        // pre-existing top-level `s.trim()` behavior: it fires on
25709        // whitespace anywhere in the value, not just at the string
25710        // boundary.
25711        let payload = r#"{"rateLimit":"100 / s"}"#;
25712        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25713        let msg = err.to_string();
25714        assert!(
25715            msg.contains("contains whitespace byte"),
25716            "expected whitespace diagnostic in {msg:?}"
25717        );
25718        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
25719    }
25720
25721    #[test]
25722    fn rate_limit_serde_rejects_tab_byte() {
25723        // `"\t100/s"` — the canonical paste-from-indented-doc /
25724        // paste-from-YAML-block-scalar footgun where a tab byte leads
25725        // the magnitude. Pins that the gate covers tab (`0x09`) as
25726        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
25727        // members and both would be silently swallowed by `s.trim()`
25728        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
25729        // space alone to the full ASCII-whitespace set (space `0x20`,
25730        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
25731        // the tab arm as a representative of the non-space members.
25732        let payload = r#"{"rateLimit":"\t100/s"}"#;
25733        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25734        let msg = err.to_string();
25735        assert!(
25736            msg.contains("contains whitespace byte"),
25737            "expected whitespace diagnostic in {msg:?}"
25738        );
25739        assert!(
25740            msg.contains("0x09"),
25741            "missing offending tab byte in {msg:?}"
25742        );
25743    }
25744
25745    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
25746    //
25747    // Successor to the ASCII-whitespace arm (1ad7755) on
25748    // `rate_limit_codec` — closes the strictly-complementary class the
25749    // byte-scan cannot see, through the lifted
25750    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
25751
25752    #[test]
25753    fn rate_limit_serde_rejects_leading_nbsp() {
25754        // NBSP prefix — paste-from-typography footgun. Byte-scan
25755        // misses, `str::trim` silently strips it, value drifts to
25756        // `"100/s"` on next serialize.
25757        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
25758        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25759        let msg = err.to_string();
25760        assert!(
25761            msg.contains("non-ASCII Unicode whitespace character"),
25762            "expected non-ASCII whitespace diagnostic in {msg:?}"
25763        );
25764        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
25765    }
25766
25767    #[test]
25768    fn rate_limit_serde_rejects_internal_em_space() {
25769        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
25770        // paste-from-typography footgun on the `<integer>/<unit>`
25771        // shape.
25772        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
25773        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
25774        let msg = err.to_string();
25775        assert!(
25776            msg.contains("non-ASCII Unicode whitespace character"),
25777            "expected non-ASCII whitespace diagnostic in {msg:?}"
25778        );
25779        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
25780    }
25781
25782    #[test]
25783    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
25784        // Positive-control pin: every ASCII-only canonical form the
25785        // renderer emits stays accepted through the new arm.
25786        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
25787            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
25788            let p: MeshPolicy = serde_json::from_str(&payload)
25789                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
25790            assert!(p.rate_limit.is_some());
25791        }
25792    }
25793
25794    #[test]
25795    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
25796        // The boundary case — `"0/s"` is the canonical form
25797        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
25798        // it at the parse layer; the downstream
25799        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
25800        // `rate == 0` at the typed-validate layer above. Pins the
25801        // partition: the leading-zero gate at the codec layer does
25802        // not poach the rate-zero semantic-validation arm at the
25803        // typed-validate layer above (a future stricter codec must
25804        // not reject `"0/s"` here, or it'd collapse the diagnostic
25805        // partitioning that lets `PolicyRateLimitZero` name the
25806        // offending typed slot).
25807        let payload = r#"{"rateLimit":"0/s"}"#;
25808        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
25809            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
25810        });
25811        let rl = policy.rate_limit.expect("rate_limit must be Some");
25812        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
25813        assert_eq!(
25814            rl.window,
25815            Duration::from_secs(1),
25816            "single-`0` magnitude with `s` unit must parse to window=1s"
25817        );
25818    }
25819
25820    #[test]
25821    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
25822        // The complementary boundary pin — every magnitude
25823        // `render` emits starts with `[1-9]` (or is the single byte
25824        // `"0"`), so the canonical-form predicate is `(len == 1) ||
25825        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
25826        // '1'` case explicitly so a future tightening of the gate
25827        // (e.g. an over-eager "no leading digit < 5" rule, or a
25828        // mistakenly anchored start-of-magnitude byte check) lands
25829        // here before the canonical-forms-iterating test would catch
25830        // it.
25831        let payload = r#"{"rateLimit":"100/s"}"#;
25832        let policy: MeshPolicy = serde_json::from_str(payload)
25833            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
25834        let rl = policy.rate_limit.expect("rate_limit must be Some");
25835        assert_eq!(
25836            rl.rate, 100,
25837            "canonical-100 magnitude must parse to rate=100"
25838        );
25839    }
25840
25841    #[test]
25842    fn rate_limit_serde_accepts_integer_canonical_forms() {
25843        // Pin the happy-path: every canonical author shape `render`
25844        // ever emits parses cleanly through the codec post-gate. The
25845        // codec's accepted set (post-gate) is exactly its emitted set
25846        // for the integer-magnitude class — same property
25847        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
25848        // gates guarantee on the peer codecs. Iterating across rate
25849        // magnitudes (including `"0"`, which the codec accepts even
25850        // though `validate_politicas` rejects `rate == 0` at the typed
25851        // layer above) closes the codec contract at the parse layer
25852        // independently of the validate layer.
25853        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
25854            for unit_lit in ["s", "m", "h"] {
25855                let lit = format!("{rate_lit}/{unit_lit}");
25856                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
25857                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
25858                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
25859                });
25860                let rl = policy.rate_limit.expect("rate_limit must be Some");
25861                assert_eq!(
25862                    rl.rate,
25863                    rate_lit.parse::<u32>().unwrap(),
25864                    "rate mismatch for {lit:?}"
25865                );
25866            }
25867        }
25868    }
25869
25870    #[test]
25871    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
25872        // The structural property the gate enforces: serialize ∘
25873        // deserialize is the identity on every canonical author shape.
25874        // Peer of `parse_byte_size`'s and `parse_duration`'s
25875        // `_round_trips_through_render_for_every_canonical_form` tests
25876        // on the rate-limit axis. Before the gate, `"+100/s"` violated
25877        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
25878        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
25879        for rate in [1u32, 100, 5000, 1_000_000] {
25880            for (window, unit) in [
25881                (Duration::from_secs(1), "s"),
25882                (Duration::from_secs(60), "m"),
25883                (Duration::from_secs(3600), "h"),
25884            ] {
25885                let policy = MeshPolicy {
25886                    rate_limit: Some(RateLimit { rate, window }),
25887                    ..Default::default()
25888                };
25889                let json = serde_json::to_string(&policy).unwrap();
25890                let expected = format!("\"{rate}/{unit}\"");
25891                assert!(
25892                    json.contains(&expected),
25893                    "expected {expected:?} in {json:?}"
25894                );
25895                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
25896                assert_eq!(
25897                    back.rate_limit, policy.rate_limit,
25898                    "round-trip for {json:?}"
25899                );
25900            }
25901        }
25902    }
25903
25904    // ── self-membership cross-slot gate ──────────────────────────────
25905
25906    #[test]
25907    fn validate_no_self_membership_rejects_self_named_membro() {
25908        // An Aplicacao whose `:membros` lists its own `:nome` is a
25909        // one-node lacre-closure recursion — rejected, naming the parent.
25910        let membros = vec![
25911            membro("catalog", "^0.1"),
25912            membro("checkout", "^0.1"),
25913            membro("cart", "^0.1"),
25914        ];
25915        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
25916        assert!(
25917            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
25918            "got {err:?}"
25919        );
25920    }
25921
25922    #[test]
25923    fn validate_no_self_membership_accepts_distinct_membros() {
25924        // Positive control: distinct member names (including a member
25925        // that is itself an Aplicacao — recursive composition is valid,
25926        // MESH-COMPOSITION §V) pass the gate.
25927        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
25928        validate_no_self_membership(&membros, "checkout").unwrap();
25929    }
25930
25931    #[test]
25932    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
25933        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
25934        // `NoMembros` arm (the more-fundamental "graph must have nodes"
25935        // gate), not by this cross-slot self-edge gate. Keeping the
25936        // self-membership predicate vacuously-ok on the empty input
25937        // matches its supervisor-axis peer
25938        // (`validate_no_self_supervision_empty_children_is_ok`) and
25939        // makes the gate composable from any future call site (an M4
25940        // CR materializer's per-membros validator) without re-checking
25941        // emptiness.
25942        validate_no_self_membership(&[], "checkout").unwrap();
25943    }
25944
25945    #[test]
25946    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
25947        // Pinning the Display: the self-membership diagnostic must name
25948        // the offending caixa verbatim + the "lists itself" framing the
25949        // author can grep for, so the cluster-far failure surfaces at
25950        // build time with one-line remediation. Same diagnostic shape
25951        // as the supervisor-axis `ChildSupervisesSelf` peer.
25952        let membros = vec![membro("orquestra", "^0.1")];
25953        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
25954        let msg = err.to_string();
25955        assert!(
25956            msg.contains("orquestra"),
25957            "diagnostic must name the offending caixa nome (got: {msg:?})"
25958        );
25959        assert!(
25960            msg.contains("lists itself"),
25961            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
25962        );
25963    }
25964
25965    #[test]
25966    fn default_servico_port_constant_pins_canonical_8080_literal() {
25967        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
25968        // at the verbatim `8080` literal both consumers (the
25969        // `Entrada::port` serde default via [`default_port`] and the
25970        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
25971        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
25972        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
25973        // discipline (a085b26) on the per-renderer canonical-K8s-axis
25974        // string-constant axis: a future refactor that drifts the
25975        // constant out from under either consumer surfaces here ahead
25976        // of every per-renderer's first emission. The literal value
25977        // matches the well-known HTTP-alt port the `pleme-computeunit`
25978        // library chart already emits as its `trigger.service.port`
25979        // default — by construction the same value the substrate
25980        // assumes about every Servico's in-cluster L4 listener.
25981        assert_eq!(
25982            DEFAULT_SERVICO_PORT, 8080,
25983            "canonical Servico port literal must remain `8080` verbatim — \
25984             this is the value both the `Entrada::port` serde default and the \
25985             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
25986        );
25987    }
25988
25989    #[test]
25990    fn default_port_helper_returns_canonical_servico_port_constant() {
25991        // The bridge-arm — pins that the [`default_port`] helper
25992        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
25993        // attribute hooks routes through the lifted
25994        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
25995        // literal. A future refactor that re-introduces the `8080`
25996        // literal at the helper's return site (silently re-opening
25997        // the drift footgun this lift closed) surfaces here ahead of
25998        // every author-side `(:entrada (:host … :para …))` slot
25999        // without an explicit `:port`. Peer with the
26000        // `default_namespace_re_export_points_at_caixa_core_canonical`
26001        // pin on the caixa-mesh-side re-export axis.
26002        assert_eq!(
26003            default_port(),
26004            DEFAULT_SERVICO_PORT,
26005            "the serde-default helper must route through the lifted constant"
26006        );
26007    }
26008
26009    #[test]
26010    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
26011        // The end-to-end pin — an author-surface `(:entrada (:host …
26012        // :para …))` without an explicit `:port` slot deserializes to
26013        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
26014        // verbatim. Routes the canonical lifted constant through both
26015        // the serde-default machinery (the `#[serde(default =
26016        // "default_port")]` attribute) and the typed-value-shape
26017        // contract (the resulting [`Entrada::port`] value). A future
26018        // refactor that drifts either axis — replacing the serde
26019        // hook's helper, changing the typed slot's wire shape — would
26020        // surface here before any per-renderer's CNP / Gateway /
26021        // HTTPRoute emission consumed the drifted default.
26022        let entrada: Entrada =
26023            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
26024        assert_eq!(
26025            entrada.port, DEFAULT_SERVICO_PORT,
26026            "the serde default must materialize as the lifted canonical Servico port"
26027        );
26028    }
26029
26030    #[test]
26031    fn servico_port_min_pins_canonical_accept_set_floor() {
26032        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
26033        // verbatim `1` literal every typed `:entrada :port` acceptance
26034        // gate keys off. Peer with the
26035        // [`default_servico_port_constant_pins_canonical_8080_literal`]
26036        // discipline on the canonical-Servico-port-constant axis: a
26037        // future refactor that drifts the accept-set floor out from
26038        // under the sole consumer at [`AplicacaoSpec::validate`]'s
26039        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
26040        // every per-`:entrada` `EntradaPortZero` diagnostic. The
26041        // literal value matches the IANA-registered TCP/UDP port
26042        // space floor (`1..=65535` — port `0` is the "any ephemeral"
26043        // sentinel, not a well-defined destination the substrate's
26044        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
26045        // axis can honor).
26046        assert_eq!(
26047            SERVICO_PORT_MIN, 1,
26048            "canonical Servico port accept-set floor must remain `1` verbatim — \
26049             this is the value the `AplicacaoSpec::validate` gate at \
26050             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
26051        );
26052    }
26053
26054    #[test]
26055    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
26056        // The cross-const invariant pin — the substrate's canonical
26057        // default port must satisfy its own accept-set floor by
26058        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
26059        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
26060        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
26061        // override the operator pins through a future
26062        // `:placement :default-port` slot that lands out-of-range, a
26063        // per-edition Servico-port migration that lifted the floor
26064        // above the previous default without coordinating the pair —
26065        // would silently invalidate the serde-default emission at
26066        // every author-side `(:entrada (:host … :para …))` slot
26067        // without an explicit `:port`: the default port would fall
26068        // below the accept-set floor, the `AplicacaoSpec::validate`
26069        // gate would reject every default-carrying Aplicacao as
26070        // `EntradaPortZero`, and the substrate's typed
26071        // `(defcaixa … :kind Aplicacao)` surface would fail validate
26072        // on every Aplicacao whose author omitted `:entrada :port`
26073        // for the substrate's chosen default — a class of authoring-
26074        // surface footguns the compile-time pin structurally closes.
26075        // Peer with the
26076        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
26077        // (27f9b34) cross-const invariant pin discipline on the peer
26078        // canonical-Helm-per-values-block child-chart-enablement-toggle
26079        // axis pair.
26080        const {
26081            assert!(
26082                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
26083                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
26084                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
26085                 every default-carrying `(:entrada (:host … :para …))` slot \
26086                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
26087                 through the serde default hook and must pass the \
26088                 `AplicacaoSpec::validate` floor gate by construction",
26089            );
26090        }
26091    }
26092
26093    #[test]
26094    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
26095        // The gate-site pin — asserts the `AplicacaoSpec::validate`
26096        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
26097        // `EntradaPortZero` diagnostic on the below-floor input
26098        // `port: 0` (the only below-floor value the `u16` field can
26099        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
26100        // is the singleton `{0}`). A future refactor that drifts the
26101        // gate off the lifted const (silently re-introducing an
26102        // inline `if e.port == 0` byte-check) surfaces here — the
26103        // pin cannot distinguish `< 1` from `== 0` on the current
26104        // floor, but it *does* pin that the diagnostic fires on `0`
26105        // through whichever gate is wired, so any future accept-set
26106        // floor migration (a hypothetical unprivileged-only
26107        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
26108        // update this test alongside the const declaration —
26109        // structurally guaranteeing the gate + accept-set + pin
26110        // trio move together. Peer with the
26111        // [`rejects_zero_entrada_port`] behavioral pin on the same
26112        // per-`:entrada :port` axis — that pin asserts the pre-lift
26113        // behavioral contract (`port: 0` → `EntradaPortZero`); this
26114        // pin adds the structural link to the lifted floor const.
26115        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
26116        let mut s = three_member_spec();
26117        s.entrada.as_mut().unwrap().port = 0;
26118        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
26119    }
26120
26121    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
26122
26123    #[test]
26124    fn membro_serde_keys_match_lifted_membro_key_consts() {
26125        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
26126        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
26127        // name the exact camelCase JSON keys the
26128        // `#[serde(rename_all = "camelCase")]` attribute on
26129        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
26130        // that each canonical byte-sequence appears verbatim in the
26131        // JSON — a future accidental `rename_all = "snake_case"` /
26132        // `"kebab-case"` / verbatim-field-name flip at the derive
26133        // attribute (any of which would silently break every downstream
26134        // JSON consumer that reaches for one of the two consts via
26135        // `Value::get(...)`) surfaces here as a build-time test failure
26136        // at `aplicacao.rs`, not as an apply-time
26137        // `.get(<stale-canonical-const>)` returning `None` far from the
26138        // derive-attr drift's commit. Peer with the sibling
26139        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
26140        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
26141        // same discipline the SupervisorSpec top-level lift established,
26142        // extended here to the M3 [`Membro`] per-`:membros` axis.
26143        let m = Membro {
26144            caixa: "catalog".into(),
26145            versao: "^0.1".into(),
26146        };
26147        let json = serde_json::to_string(&m).unwrap();
26148        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26149            let quoted = format!("\"{key}\"");
26150            assert!(
26151                json.contains(&quoted),
26152                "serialized Membro must carry the lifted MEMBRO_KEY_* \
26153                 byte-sequence {quoted} verbatim in the JSON emission \
26154                 (got: {json})",
26155            );
26156        }
26157    }
26158
26159    #[test]
26160    fn membro_key_consts_are_pairwise_distinct() {
26161        // Cross-axis drift-detection pin: a future collapse of the two
26162        // canonical [`Membro`] per-entry byte-strings onto the same
26163        // value (e.g. an accidental copy-paste flip of
26164        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
26165        // silently reroute every downstream probe on one axis onto the
26166        // sibling axis's overlay entry and pass every propagation-probe
26167        // test that expected only the stale axis's value. Peer of the
26168        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
26169        // (40cc4e5).
26170        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
26171        for (i, a) in all.iter().enumerate() {
26172            for b in all.iter().skip(i + 1) {
26173                assert_ne!(
26174                    a, b,
26175                    "MEMBRO_KEY_* consts must be pairwise-distinct \
26176                     canonical byte-sequences — got `{a}` == `{b}`",
26177                );
26178            }
26179        }
26180    }
26181
26182    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
26183    //    URL-path fallback resolver every HTTPRoute-aware renderer
26184    //    reaching for a per-rule path-list resolution routes through.
26185    //    The four pin tests below fix the four-way accept-set the
26186    //    resolver must always honor: (:paths-non-empty-verbatim,
26187    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
26188    //    :paths-preserves-order-across-multiple-entries) — drift on any
26189    //    arm surfaces at caixa-core build time rather than at cluster-
26190    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
26191    //    sibling `:politicas` typed-primitive dispatch axis.
26192
26193    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
26194        Entrada {
26195            host: "example.com".into(),
26196            para: "cart".into(),
26197            paths: paths.into_iter().map(String::from).collect(),
26198            port: DEFAULT_SERVICO_PORT,
26199        }
26200    }
26201
26202    #[test]
26203    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
26204        // The typed `:entrada :paths` slot carries an author-declared
26205        // list — the resolver returns each entry verbatim, no
26206        // catch-all substitution. The canonical "author declared
26207        // paths, honor them verbatim" arm of the path-list dispatch.
26208        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
26209        assert_eq!(
26210            e.resolved_paths(),
26211            vec!["/api/cart", "/api/products"],
26212            "resolved_paths must return each `:entrada :paths` entry \
26213             verbatim when the typed slot is non-empty (got {:?})",
26214            e.resolved_paths(),
26215        );
26216    }
26217
26218    #[test]
26219    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
26220        // Empty `:entrada :paths` slot — the resolver substitutes the
26221        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
26222        // catch-all fallback verbatim. Pins the empty-arm of the
26223        // resolver's four-way accept-set against a future silent
26224        // detour that returned an empty Vec (which would emit an
26225        // HTTPRoute with zero rules — silently dropping every
26226        // external `:entrada` flow at admission time), routed to a
26227        // different fallback shape, or dropped the catch-all
26228        // altogether.
26229        let e = entrada_with_paths(vec![]);
26230        assert_eq!(
26231            e.resolved_paths(),
26232            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
26233            "resolved_paths on empty `:entrada :paths` must fall back \
26234             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
26235             all — got {:?}",
26236            e.resolved_paths(),
26237        );
26238    }
26239
26240    #[test]
26241    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
26242        // Single-entry `:entrada :paths` — the resolver returns the
26243        // single declared path verbatim, NOT the catch-all fallback
26244        // (author declared a path, honor it — the empty-arm and the
26245        // len-1 arm are semantically distinct axes of the resolver's
26246        // accept-set). Pins that the resolver treats "author declared
26247        // one path" as authored input, not as the empty case.
26248        let e = entrada_with_paths(vec!["/api/only"]);
26249        assert_eq!(
26250            e.resolved_paths(),
26251            vec!["/api/only"],
26252            "resolved_paths on single-entry `:entrada :paths` must \
26253             return the declared path verbatim, NOT the catch-all \
26254             fallback (got {:?})",
26255            e.resolved_paths(),
26256        );
26257    }
26258
26259    #[test]
26260    fn resolved_paths_preserves_author_declared_order() {
26261        // The `:entrada :paths` list is author-ordered — the resolver
26262        // preserves the author's declaration order verbatim, since
26263        // per-rule dispatch order at the K8s Gateway API HTTPRoute
26264        // consumer is significant (first-match-wins under the
26265        // path-prefix matcher). Pins against a future silent
26266        // re-sort / dedup / normalize detour that reordered author
26267        // input.
26268        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
26269        assert_eq!(
26270            e.resolved_paths(),
26271            vec!["/z/last", "/a/first", "/m/mid"],
26272            "resolved_paths must preserve author-declared `:entrada \
26273             :paths` order verbatim — got {:?}",
26274            e.resolved_paths(),
26275        );
26276    }
26277
26278    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
26279    //    slot `&[String]` slice accessor every per-`:entrada` consumer
26280    //    that must see the author's declaration verbatim (not the
26281    //    fallback-applied projection the sibling `resolved_paths`
26282    //    returns) routes through. The three pin tests below fix the
26283    //    accept-set the accessor must honor: (:non-empty-byte-equal,
26284    //    :empty-projects-empty-slice, :preserves-author-declared-order)
26285    //    — drift on any arm surfaces at caixa-core build time rather
26286    //    than at cluster-apply time. Peer discipline with the sibling
26287    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
26288    //    peer M3 mesh-slot `Vec<String>`-carry axis.
26289
26290    #[test]
26291    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
26292        // Byte-equal pin: [`Entrada::paths`] must project the raw
26293        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
26294        // slice borrowed from the typed slot's own [`Vec<String>`]
26295        // storage — no re-ordering, no dedup, no per-entry normalization,
26296        // no fallback substitution (the fallback-applying projection is
26297        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
26298        // a future silent detour that re-normalized the list, dropped
26299        // duplicates the [`AplicacaoSpec::validate`]
26300        // `EntradaPathDuplicate` refusal already rejects at build time,
26301        // or (most severe) accidentally routed through the fallback-
26302        // applying sibling and returned the substrate catch-all when
26303        // the author declared an empty list — collapsing the raw-slot
26304        // and fallback-applied axes into one and breaking the
26305        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
26306        //
26307        // Peer of the sibling
26308        // [`Placement::clusters`]-shape byte-equal pin
26309        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
26310        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
26311        let fixtures: Vec<Vec<String>> = vec![
26312            Vec::new(),
26313            vec!["/api/cart".into()],
26314            vec!["/api/cart".into(), "/api/products".into()],
26315            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
26316        ];
26317        for paths in fixtures {
26318            let e = Entrada {
26319                host: "example.com".into(),
26320                para: "cart".into(),
26321                paths: paths.clone(),
26322                port: DEFAULT_SERVICO_PORT,
26323            };
26324            assert_eq!(
26325                e.paths(),
26326                paths.as_slice(),
26327                "Entrada::paths must return :entrada :paths verbatim \
26328                 (got {:?}, expected {:?})",
26329                e.paths(),
26330                paths.as_slice(),
26331            );
26332            assert_eq!(
26333                e.paths(),
26334                e.paths.as_slice(),
26335                "Entrada::paths accessor and .paths.as_slice() field \
26336                 access must byte-equal — the accessor is the substrate-\
26337                 primitive typed dispatch every downstream per-`:entrada` \
26338                 raw-slot path-list consumer must route through",
26339            );
26340            assert_eq!(
26341                e.paths().len(),
26342                e.paths.len(),
26343                "Entrada::paths().len() must byte-equal self.paths.len() \
26344                 — a length drift would silently split the paired \
26345                 pre-flight cascade-head `.is_empty()` probe input in \
26346                 the sibling [`Entrada::resolved_paths`] resolver from \
26347                 the per-entry validate loop's traversal input in \
26348                 [`AplicacaoSpec::validate`]",
26349            );
26350        }
26351    }
26352
26353    #[test]
26354    fn resolved_paths_reads_through_lifted_paths_accessor() {
26355        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
26356        // pre-flight `.paths().is_empty()` cascade-head probe (which
26357        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
26358        // catch-all fallback arm when the accessor projects the empty
26359        // slice) and the per-entry `.paths().iter().map(String::as_str)`
26360        // projection (which must reach every entry in the same order
26361        // the accessor projects, so the sibling
26362        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
26363        // per-entry projection stay in lockstep by construction) must
26364        // both key off the lifted accessor. Pins the two-site coherence
26365        // by exercising each production consumer end-to-end: (1) the
26366        // catch-all-fallback arm under the empty slice, (2) the
26367        // author-declared-verbatim arm under a two-entry cohort whose
26368        // per-entry projection must byte-equal the input's per-entry
26369        // author-declared paths in the author's declared order.
26370        //
26371        // Peer of the sibling M3
26372        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
26373        // `validate_placement_reads_through_lifted_clusters_accessor`
26374        // on the sibling `Placement::clusters` reader-site convergence.
26375        let empty = entrada_with_paths(vec![]);
26376        assert_eq!(
26377            empty.resolved_paths(),
26378            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
26379            "resolved_paths on empty :entrada :paths must trip the \
26380             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
26381             catch-all fallback — routing through the lifted paths() \
26382             accessor must not silently drop the fallback arm",
26383        );
26384
26385        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
26386        assert_eq!(
26387            declared.resolved_paths(),
26388            vec!["/api/cart", "/api/products"],
26389            "resolved_paths on non-empty :entrada :paths must return each \
26390             entry verbatim in the author's declared order — routing \
26391             through the lifted paths() accessor must not silently \
26392             reorder or drop entries",
26393        );
26394        // Byte-equal pin against the raw-slot accessor to keep the
26395        // fallback-applying resolver's per-entry projection input in
26396        // lockstep with the raw-slot accessor's projection.
26397        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
26398        assert_eq!(
26399            declared.resolved_paths(),
26400            raw_projected,
26401            "resolved_paths non-empty projection must byte-equal the \
26402             lifted paths() accessor's per-entry String::as_str projection \
26403             — the two projections share the same input slice by \
26404             construction, so any drift here would surface a silent \
26405             re-ordering / dedup / normalization detour in the resolver",
26406        );
26407    }
26408
26409    #[test]
26410    fn validate_reads_through_lifted_entrada_paths_accessor() {
26411        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
26412        // per-entry value-shape gate's `for p in e.paths()` traversal
26413        // (which must reach every entry in the same order the accessor
26414        // projects, so both the per-entry `EntradaPathEmpty` /
26415        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
26416        // the duplicate-detection HashSet insert that trips
26417        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
26418        // projection) must route through the lifted accessor. Pins the
26419        // coherence by exercising each production consumer end-to-end:
26420        // (1) the `EntradaPathEmpty` refusal fires on the second entry
26421        // of a two-entry cohort whose head is valid but tail is empty
26422        // (which requires the loop to reach the second entry through
26423        // the accessor), and (2) the `EntradaPathDuplicate` refusal
26424        // fires on the second entry of a two-entry cohort that shares
26425        // a path (which requires the loop to reach both entries — a
26426        // first-entry-only projection would silently pass since the
26427        // dedup HashSet has room for the first insert).
26428        //
26429        // Peer of the sibling
26430        // `validate_placement_reads_through_lifted_clusters_accessor`
26431        // on the sibling `Placement::clusters` reader-site convergence.
26432        let base = crate::AplicacaoSpec {
26433            membros: vec![crate::Membro {
26434                caixa: "cart".into(),
26435                versao: "^0.1".into(),
26436            }],
26437            contratos: Vec::new(),
26438            politicas: crate::MeshPolicy::default(),
26439            placement: crate::Placement {
26440                estrategia: crate::PlacementStrategy::SingleNode,
26441                clusters: vec!["rio".into()],
26442                shard_key: None,
26443                affinity: None,
26444            },
26445            entrada: Some(Entrada {
26446                host: "example.com".into(),
26447                para: "cart".into(),
26448                paths: vec!["/api/cart".into(), String::new()],
26449                port: DEFAULT_SERVICO_PORT,
26450            }),
26451        };
26452        assert_eq!(
26453            base.validate(),
26454            Err(crate::AplicacaoError::EntradaPathEmpty),
26455            "validate must trip EntradaPathEmpty on the second entry of \
26456             a two-entry cohort — routing through the lifted paths() \
26457             accessor must not silently short-circuit the loop at the \
26458             valid head entry",
26459        );
26460
26461        let mut dup = base;
26462        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
26463        assert_eq!(
26464            dup.validate(),
26465            Err(crate::AplicacaoError::EntradaPathDuplicate {
26466                path: "/api/cart".into(),
26467            }),
26468            "validate must trip EntradaPathDuplicate on the second entry \
26469             of a two-entry cohort that shares a path — routing through \
26470             the lifted paths() accessor must not silently short-circuit \
26471             the dedup HashSet insert at the first entry",
26472        );
26473    }
26474
26475    // ── Entrada::hostname / Entrada::hostnames — the substrate-
26476    //    canonical per-`:entrada` DNS-hostname resolver pair every
26477    //    Gateway-API-aware renderer reaching for a per-listener
26478    //    singular `hostname:` filter (Gateway) or a per-route plural
26479    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
26480    //    The three pin tests below fix the two-way accept-set the pair
26481    //    must always honor: (:singular-byte-equal-to-host,
26482    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
26483    //    on any arm surfaces at caixa-core build time rather than at
26484    //    cluster-apply time when the API server refuses the HTTPRoute
26485    //    for non-intersecting hostname filters. Peer discipline with
26486    //    the sibling `resolved_paths` accept-set pin block above on the
26487    //    per-`:entrada` path-list resolver axis.
26488
26489    fn entrada_with_host(host: &str) -> Entrada {
26490        Entrada {
26491            host: host.into(),
26492            para: "cart".into(),
26493            paths: Vec::new(),
26494            port: DEFAULT_SERVICO_PORT,
26495        }
26496    }
26497
26498    #[test]
26499    fn hostname_returns_entrada_host_byte_equal() {
26500        // The canonical singular-axis pin: [`Entrada::hostname`] must
26501        // return the `:entrada :host` field byte-for-byte, borrowed
26502        // from the typed slot's own [`String`] storage. Pins against a
26503        // future silent detour that re-normalized the host (an
26504        // accidental `.to_lowercase()` — validate_entrada_host already
26505        // enforces lowercase, so any re-normalization is redundant + a
26506        // drift surface between the validator and the accessor), a
26507        // trailing-`.` fully-qualified DNS shape substitution, or a
26508        // Punycode round-trip that lowered a Unicode host through IDNA.
26509        let e = entrada_with_host("checkout.quero.cloud");
26510        assert_eq!(
26511            e.hostname(),
26512            "checkout.quero.cloud",
26513            "Entrada::hostname must return :entrada :host verbatim \
26514             (got {:?})",
26515            e.hostname(),
26516        );
26517        assert_eq!(
26518            e.hostname(),
26519            e.host.as_str(),
26520            "Entrada::hostname must byte-equal the .host field access",
26521        );
26522    }
26523
26524    #[test]
26525    fn hostnames_returns_singleton_of_hostname_accessor() {
26526        // The pair-invariant pin: [`Entrada::hostnames`] must always
26527        // return exactly `vec![hostname()]` — the singleton list whose
26528        // sole entry is the substrate's canonical per-`:entrada`
26529        // singular hostname. Pins the two-consumer coherence axis: the
26530        // Gateway listener's singular `hostname:` filter and the
26531        // HTTPRoute's plural `spec.hostnames[]` filter list must
26532        // agree, else the Gateway API v1.x conformance layer rejects
26533        // the HTTPRoute at attach time with
26534        // `Accepted:False/NoMatchingParent` (the parent Gateway's
26535        // listener hostname doesn't intersect the route's hostname
26536        // filter list) — a divergence whose apply-time symptom is far
26537        // from any single-site commit and never surfaces in the
26538        // emitted YAML. Pinning the pair-invariant here makes any
26539        // future accidental split (an accidental `.to_string() + "."`
26540        // trailing-`.` on the plural side that didn't land on the
26541        // singular side, an accidental prefix stripping on one axis,
26542        // an accidental wildcard prepend the SNI fan-out overlay
26543        // authors on the plural side without a paired singular
26544        // migration) trip at caixa-core build time.
26545        let e = entrada_with_host("checkout.quero.cloud");
26546        assert_eq!(
26547            e.hostnames(),
26548            vec![e.hostname()],
26549            "Entrada::hostnames must return `vec![hostname()]` under \
26550             the pair-invariant — got {:?} vs. singleton {:?}",
26551            e.hostnames(),
26552            vec![e.hostname()],
26553        );
26554    }
26555
26556    #[test]
26557    fn hostnames_is_singleton_under_single_host_author_surface() {
26558        // The singleton-shape pin: under today's single-hostname-per-
26559        // `:entrada` author surface (the `:host` slot is a single
26560        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
26561        // must always return a list of length exactly one. Pins
26562        // against a future silent detour that returned an empty list
26563        // (which would emit an HTTPRoute with `spec.hostnames: []` —
26564        // matching every incoming Host header regardless of the
26565        // Aplicacao's declared ingress apex, silently over-matching
26566        // every foreign VirtualHost the parent Gateway also fronts) or
26567        // a duplicated entry (which the Gateway API v1.x parser
26568        // accepts as a `[]-length-2 list of equal hostnames]` but
26569        // whose semantics differ from the intended singleton). The
26570        // author-surface extension point ("a future `:entrada
26571        // :alt-hosts` list overlay" the docstring names) is the sole
26572        // future axis that flips this pin — that migration will re-
26573        // author this test to pin the new plural cardinality.
26574        let e = entrada_with_host("checkout.quero.cloud");
26575        assert_eq!(
26576            e.hostnames().len(),
26577            1,
26578            "Entrada::hostnames must be a singleton under today's \
26579             single-hostname-per-`:entrada` author surface — got \
26580             length {}: {:?}",
26581            e.hostnames().len(),
26582            e.hostnames(),
26583        );
26584    }
26585
26586    // ── Entrada::destination — the substrate-canonical per-`:entrada`
26587    //    destination-Servico scalar accessor every Gateway-API
26588    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
26589    //    discriminator arg (HTTPRoute name composer) or a per-rule
26590    //    `backendRefs[0].name` axis routes through. The two pin tests
26591    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
26592    //    either arm surfaces at caixa-core build time rather than at
26593    //    cluster-apply time when an HTTPRoute's `metadata.name` and
26594    //    `backendRefs[]` silently disagree on which destination Servico
26595    //    the ingress fronts. Peer discipline with the sibling
26596    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
26597    //    blocks above on the per-`:entrada` path-list / DNS-hostname
26598    //    resolver axes.
26599
26600    #[test]
26601    fn destination_returns_entrada_para_byte_equal() {
26602        // The canonical destination-scalar pin: [`Entrada::destination`]
26603        // must return the `:entrada :para` field byte-for-byte, borrowed
26604        // from the typed slot's own [`String`] storage. Pins against a
26605        // future silent detour that re-normalized the destination (an
26606        // accidental `.to_lowercase()` — the destination Servico is
26607        // already validated as a DNS-1123 label upstream, so any
26608        // re-normalization is redundant + a drift surface between the
26609        // validator and the accessor), a namespace-prefix rewrite (an
26610        // accidental `format!("{namespace}/{para}")` per-CR fully-
26611        // qualified rewrite that didn't land on the peer axis), or a
26612        // per-cluster suffix stamp the operator authors on one
26613        // consumer without the other.
26614        for para in ["cart", "checkout", "catalog", "orders-v2"] {
26615            let e = Entrada {
26616                host: "checkout.quero.cloud".into(),
26617                para: para.into(),
26618                paths: Vec::new(),
26619                port: DEFAULT_SERVICO_PORT,
26620            };
26621            assert_eq!(
26622                e.destination(),
26623                para,
26624                "Entrada::destination must return :entrada :para verbatim \
26625                 (got {:?}, expected {para:?})",
26626                e.destination(),
26627            );
26628            assert_eq!(
26629                e.destination(),
26630                e.para.as_str(),
26631                "Entrada::destination must byte-equal the .para field access",
26632            );
26633        }
26634    }
26635
26636    #[test]
26637    fn destination_borrows_from_entrada_para_storage() {
26638        // The borrow-not-copy pin: [`Entrada::destination`] must
26639        // return a `&str` slice that borrows from the typed slot's
26640        // own [`String`] storage — same-address invariant with
26641        // `entrada.para.as_str()`. Pins against a future silent detour
26642        // that allocated a fresh `String` (`self.para.clone()` in the
26643        // body would type-check but silently drop the borrow, and
26644        // every downstream consumer that assumed the returned slice
26645        // outlives `&self` would break on a stale-reference use-after-
26646        // free). Peer with the sibling `hostname_returns_entrada_
26647        // host_byte_equal` on the singular-DNS-hostname axis.
26648        let e = entrada_with_host("checkout.quero.cloud");
26649        let dest = e.destination();
26650        let para_slice = e.para.as_str();
26651        assert_eq!(
26652            dest.as_ptr(),
26653            para_slice.as_ptr(),
26654            "Entrada::destination must borrow from the .para String's \
26655             backing storage — a fresh allocation here means the \
26656             accessor no longer names the substrate-primitive typed \
26657             dispatch and every downstream consumer would silently \
26658             carry a detached copy",
26659        );
26660        assert_eq!(
26661            dest.len(),
26662            para_slice.len(),
26663            "Entrada::destination and .para.as_str() must byte-equal in \
26664             length as well as in address",
26665        );
26666    }
26667
26668    #[test]
26669    fn port_returns_entrada_port_verbatim_across_permutations() {
26670        // The canonical L4-port-scalar pin: [`Entrada::port`] must
26671        // return the `:entrada :port` field verbatim as a `u16` across
26672        // every author-declared value in the validated accept-set
26673        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
26674        // silent detour that clamped the port (an accidental
26675        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
26676        // land on the peer [`AplicacaoSpec::port_for_destination`]
26677        // resolver), rewrote it through a per-cluster port-remap table
26678        // the operator authors on one consumer without the other, or
26679        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
26680        // serde-default value (which would silently collapse the
26681        // distinction between "author explicitly declared `:port 8080`"
26682        // and "author omitted the slot and inherited the default" the
26683        // future per-cluster override slot depends on). Peer with the
26684        // sibling `destination_returns_entrada_para_byte_equal` +
26685        // `hostname_returns_entrada_host_byte_equal` pins on the
26686        // per-`:entrada` `&str` scalar axes.
26687        for port in [
26688            SERVICO_PORT_MIN,
26689            DEFAULT_SERVICO_PORT,
26690            8443u16,
26691            9090u16,
26692            u16::MAX,
26693        ] {
26694            let e = Entrada {
26695                host: "checkout.quero.cloud".into(),
26696                para: "cart".into(),
26697                paths: Vec::new(),
26698                port,
26699            };
26700            assert_eq!(
26701                e.port(),
26702                port,
26703                "Entrada::port must return :entrada :port verbatim \
26704                 (got {}, expected {port})",
26705                e.port(),
26706            );
26707            assert_eq!(
26708                e.port(),
26709                e.port,
26710                "Entrada::port accessor and .port field access must \
26711                 byte-equal — the accessor is the substrate-primitive \
26712                 typed dispatch every downstream L4-port consumer must \
26713                 route through",
26714            );
26715        }
26716    }
26717
26718    #[test]
26719    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
26720        // Two-consumer coherence pin: the
26721        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
26722        // (which reads through [`Entrada::port`] to compare against
26723        // [`SERVICO_PORT_MIN`]) and the
26724        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
26725        // through [`Entrada::port`] to emit the per-destination
26726        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
26727        // lifted accessor, so any future rebrand on the typed slot's
26728        // reader shape lands at exactly one place. Pins the two-site
26729        // coherence by exercising a below-floor port through validate
26730        // (which must reject) and a validated in-accept-set port through
26731        // port_for_destination (which must emit the same value the
26732        // accessor returns).
26733        let mut spec = three_member_spec();
26734        if let Some(e) = spec.entrada.as_mut() {
26735            e.port = 0;
26736        }
26737        assert_eq!(
26738            spec.validate().unwrap_err(),
26739            AplicacaoError::EntradaPortZero,
26740            "validate must reject `:entrada :port 0` through the lifted \
26741             Entrada::port accessor — port zero lies below \
26742             SERVICO_PORT_MIN and the validator routes through port() \
26743             to name the floor",
26744        );
26745
26746        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
26747            let mut spec = three_member_spec();
26748            if let Some(e) = spec.entrada.as_mut() {
26749                e.port = port;
26750            }
26751            spec.validate().expect(
26752                "entrada with in-accept-set :port must validate — the \
26753                 structural-floor gate reads through Entrada::port",
26754            );
26755            let entrada_ref = spec.entrada().expect(":entrada present");
26756            assert_eq!(
26757                spec.port_for_destination(entrada_ref.destination()),
26758                entrada_ref.port(),
26759                "port_for_destination(entrada.destination()) must equal \
26760                 entrada.port() — the two consumers of the per-:entrada \
26761                 L4-port axis (validator, per-destination resolver) both \
26762                 route through Entrada::port",
26763            );
26764        }
26765    }
26766
26767    #[test]
26768    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
26769        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
26770        // must return the `:contratos :de` field byte-for-byte, borrowed
26771        // from the typed slot's own [`String`] storage. Peer of the
26772        // sibling `destination_returns_entrada_para_byte_equal` pin on
26773        // the per-`:entrada` axis — same "the substrate-primitive
26774        // accessor must byte-equal the raw field access verbatim across
26775        // every author-declared value" discipline extended to the
26776        // per-`:contratos` caller arm. Pins against a future silent
26777        // detour that re-normalized the caller (an accidental
26778        // `.to_lowercase()` — every `:contratos :de` is validated as a
26779        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
26780        // re-normalization is redundant + a drift surface between the
26781        // validator and the accessor), a namespace-prefix rewrite (an
26782        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
26783        // rewrite that didn't land on the peer axis), or a per-cluster
26784        // suffix stamp the operator authors on one consumer without the
26785        // other.
26786        for de in ["cart", "checkout", "catalog", "orders-v2"] {
26787            let c = WitContract {
26788                de: de.into(),
26789                para: "downstream".into(),
26790                wit: "wasi:http/proxy".into(),
26791                endpoint: Some("/lookup".into()),
26792                subject: None,
26793                slot: None,
26794            };
26795            assert_eq!(
26796                c.source(),
26797                de,
26798                "WitContract::source must return :contratos :de verbatim \
26799                 (got {:?}, expected {de:?})",
26800                c.source(),
26801            );
26802            assert_eq!(
26803                c.source(),
26804                c.de.as_str(),
26805                "WitContract::source must byte-equal the .de field access",
26806            );
26807        }
26808    }
26809
26810    #[test]
26811    fn wit_contract_source_borrows_from_de_storage() {
26812        // The borrow-not-copy pin: [`WitContract::source`] must return a
26813        // `&str` slice that borrows from the typed slot's own [`String`]
26814        // storage — same-address invariant with `c.de.as_str()`. Pins
26815        // against a future silent detour that allocated a fresh `String`
26816        // (`self.de.clone()` in the body would type-check but silently
26817        // drop the borrow, and every downstream consumer that assumed
26818        // the returned slice outlives `&self` would break on a stale-
26819        // reference use-after-free). Peer of the sibling
26820        // `destination_borrows_from_entrada_para_storage` on the
26821        // per-`:entrada` axis.
26822        let c = WitContract {
26823            de: "cart".into(),
26824            para: "catalog".into(),
26825            wit: "wasi:http/proxy".into(),
26826            endpoint: Some("/lookup".into()),
26827            subject: None,
26828            slot: None,
26829        };
26830        let src = c.source();
26831        let de_slice = c.de.as_str();
26832        assert_eq!(
26833            src.as_ptr(),
26834            de_slice.as_ptr(),
26835            "WitContract::source must borrow from the .de String's \
26836             backing storage — a fresh allocation here means the \
26837             accessor no longer names the substrate-primitive typed \
26838             dispatch and every downstream consumer would silently \
26839             carry a detached copy",
26840        );
26841        assert_eq!(
26842            src.len(),
26843            de_slice.len(),
26844            "WitContract::source and .de.as_str() must byte-equal in \
26845             length as well as in address",
26846        );
26847    }
26848
26849    #[test]
26850    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
26851        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
26852        // must return the `:contratos :para` field byte-for-byte,
26853        // borrowed from the typed slot's own [`String`] storage. Peer of
26854        // the sibling `destination_returns_entrada_para_byte_equal` on
26855        // the per-`:entrada` axis — both accessors name "the destination-
26856        // Servico byte-string" concept on their respective mesh-slot
26857        // atoms (per-ingress apex vs. per-typed-edge callee) and both
26858        // must project the underlying `.para` field verbatim so every
26859        // downstream renderer that composes them with peer accessors
26860        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
26861        // per-edge L4 port emit site) reads the same byte-string the
26862        // author declared.
26863        for para in ["catalog", "payment", "orders", "inventory-v3"] {
26864            let c = WitContract {
26865                de: "cart".into(),
26866                para: para.into(),
26867                wit: "wasi:http/proxy".into(),
26868                endpoint: Some("/lookup".into()),
26869                subject: None,
26870                slot: None,
26871            };
26872            assert_eq!(
26873                c.destination(),
26874                para,
26875                "WitContract::destination must return :contratos :para \
26876                 verbatim (got {:?}, expected {para:?})",
26877                c.destination(),
26878            );
26879            assert_eq!(
26880                c.destination(),
26881                c.para.as_str(),
26882                "WitContract::destination must byte-equal the .para \
26883                 field access",
26884            );
26885        }
26886    }
26887
26888    #[test]
26889    fn wit_contract_destination_borrows_from_para_storage() {
26890        // The borrow-not-copy pin: [`WitContract::destination`] must
26891        // return a `&str` slice that borrows from the typed slot's own
26892        // [`String`] storage — same-address invariant with
26893        // `c.para.as_str()`. Peer of the sibling
26894        // `destination_borrows_from_entrada_para_storage` on the
26895        // per-`:entrada` axis.
26896        let c = WitContract {
26897            de: "cart".into(),
26898            para: "catalog".into(),
26899            wit: "wasi:http/proxy".into(),
26900            endpoint: Some("/lookup".into()),
26901            subject: None,
26902            slot: None,
26903        };
26904        let dest = c.destination();
26905        let para_slice = c.para.as_str();
26906        assert_eq!(
26907            dest.as_ptr(),
26908            para_slice.as_ptr(),
26909            "WitContract::destination must borrow from the .para \
26910             String's backing storage — a fresh allocation here means \
26911             the accessor no longer names the substrate-primitive typed \
26912             dispatch and every downstream consumer would silently \
26913             carry a detached copy",
26914        );
26915        assert_eq!(
26916            dest.len(),
26917            para_slice.len(),
26918            "WitContract::destination and .para.as_str() must byte-equal \
26919             in length as well as in address",
26920        );
26921    }
26922
26923    #[test]
26924    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
26925        // The canonical per-`:contratos` WIT-world-reference scalar pin:
26926        // [`WitContract::world_ref`] must return the `:contratos :wit`
26927        // field byte-for-byte, borrowed from the typed slot's own
26928        // [`String`] storage. Sibling of the peer per-`:contratos`
26929        // [`WitContract::source`] / [`WitContract::destination`]
26930        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
26931        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
26932        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
26933        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
26934        // "the substrate-primitive accessor must byte-equal the raw
26935        // field access verbatim across every author-declared value"
26936        // discipline extended to the per-`:contratos` WIT-world arm.
26937        // Pins against a future silent detour that re-canonicalized the
26938        // WIT world reference (an accidental `.to_lowercase()` pass that
26939        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
26940        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
26941        // gate is already lowercase-prefixed so any re-normalization is
26942        // redundant + a drift surface between the validator and the
26943        // accessor), an M4-promotion-shape rewrite that formatted a
26944        // typed WIT-world enum through [`Display`] and silently drifted
26945        // the printer output from the source `caixa.lisp`, or a per-
26946        // cluster WIT-alias rewrite that didn't land on the peer field-
26947        // access sites. Five values sweep the shape-dispatch accept-set
26948        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
26949        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
26950        // `wasi:keyvalue/`).
26951        for (wit, endpoint, subject, slot) in [
26952            ("wasi:http/proxy", Some("/lookup"), None, None),
26953            ("http:proxy", Some("/health"), None, None),
26954            ("nats:pub-sub", None, Some("orders.paid"), None),
26955            ("kafka:events", None, Some("checkout-events"), None),
26956            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
26957        ] {
26958            let c = WitContract {
26959                de: "cart".into(),
26960                para: "downstream".into(),
26961                wit: wit.into(),
26962                endpoint: endpoint.map(str::to_string),
26963                subject: subject.map(str::to_string),
26964                slot: slot.map(str::to_string),
26965            };
26966            assert_eq!(
26967                c.world_ref(),
26968                wit,
26969                "WitContract::world_ref must return :contratos :wit \
26970                 verbatim (got {:?}, expected {wit:?})",
26971                c.world_ref(),
26972            );
26973            assert_eq!(
26974                c.world_ref(),
26975                c.wit.as_str(),
26976                "WitContract::world_ref must byte-equal the .wit field \
26977                 access",
26978            );
26979        }
26980    }
26981
26982    #[test]
26983    fn wit_contract_world_ref_borrows_from_wit_storage() {
26984        // The borrow-not-copy pin: [`WitContract::world_ref`] must
26985        // return a `&str` slice that borrows from the typed slot's own
26986        // [`String`] storage — same-address invariant with
26987        // `c.wit.as_str()`. Pins against a future silent detour that
26988        // allocated a fresh `String` (`self.wit.clone()` in the body
26989        // would type-check but silently drop the borrow, and every
26990        // downstream consumer that assumed the returned slice outlives
26991        // `&self` would break on a stale-reference use-after-free — the
26992        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
26993        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
26994        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
26995        // / [`is_pubsub`][WitContract::is_pubsub] /
26996        // [`is_store`][WitContract::is_store] methods route through —
26997        // each borrow from the WitContract's own storage and each would
26998        // silently misbehave if this accessor produced a detached copy).
26999        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
27000        // [`WitContract::destination`] and per-`:entrada`
27001        // [`Entrada::destination`] / [`Entrada::hostname`] and
27002        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
27003        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
27004        let c = WitContract {
27005            de: "cart".into(),
27006            para: "catalog".into(),
27007            wit: "wasi:http/proxy".into(),
27008            endpoint: Some("/lookup".into()),
27009            subject: None,
27010            slot: None,
27011        };
27012        let world = c.world_ref();
27013        let wit_slice = c.wit.as_str();
27014        assert_eq!(
27015            world.as_ptr(),
27016            wit_slice.as_ptr(),
27017            "WitContract::world_ref must borrow from the .wit String's \
27018             backing storage — a fresh allocation here means the \
27019             accessor no longer names the substrate-primitive typed \
27020             dispatch and every downstream consumer would silently carry \
27021             a detached copy",
27022        );
27023        assert_eq!(
27024            world.len(),
27025            wit_slice.len(),
27026            "WitContract::world_ref and .wit.as_str() must byte-equal in \
27027             length as well as in address",
27028        );
27029    }
27030
27031    #[test]
27032    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
27033        // Sibling-triple invariant pin composing all three per-`:contratos`
27034        // substrate-primitive typed dispatches — [`WitContract::source`]
27035        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
27036        // [`WitContract::world_ref`] — at the joint
27037        // `(source(), destination(), world_ref())` call shape every
27038        // renderer that fans on per-edge caller-callee-shape identity
27039        // keys off. The invariant, evaluated per-contract:
27040        //
27041        //   (c.source(), c.destination(), c.world_ref())
27042        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
27043        //
27044        // Closes the last unlifted per-`:contratos` scalar axis — every
27045        // downstream consumer that reads the triple now routes through
27046        // exactly three typed dispatches on the substrate primitive,
27047        // not two typed + one open-coded field access. A future refactor
27048        // that silently split any one accessor's projection (an
27049        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
27050        // canonicalization that didn't reach the peer `source`/
27051        // `destination` arms, an accidental `source()` per-cluster
27052        // caller-alias rewrite that didn't land on the `world_ref` peer)
27053        // surfaces at caixa-core build time. Peer of the sibling per-
27054        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
27055        // per-`:entrada` `(hostname(), destination())` (6db982c /
27056        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
27057        // axes, extended to the per-`:contratos` triple.
27058        for (de, para, wit, endpoint, subject, slot) in [
27059            (
27060                "cart",
27061                "catalog",
27062                "wasi:http/proxy",
27063                Some("/lookup"),
27064                None,
27065                None,
27066            ),
27067            (
27068                "checkout",
27069                "orders",
27070                "nats:pub-sub",
27071                None,
27072                Some("orders.paid"),
27073                None,
27074            ),
27075            (
27076                "cart",
27077                "kv",
27078                "wasi:keyvalue/store",
27079                None,
27080                None,
27081                Some("carts/{cart_id}"),
27082            ),
27083            (
27084                "orders-v2",
27085                "inventory-v3",
27086                "http:proxy",
27087                Some("/reserve"),
27088                None,
27089                None,
27090            ),
27091        ] {
27092            let c = WitContract {
27093                de: de.into(),
27094                para: para.into(),
27095                wit: wit.into(),
27096                endpoint: endpoint.map(str::to_string),
27097                subject: subject.map(str::to_string),
27098                slot: slot.map(str::to_string),
27099            };
27100            assert_eq!(
27101                (c.source(), c.destination(), c.world_ref()),
27102                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
27103                "(WitContract::source, ::destination, ::world_ref) must \
27104                 project (.de, .para, .wit) verbatim across every author-\
27105                 declared triple (got ({:?}, {:?}, {:?}), expected \
27106                 ({de:?}, {para:?}, {wit:?}))",
27107                c.source(),
27108                c.destination(),
27109                c.world_ref(),
27110            );
27111        }
27112    }
27113
27114    #[test]
27115    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
27116        // The canonical per-`:contratos` owned-form caller-callee-pair
27117        // pin: [`WitContract::edge_pair`] must return the
27118        // `(source(), destination())` tuple in owned form byte-for-byte,
27119        // projected through the lifted [`WitContract::source`] /
27120        // [`WitContract::destination`] scalar accessors. Pins the
27121        // composite-projection invariant on the per-`:contratos`
27122        // mesh-slot atom — every author-declared `(de, para)` pair must
27123        // round-trip verbatim through the substrate primitive's typed
27124        // dispatch, so the nine [`AplicacaoError`] diagnostic-
27125        // construction sites the accessor now feeds
27126        // ([`AplicacaoError::EmptyWit`],
27127        // [`AplicacaoError::ContratoEndpointEmpty`],
27128        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
27129        // [`AplicacaoError::ContratoEndpointInvalid`],
27130        // [`AplicacaoError::ContratoSubjectEmpty`],
27131        // [`AplicacaoError::ContratoSubjectInvalid`],
27132        // [`AplicacaoError::ContratoSlotEmpty`],
27133        // [`AplicacaoError::ContratoSlotInvalid`],
27134        // [`AplicacaoError::ContratoDuplicate`]) all read the same
27135        // `(de, para)` label pair every author sees at the source
27136        // `caixa.lisp`. Pins against a future silent detour that swapped
27137        // the `.0` / `.1` arms (an accidental `(destination(),
27138        // source())` re-order in the body would silently invert every
27139        // downstream diagnostic's `de:` / `para:` label pair, silently
27140        // reversing the direction of every operator-facing typed error
27141        // arrow), a fresh-allocation shape drift (an accidental
27142        // `.to_string()` on one arm but not the other would leave the
27143        // owned/borrowed pair mismatched vs. the sibling `source()` /
27144        // `destination()` returns), or an M4 per-cluster caller/callee-
27145        // alias rewrite that landed on `source()` without reaching
27146        // `destination()` (or vice versa). Peer of the sibling per-
27147        // `:contratos` `(source, destination, world_ref)` triple
27148        // pin above on the mesh-slot-atom scalar-value axes, extended
27149        // to the owned-form pair-projection axis.
27150        for (de, para, wit, endpoint, subject, slot) in [
27151            (
27152                "cart",
27153                "catalog",
27154                "wasi:http/proxy",
27155                Some("/lookup"),
27156                None,
27157                None,
27158            ),
27159            (
27160                "checkout",
27161                "orders",
27162                "nats:pub-sub",
27163                None,
27164                Some("orders.paid"),
27165                None,
27166            ),
27167            (
27168                "cart",
27169                "kv",
27170                "wasi:keyvalue/store",
27171                None,
27172                None,
27173                Some("carts/{cart_id}"),
27174            ),
27175            (
27176                "orders-v2",
27177                "inventory-v3",
27178                "http:proxy",
27179                Some("/reserve"),
27180                None,
27181                None,
27182            ),
27183        ] {
27184            let c = WitContract {
27185                de: de.into(),
27186                para: para.into(),
27187                wit: wit.into(),
27188                endpoint: endpoint.map(str::to_string),
27189                subject: subject.map(str::to_string),
27190                slot: slot.map(str::to_string),
27191            };
27192            assert_eq!(
27193                c.edge_pair(),
27194                (de.to_string(), para.to_string()),
27195                "WitContract::edge_pair must return (:contratos :de, \
27196                 :contratos :para) as an owned tuple verbatim (got {:?}, \
27197                 expected ({de:?}, {para:?}))",
27198                c.edge_pair(),
27199            );
27200        }
27201    }
27202
27203    #[test]
27204    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
27205        // The composition pin: [`WitContract::edge_pair`] must return
27206        // exactly `(source().to_string(), destination().to_string())` —
27207        // the owned form of the sibling accessor pair — so any future
27208        // refactor that silently re-authored the caller-arm / callee-arm
27209        // projection to bypass the lifted scalar accessors (an accidental
27210        // `(self.de.clone(), self.para.clone())` regression back to the
27211        // raw field-access shape, an M4-typed-caller-enum `Display`
27212        // re-canonicalization on `source()` that didn't reach
27213        // `edge_pair()`, a per-cluster alias rewrite the operator lands
27214        // on `destination()` without reaching this composite projection)
27215        // trips at caixa-core build time. Pins the "typed dispatch
27216        // composes with typed dispatch, not with raw field access"
27217        // discipline every downstream diagnostic-construction site now
27218        // routes through — a `de:` / `para:` label pair whose
27219        // projection silently drifted off the substrate primitive's
27220        // scalar accessors would silently split the diagnostic's self-
27221        // locating signal from the source `caixa.lisp` author's view.
27222        // Peer of the sibling per-`:politicas` `is_empty` /
27223        // `validate_politicas` accessor-routing-pin family on the M3
27224        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
27225        let c = WitContract {
27226            de: "cart".into(),
27227            para: "catalog".into(),
27228            wit: "wasi:http/proxy".into(),
27229            endpoint: Some("/lookup".into()),
27230            subject: None,
27231            slot: None,
27232        };
27233        assert_eq!(
27234            c.edge_pair(),
27235            (c.source().to_string(), c.destination().to_string()),
27236            "WitContract::edge_pair must compose exactly \
27237             (source().to_string(), destination().to_string()) — a \
27238             bypass of either sibling accessor here would silently \
27239             decouple the composite-projection axis from the \
27240             substrate-primitive scalar accessors every downstream \
27241             consumer routes through",
27242        );
27243    }
27244
27245    #[test]
27246    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
27247     {
27248        // The canonical per-`:contratos` owned-form
27249        // caller-callee-world-ref-triple pin:
27250        // [`WitContract::edge_triple`] must return the
27251        // `(source(), destination(), world_ref())` tuple in owned form
27252        // byte-for-byte, projected through the lifted
27253        // [`WitContract::source`] / [`WitContract::destination`] /
27254        // [`WitContract::world_ref`] scalar accessors. Pins the
27255        // composite-projection invariant on the per-`:contratos`
27256        // mesh-slot atom — every author-declared `(de, para, wit)`
27257        // triple must round-trip verbatim through the substrate
27258        // primitive's typed dispatch, so the nine
27259        // [`AplicacaoError`] diagnostic-construction sites the
27260        // accessor now feeds (the [`WitTarget`]-dispatch's eight
27261        // wrong-target / missing-target / invalid-wit / capability-
27262        // with-payload arms in [`WitContract::target`], plus the
27263        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
27264        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
27265        // read the same `(de, para, wit)` triple every author sees at
27266        // the source `caixa.lisp`. Pins against a future silent
27267        // detour that swapped any two arms (an accidental `(destination(),
27268        // source(), world_ref())` re-order in the body would silently
27269        // invert every downstream diagnostic's `de:` / `para:` label
27270        // pair, silently reversing the direction of every operator-
27271        // facing typed error arrow), a fresh-allocation shape drift
27272        // (an accidental `.to_string()` skipped on one arm would leave
27273        // the owned/borrowed triple mismatched vs. the sibling
27274        // `source()` / `destination()` / `world_ref()` returns), or an
27275        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
27276        // canonicalization pass that landed on one accessor without
27277        // reaching the peers. Peer of the sibling per-`:contratos`
27278        // caller-callee-pair
27279        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
27280        // pin on the mesh-slot-atom composite-projection axis,
27281        // extended to the triple-projection axis.
27282        for (de, para, wit, endpoint, subject, slot) in [
27283            (
27284                "cart",
27285                "catalog",
27286                "wasi:http/proxy",
27287                Some("/lookup"),
27288                None,
27289                None,
27290            ),
27291            (
27292                "checkout",
27293                "orders",
27294                "nats:pub-sub",
27295                None,
27296                Some("orders.paid"),
27297                None,
27298            ),
27299            (
27300                "cart",
27301                "kv",
27302                "wasi:keyvalue/store",
27303                None,
27304                None,
27305                Some("carts/{cart_id}"),
27306            ),
27307            (
27308                "orders-v2",
27309                "inventory-v3",
27310                "http:proxy",
27311                Some("/reserve"),
27312                None,
27313                None,
27314            ),
27315        ] {
27316            let c = WitContract {
27317                de: de.into(),
27318                para: para.into(),
27319                wit: wit.into(),
27320                endpoint: endpoint.map(str::to_string),
27321                subject: subject.map(str::to_string),
27322                slot: slot.map(str::to_string),
27323            };
27324            assert_eq!(
27325                c.edge_triple(),
27326                (de.to_string(), para.to_string(), wit.to_string()),
27327                "WitContract::edge_triple must return (:contratos :de, \
27328                 :contratos :para, :contratos :wit) as an owned triple \
27329                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
27330                c.edge_triple(),
27331            );
27332        }
27333    }
27334
27335    #[test]
27336    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
27337        // The composition pin: [`WitContract::edge_triple`] must return
27338        // exactly `(source().to_string(), destination().to_string(),
27339        // world_ref().to_string())` — the owned form of the sibling
27340        // scalar-accessor triple — so any future refactor that silently
27341        // re-authored one arm's projection to bypass the lifted scalar
27342        // accessors (an accidental `(self.de.clone(), self.para.clone(),
27343        // self.wit.clone())` regression back to the raw field-access
27344        // shape the internal `edge` closure and the ContratoDuplicate
27345        // diagnostic both carried before this lift landed, an
27346        // M4-typed-caller-enum `Display` re-canonicalization on
27347        // `source()` that didn't reach `edge_triple()`, a per-cluster
27348        // alias rewrite the operator lands on `destination()` /
27349        // `world_ref()` without reaching this composite projection)
27350        // trips at caixa-core build time. Pins the "typed dispatch
27351        // composes with typed dispatch, not with raw field access"
27352        // discipline every downstream diagnostic-construction site now
27353        // routes through — a `de:` / `para:` / `wit:` triple whose
27354        // projection silently drifted off the substrate primitive's
27355        // scalar accessors would silently split the diagnostic's self-
27356        // locating signal from the source `caixa.lisp` author's view.
27357        // Peer of the sibling per-`:contratos` edge_pair composition-
27358        // pin above on the mesh-slot-atom composite-projection axis.
27359        let c = WitContract {
27360            de: "cart".into(),
27361            para: "catalog".into(),
27362            wit: "wasi:http/proxy".into(),
27363            endpoint: Some("/lookup".into()),
27364            subject: None,
27365            slot: None,
27366        };
27367        assert_eq!(
27368            c.edge_triple(),
27369            (
27370                c.source().to_string(),
27371                c.destination().to_string(),
27372                c.world_ref().to_string(),
27373            ),
27374            "WitContract::edge_triple must compose exactly \
27375             (source().to_string(), destination().to_string(), \
27376             world_ref().to_string()) — a bypass of any sibling accessor \
27377             here would silently decouple the composite-projection axis \
27378             from the substrate-primitive scalar accessors every \
27379             downstream consumer routes through",
27380        );
27381    }
27382
27383    #[test]
27384    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
27385        // The canonical semantics-pin: [`WitContract::edge_triple`] must
27386        // project the full `(de, para, wit)` identity of a `:contratos`
27387        // edge — the sub-triple every triple-carrying
27388        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
27389        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
27390        // missing-target, capability-with-payload, invalid-wit, and the
27391        // duplicate-gate). Rejects a drift in shape (an accidental
27392        // silent detour that returned a `(de, para)` pair or added an
27393        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
27394        // would trip here because the return type would no longer
27395        // pattern-match the eight `let (de, para, wit) = edge();`
27396        // destructures the [`WitContract::target`] dispatch feeds off
27397        // + the paired duplicate-gate `let (de, para, wit) =
27398        // c.edge_triple();` destructure in
27399        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
27400        // `:contratos` caller-callee-pair pin above extended to the
27401        // triple projection surface: closes the "one composite
27402        // accessor per typed diagnostic-construction sub-tuple"
27403        // discipline on the per-`:contratos` mesh-slot-atom axis.
27404        let c = WitContract {
27405            de: "checkout".into(),
27406            para: "orders".into(),
27407            wit: "nats:pub-sub".into(),
27408            endpoint: None,
27409            subject: Some("orders.paid".into()),
27410            slot: None,
27411        };
27412        let (de, para, wit) = c.edge_triple();
27413        assert_eq!(de, "checkout");
27414        assert_eq!(para, "orders");
27415        assert_eq!(wit, "nats:pub-sub");
27416    }
27417
27418    #[test]
27419    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
27420     {
27421        // The composition pin: [`WitContract::identity`] must return
27422        // exactly `(source(), destination(), world_ref(), endpoint(),
27423        // subject(), slot())` — the borrowed form of the six-scalar-
27424        // accessor identity axis. Any future refactor that silently
27425        // re-authored one arm's projection to bypass a scalar accessor
27426        // (a `self.de.as_str()` regression back to raw field access on
27427        // any of the three required arms, a `self.endpoint.as_deref()`
27428        // regression on any of the three optional arms, an M4 per-
27429        // cluster caller/callee-alias rewrite the operator lands on
27430        // `source()` / `destination()` without reaching this composite
27431        // projection) trips at caixa-core build time. Sweeps four
27432        // permutations of the WIT-shape × payload lattice — HTTP with
27433        // endpoint, pub-sub with subject, store with slot, payload-less
27434        // capability — so every payload arm is exercised. Peer of the
27435        // sibling per-`:contratos`
27436        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
27437        // composition pin on the mesh-slot-atom composite-projection
27438        // axis; extends the discipline from the (de, para, wit) prefix
27439        // onto the full-identity axis carrying the three payload arms.
27440        for (de, para, wit, endpoint, subject, slot) in [
27441            (
27442                "cart",
27443                "catalog",
27444                "wasi:http/proxy",
27445                Some("/lookup"),
27446                None,
27447                None,
27448            ),
27449            (
27450                "checkout",
27451                "orders",
27452                "nats:pub-sub",
27453                None,
27454                Some("orders.paid"),
27455                None,
27456            ),
27457            (
27458                "cart",
27459                "kv",
27460                "wasi:keyvalue/store",
27461                None,
27462                None,
27463                Some("carts/{cart_id}"),
27464            ),
27465            ("audit", "sink", "wasi:logging", None, None, None),
27466        ] {
27467            let c = WitContract {
27468                de: de.into(),
27469                para: para.into(),
27470                wit: wit.into(),
27471                endpoint: endpoint.map(str::to_owned),
27472                subject: subject.map(str::to_owned),
27473                slot: slot.map(str::to_owned),
27474            };
27475            assert_eq!(
27476                c.identity(),
27477                (
27478                    c.source(),
27479                    c.destination(),
27480                    c.world_ref(),
27481                    c.endpoint(),
27482                    c.subject(),
27483                    c.slot(),
27484                ),
27485                "WitContract::identity must compose exactly \
27486                 (source(), destination(), world_ref(), endpoint(), \
27487                 subject(), slot()) — a bypass of any sibling accessor \
27488                 here would silently decouple the identity-projection \
27489                 axis from the substrate-primitive scalar accessors \
27490                 every dedup-key consumer routes through",
27491            );
27492        }
27493    }
27494
27495    #[test]
27496    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
27497        // The canonical semantics-pin: [`WitContract::identity`] must
27498        // project the six-axis (de, para, wit, endpoint, subject, slot)
27499        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
27500        // gate keys off — two `WitContract`s that agree on all six axes
27501        // are the same typed edge declared twice, the graph-edge
27502        // analogue of duplicate `:membros` / `:placement :clusters` /
27503        // `:entrada :paths` entries. Rejects a shape drift (an
27504        // accidental silent detour that returned a prefix tuple or
27505        // added an extra field) by pattern-matching the six-arm shape.
27506        // Peer of the sibling per-`:contratos`
27507        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
27508        // pin extended from the (de, para, wit) prefix onto the full
27509        // six-axis identity that the dedup key rides.
27510        let c = WitContract {
27511            de: "cart".into(),
27512            para: "catalog".into(),
27513            wit: "wasi:http/proxy".into(),
27514            endpoint: Some("/products/:id".into()),
27515            subject: None,
27516            slot: None,
27517        };
27518        let (de, para, wit, endpoint, subject, slot) = c.identity();
27519        assert_eq!(de, "cart");
27520        assert_eq!(para, "catalog");
27521        assert_eq!(wit, "wasi:http/proxy");
27522        assert_eq!(endpoint, Some("/products/:id"));
27523        assert_eq!(subject, None);
27524        assert_eq!(slot, None);
27525
27526        // Two byte-identical contracts must produce equal identities —
27527        // the dedup key's foundational invariant.
27528        let c2 = c.clone();
27529        assert_eq!(c.identity(), c2.identity());
27530
27531        // Any change on any of the six axes must break the identity —
27532        // sweeps by mutating one axis at a time.
27533        let mut mutated = c.clone();
27534        mutated.de = "search".into();
27535        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
27536        let mut mutated = c.clone();
27537        mutated.para = "warehouse".into();
27538        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
27539        let mut mutated = c.clone();
27540        mutated.wit = "http:legacy".into();
27541        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
27542        let mut mutated = c.clone();
27543        mutated.endpoint = Some("/search".into());
27544        assert_ne!(
27545            c.identity(),
27546            mutated.identity(),
27547            "endpoint axis must partition"
27548        );
27549        let mut mutated = c.clone();
27550        mutated.subject = Some("orders.paid".into());
27551        assert_ne!(
27552            c.identity(),
27553            mutated.identity(),
27554            "subject axis must partition"
27555        );
27556        let mut mutated = c;
27557        mutated.slot = Some("carts/{id}".into());
27558        assert_ne!(mutated.identity().5, None, "slot axis must partition");
27559    }
27560
27561    #[test]
27562    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
27563        // The canonical per-`:contratos` structural-self-edge pin:
27564        // [`WitContract::is_self_loop`] must return `true` when the
27565        // `:de` and `:para` fields agree byte-for-byte, across every
27566        // WIT-shape variant the per-edge shape family carries. Pins
27567        // the shape-agnostic identity-space partition the
27568        // [`AplicacaoSpec::validate`] self-edge gate at
27569        // caixa-core/src/aplicacao.rs:5559 fires against — all four
27570        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
27571        // under the same one predicate. Four permutations sweep the
27572        // accept-set: HTTP with endpoint, pub-sub with subject, KV
27573        // store with slot, and payload-less capability.
27574        for (nome, wit, endpoint, subject, slot) in [
27575            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
27576            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
27577            (
27578                "kv",
27579                "wasi:keyvalue/store",
27580                None,
27581                None,
27582                Some("carts/{cart_id}"),
27583            ),
27584            ("audit", "wasi:logging", None, None, None),
27585        ] {
27586            let c = WitContract {
27587                de: nome.into(),
27588                para: nome.into(),
27589                wit: wit.into(),
27590                endpoint: endpoint.map(str::to_string),
27591                subject: subject.map(str::to_string),
27592                slot: slot.map(str::to_string),
27593            };
27594            assert!(
27595                c.is_self_loop(),
27596                "WitContract::is_self_loop must return true when \
27597                 :contratos :de == :contratos :para (got false on \
27598                 {nome:?} under {wit:?})",
27599            );
27600        }
27601    }
27602
27603    #[test]
27604    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
27605        // The complement pin: [`WitContract::is_self_loop`] must return
27606        // `false` on every well-shaped inter-Servico contract (the
27607        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
27608        // names — "Servico A calls Servico B" between two distinct
27609        // graph nodes). Pins against a future silent detour that
27610        // inverted the predicate (an accidental `!= ` swap for `==`
27611        // would silently reject every legitimate inter-Servico edge
27612        // and admit every self-edge — the exact inversion of the
27613        // author-intended shape). Four permutations sweep the same
27614        // WIT-shape accept-set the sibling positive-arm test carries.
27615        for (de, para, wit, endpoint, subject, slot) in [
27616            (
27617                "cart",
27618                "catalog",
27619                "wasi:http/proxy",
27620                Some("/lookup"),
27621                None,
27622                None,
27623            ),
27624            (
27625                "checkout",
27626                "orders",
27627                "nats:pub-sub",
27628                None,
27629                Some("orders.paid"),
27630                None,
27631            ),
27632            (
27633                "cart",
27634                "kv",
27635                "wasi:keyvalue/store",
27636                None,
27637                None,
27638                Some("carts/{cart_id}"),
27639            ),
27640            ("audit", "sink", "wasi:logging", None, None, None),
27641        ] {
27642            let c = WitContract {
27643                de: de.into(),
27644                para: para.into(),
27645                wit: wit.into(),
27646                endpoint: endpoint.map(str::to_string),
27647                subject: subject.map(str::to_string),
27648                slot: slot.map(str::to_string),
27649            };
27650            assert!(
27651                !c.is_self_loop(),
27652                "WitContract::is_self_loop must return false when \
27653                 :contratos :de differs from :contratos :para (got true \
27654                 on {de:?} → {para:?} under {wit:?})",
27655            );
27656        }
27657    }
27658
27659    #[test]
27660    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
27661        // The composition pin: [`WitContract::is_self_loop`] must
27662        // resolve to exactly `self.source() == self.destination()` —
27663        // the equality probe of the sibling scalar-accessor pair — so
27664        // any future refactor that silently re-authored the predicate
27665        // to bypass the lifted scalar accessors (an accidental
27666        // `self.de == self.para` regression back to the raw field-
27667        // access shape, an M4-typed-caller-enum identity-comparison
27668        // rule that landed on `source()` without reaching
27669        // `destination()`, a per-cluster alias rewrite the operator
27670        // pins on `destination()` without reaching this predicate)
27671        // trips at caixa-core build time. Pins the "typed dispatch
27672        // composes with typed dispatch, not with raw field access"
27673        // discipline the sibling [`WitContract::edge_pair`] /
27674        // [`WitContract::edge_triple`] composite-projection accessors
27675        // already carry, extended onto the per-edge endpoint-equality
27676        // predicate axis. Positive and complement arms both fire.
27677        let self_edge = WitContract {
27678            de: "cart".into(),
27679            para: "cart".into(),
27680            wit: "wasi:http/proxy".into(),
27681            endpoint: Some("/lookup".into()),
27682            subject: None,
27683            slot: None,
27684        };
27685        assert_eq!(
27686            self_edge.is_self_loop(),
27687            self_edge.source() == self_edge.destination(),
27688            "WitContract::is_self_loop must compose exactly \
27689             `source() == destination()` — a bypass of either sibling \
27690             accessor here would silently decouple the endpoint-\
27691             equality predicate from the substrate-primitive scalar \
27692             accessors every downstream consumer routes through",
27693        );
27694        let inter_edge = WitContract {
27695            de: "cart".into(),
27696            para: "catalog".into(),
27697            wit: "wasi:http/proxy".into(),
27698            endpoint: Some("/lookup".into()),
27699            subject: None,
27700            slot: None,
27701        };
27702        assert_eq!(
27703            inter_edge.is_self_loop(),
27704            inter_edge.source() == inter_edge.destination(),
27705            "WitContract::is_self_loop must compose exactly \
27706             `source() == destination()` on the complement arm too",
27707        );
27708    }
27709
27710    #[test]
27711    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
27712        // The composition pin: [`WitContract::target`]'s invalid-wit
27713        // value-shape gate must feed the reason string through the
27714        // lifted [`WitContract::world_ref`] scalar accessor — the same
27715        // typed dispatch on the substrate primitive every peer
27716        // per-`:contratos` payload-carrier extraction in the same
27717        // method body already routes through
27718        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
27719        // [`WitContract::subject`] on the pub-sub-arm target extraction,
27720        // [`WitContract::slot`] on the store-arm target extraction) and
27721        // every peer composite-projection accessor
27722        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
27723        // [`WitContract::identity`]) already composes from. Any future
27724        // refactor that silently re-authored the gate to bypass the
27725        // lifted accessor (an accidental `&self.wit` regression back to
27726        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
27727        // re-canonicalization on `world_ref()` that didn't reach this
27728        // gate, a per-CR lowercasing canonicalization pass the M4
27729        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
27730        // per-tenant that lands on `world_ref()` without reaching this
27731        // gate) would silently split the invalid-wit diagnostic reason
27732        // from the substrate-primitive projection every downstream
27733        // consumer routes through. Same "typed dispatch composes with
27734        // typed dispatch, not with raw field access" discipline the
27735        // sibling
27736        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
27737        // pin already carries on the endpoint-equality predicate axis,
27738        // extended onto the invalid-wit value-shape gate axis inside
27739        // the same [`WitContract::target`] body. Closes the last
27740        // unlifted raw-field-access site inside `impl WitContract`.
27741        //
27742        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
27743        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
27744        // to a capability-only edge; the value-shape gate rejects it
27745        // through [`crate::render::is_wit_world_ref`] on the substrate
27746        // primitive's ASCII-lowercase-only accept-set, with a
27747        // parser-shaped reason string the test asserts round-trips
27748        // byte-for-byte between the direct-dispatch call (through the
27749        // predicate on the accessor's projection) and the
27750        // [`WitContract::target`] gate's produced reason field.
27751        let c = WitContract {
27752            de: "cart".into(),
27753            para: "catalog".into(),
27754            wit: "WASI:HTTP/proxy".into(),
27755            endpoint: Some("/lookup".into()),
27756            subject: None,
27757            slot: None,
27758        };
27759        let err = c.target().unwrap_err();
27760        let AplicacaoError::ContratoWitInvalid {
27761            ref de,
27762            ref para,
27763            ref wit,
27764            ref reason,
27765        } = err
27766        else {
27767            panic!("expected ContratoWitInvalid, got {err:?}");
27768        };
27769        assert_eq!(de, "cart");
27770        assert_eq!(para, "catalog");
27771        assert_eq!(wit, "WASI:HTTP/proxy");
27772        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
27773        assert_eq!(
27774            *reason, expected_reason,
27775            "WitContract::target's invalid-wit value-shape gate reason \
27776             must compose exactly is_wit_world_ref(self.world_ref()) — \
27777             a bypass here (e.g. a raw `&self.wit` field-access \
27778             regression, or a divergent predicate on a different \
27779             projection) would silently decouple the invalid-wit \
27780             diagnostic's reason field from the substrate-primitive \
27781             scalar accessor every peer per-`:contratos` extraction in \
27782             the same method body already routes through",
27783        );
27784    }
27785
27786    #[test]
27787    fn wit_contract_is_self_loop_predicate_is_const_fn() {
27788        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
27789        // caller-callee identity-space predicate's `const`-eval-surface
27790        // posture. The wrapper below dispatches through
27791        // [`WitContract::is_self_loop`] and is well-formed only when the
27792        // callee is itself `pub const fn` — any future accidental
27793        // downgrade to non-`const` fails the wrapper at caixa-core build
27794        // time with E0015 (`cannot call non-const method`), strictly
27795        // stronger than a runtime `assert!` and strictly stronger than a
27796        // module-scope `const _: () = assert!(…)` pin (the type's
27797        // `String` / `Option<String>` carriers rule out `const`-context
27798        // value construction; the `const fn` wrapper is the load-bearing
27799        // shape that side-steps the destructor-in-const restriction on
27800        // the value axis while still pinning the `const`-fn posture on
27801        // the callee — mirror of the sibling
27802        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
27803        // (279823b) and
27804        // [`wit_contract_identity_projection_accessor_is_const_fn`]
27805        // (1ab648c) pins' discipline verbatim on the peer scalar-
27806        // accessor and composite-projection surfaces). Closes the last
27807        // unlifted per-`:contratos` shape/identity predicate on the
27808        // const-eval surface — the peer WIT-shape-partition family
27809        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
27810        // [`WitContract::is_store`] / [`WitContract::is_capability`]
27811        // already carried the `pub const fn` posture on the peer
27812        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
27813        // this pin extends the same posture onto the caller-callee
27814        // identity-space partition. Sweeps every WIT-shape arm on both
27815        // the equal-endpoints (self-edge) and distinct-endpoints
27816        // (inter-edge) arms of the identity-space partition, plus one
27817        // same-length distinct-byte pair to pin the mid-loop `!=` arm
27818        // past the leading length-mismatch shortcut.
27819        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
27820            c.is_self_loop()
27821        }
27822        let mk = |de: &str, para: &str, wit: &str| WitContract {
27823            de: de.into(),
27824            para: para.into(),
27825            wit: wit.into(),
27826            endpoint: None,
27827            subject: None,
27828            slot: None,
27829        };
27830        for (nome, wit) in [
27831            ("cart", "wasi:http/proxy"),
27832            ("checkout", "nats:pub-sub"),
27833            ("kv", "wasi:keyvalue/store"),
27834            ("audit", "wasi:logging"),
27835        ] {
27836            let self_edge = mk(nome, nome, wit);
27837            assert!(
27838                is_self_loop_via_const_fn(&self_edge),
27839                "self-edge {nome:?} under {wit:?}"
27840            );
27841            assert_eq!(
27842                is_self_loop_via_const_fn(&self_edge),
27843                self_edge.is_self_loop()
27844            );
27845        }
27846        for (de, para, wit) in [
27847            ("cart", "catalog", "wasi:http/proxy"),
27848            ("checkout", "orders", "nats:pub-sub"),
27849            ("cart", "kv", "wasi:keyvalue/store"),
27850            ("audit", "sink", "wasi:logging"),
27851        ] {
27852            let inter_edge = mk(de, para, wit);
27853            assert!(
27854                !is_self_loop_via_const_fn(&inter_edge),
27855                "inter-edge {de:?}→{para:?} under {wit:?}",
27856            );
27857            assert_eq!(
27858                is_self_loop_via_const_fn(&inter_edge),
27859                inter_edge.is_self_loop()
27860            );
27861        }
27862        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
27863        // past the leading `a.len() != b.len()` shortcut so the const-fn
27864        // wrapper exercises every arm of the byte-slice equality loop.
27865        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
27866        assert!(
27867            !is_self_loop_via_const_fn(&same_len_pair),
27868            "same-length distinct-byte"
27869        );
27870        assert_eq!(
27871            is_self_loop_via_const_fn(&same_len_pair),
27872            same_len_pair.is_self_loop()
27873        );
27874    }
27875
27876    #[test]
27877    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
27878        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
27879        // pin: [`WitContract::endpoint`] must return the `:contratos
27880        // :endpoint` field byte-for-byte, borrowed from the typed slot's
27881        // own `Option<String>` storage. Peer of the sibling
27882        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
27883        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
27884        // mesh-slot `Option<String>` optional-scalar axes — same "the
27885        // substrate-primitive accessor must byte-equal the raw field
27886        // access verbatim across every author-declared value" discipline
27887        // extended to the per-`:contratos` HTTP-payload-carrier arm.
27888        // Pins against a future silent detour that re-canonicalized the
27889        // endpoint (an accidental percent-encoding pass that didn't
27890        // reach the peer field-access site at the dedup key, a per-CR
27891        // fully-qualified prefix rewrite the operator authors on one
27892        // consumer without the other, or an M4 typed-path-template
27893        // `Display` re-canonicalization that silently drifted the
27894        // printer output from the source `caixa.lisp`). Four values
27895        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
27896        // gate upstream admits (short root-path, dashed, param-shaped,
27897        // deep-hierarchy).
27898        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
27899            let c = WitContract {
27900                de: "cart".into(),
27901                para: "catalog".into(),
27902                wit: "wasi:http/proxy".into(),
27903                endpoint: Some(endpoint.into()),
27904                subject: None,
27905                slot: None,
27906            };
27907            assert_eq!(
27908                c.endpoint(),
27909                Some(endpoint),
27910                "WitContract::endpoint must return :contratos :endpoint \
27911                 verbatim (got {:?}, expected Some({endpoint:?}))",
27912                c.endpoint(),
27913            );
27914            assert_eq!(
27915                c.endpoint(),
27916                c.endpoint.as_deref(),
27917                "WitContract::endpoint must byte-equal the .endpoint \
27918                 field's `.as_deref()` projection",
27919            );
27920        }
27921    }
27922
27923    #[test]
27924    fn wit_contract_endpoint_none_when_field_is_none() {
27925        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
27926        // payload-carrier accessor pin: when the typed slot is absent —
27927        // the canonical shape under a non-HTTP `:wit` world per the
27928        // [`WitContract::target`]-enforced shape ↔ target partition
27929        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
27930        // carries `:slot`, [`WitTarget::Capability`] carries none) —
27931        // [`WitContract::endpoint`] must return `None`. Pins against a
27932        // future silent detour that projected the absent slot to a
27933        // `Some("")` empty-string default (the canonical `Option<String>`
27934        // → `String` collapse footgun the sibling M2
27935        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
27936        // emptiness predicates already guard on the peer M2 typed-slot
27937        // surfaces), a `Some("None")` stringified-None round-trip, or a
27938        // `Some` arm whose contents were derived from a sibling slot (an
27939        // accidental fallback to the `:subject` / `:slot` payload that
27940        // read the pub-sub / store payload into the endpoint axis).
27941        // Three contracts sweep the accept-set every non-HTTP `:wit`
27942        // world lands on — pub-sub NATS, key/value, and payload-less
27943        // capability.
27944        for (wit, subject, slot) in [
27945            ("nats:pub-sub", Some("orders.paid"), None),
27946            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
27947            ("wasi:cli/environment", None, None),
27948        ] {
27949            let c = WitContract {
27950                de: "cart".into(),
27951                para: "downstream".into(),
27952                wit: wit.into(),
27953                endpoint: None,
27954                subject: subject.map(str::to_string),
27955                slot: slot.map(str::to_string),
27956            };
27957            assert!(
27958                c.endpoint().is_none(),
27959                "WitContract::endpoint must return None when the typed \
27960                 slot is absent under :wit {wit:?} (got {:?})",
27961                c.endpoint(),
27962            );
27963            assert_eq!(
27964                c.endpoint(),
27965                c.endpoint.as_deref(),
27966                "WitContract::endpoint must byte-equal the .endpoint \
27967                 field's `.as_deref()` projection in the absent arm",
27968            );
27969        }
27970    }
27971
27972    #[test]
27973    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
27974        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
27975        // an `Option<&str>` whose `Some` arm borrows from the typed
27976        // slot's own [`String`] storage — same-address invariant with
27977        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
27978        // detour that allocated a fresh `String`
27979        // (`self.endpoint.clone().map(...)` in the body would type-check
27980        // but silently drop the borrow, and every downstream consumer
27981        // that assumed the returned slice outlives `&self` would break
27982        // on a stale-reference use-after-free — the [`WitContract::target`]
27983        // Http-arm payload extraction rebinds the returned `Option<&str>`
27984        // through `.ok_or_else(...)` and threads the `&str` payload into
27985        // [`WitTarget::Http { endpoint: &'a str }`], the
27986        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
27987        // [`ContratoIdentity`] dedup key threads the returned
27988        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
27989        // from the WitContract's own storage and each would silently
27990        // misbehave if this accessor produced a detached copy). Peer of
27991        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
27992        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
27993        // shaped optional-scalar axes — first extension of the
27994        // `Option<&str>` borrow-not-copy discipline onto the
27995        // per-`:contratos` HTTP-shaped payload-carrier axis.
27996        let c = WitContract {
27997            de: "cart".into(),
27998            para: "catalog".into(),
27999            wit: "wasi:http/proxy".into(),
28000            endpoint: Some("/lookup".into()),
28001            subject: None,
28002            slot: None,
28003        };
28004        let ep = c.endpoint().expect("Some arm");
28005        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
28006        assert_eq!(
28007            ep.as_ptr(),
28008            storage_slice.as_ptr(),
28009            "WitContract::endpoint must borrow from the .endpoint \
28010             String's backing storage — a fresh allocation here means \
28011             the accessor no longer names the substrate-primitive typed \
28012             dispatch and every downstream consumer would silently \
28013             carry a detached copy",
28014        );
28015        assert_eq!(
28016            ep.len(),
28017            storage_slice.len(),
28018            "WitContract::endpoint and .endpoint.as_deref() must byte-\
28019             equal in length as well as in address",
28020        );
28021    }
28022
28023    #[test]
28024    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
28025        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
28026        // pin: [`WitContract::subject`] must return the `:contratos
28027        // :subject` field byte-for-byte, borrowed from the typed slot's
28028        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
28029        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
28030        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
28031        // optional-scalar axis — same "the substrate-primitive accessor
28032        // must byte-equal the raw field access verbatim across every
28033        // author-declared value" discipline extended to the pub-sub arm.
28034        // Pins against a future silent detour that re-canonicalized the
28035        // subject (an accidental `.to_lowercase()` normalization that
28036        // didn't reach the peer field-access site at the dedup key, a
28037        // per-CR fully-qualified prefix rewrite the operator authors on
28038        // one consumer without the other, or an M4 typed-subject-template
28039        // `Display` re-canonicalization that silently drifted the printer
28040        // output from the source `caixa.lisp`). Four values sweep the
28041        // NATS accept-set every pub-sub author-declared subject lands on
28042        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
28043        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
28044            let c = WitContract {
28045                de: "cart".into(),
28046                para: "notifier".into(),
28047                wit: "nats:pub-sub".into(),
28048                endpoint: None,
28049                subject: Some(subject.into()),
28050                slot: None,
28051            };
28052            assert_eq!(
28053                c.subject(),
28054                Some(subject),
28055                "WitContract::subject must return :contratos :subject \
28056                 verbatim (got {:?}, expected Some({subject:?}))",
28057                c.subject(),
28058            );
28059            assert_eq!(
28060                c.subject(),
28061                c.subject.as_deref(),
28062                "WitContract::subject must byte-equal the .subject \
28063                 field's `.as_deref()` projection",
28064            );
28065        }
28066    }
28067
28068    #[test]
28069    fn wit_contract_subject_none_when_field_is_none() {
28070        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
28071        // shaped payload-carrier accessor pin: when the typed slot is
28072        // absent — the canonical shape under a non-pub-sub `:wit` world
28073        // per the [`WitContract::target`]-enforced shape ↔ target
28074        // partition ([`WitTarget::Http`] carries `:endpoint`,
28075        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
28076        // carries none) — [`WitContract::subject`] must return `None`.
28077        // Pins against a future silent detour that projected the absent
28078        // slot to a `Some("")` empty-string default (the canonical
28079        // `Option<String>` → `String` collapse footgun the sibling M2
28080        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
28081        // emptiness predicates already guard on the peer M2 typed-slot
28082        // surfaces), a `Some("None")` stringified-None round-trip, or a
28083        // `Some` arm whose contents were derived from a sibling slot (an
28084        // accidental fallback to the `:endpoint` / `:slot` payload that
28085        // read the HTTP / store payload into the subject axis). Three
28086        // contracts sweep the accept-set every non-pub-sub `:wit` world
28087        // lands on — HTTP proxy, key/value store, and payload-less
28088        // capability.
28089        for (wit, endpoint, slot) in [
28090            ("wasi:http/proxy", Some("/lookup"), None),
28091            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
28092            ("wasi:cli/environment", None, None),
28093        ] {
28094            let c = WitContract {
28095                de: "cart".into(),
28096                para: "downstream".into(),
28097                wit: wit.into(),
28098                endpoint: endpoint.map(str::to_string),
28099                subject: None,
28100                slot: slot.map(str::to_string),
28101            };
28102            assert!(
28103                c.subject().is_none(),
28104                "WitContract::subject must return None when the typed \
28105                 slot is absent under :wit {wit:?} (got {:?})",
28106                c.subject(),
28107            );
28108            assert_eq!(
28109                c.subject(),
28110                c.subject.as_deref(),
28111                "WitContract::subject must byte-equal the .subject \
28112                 field's `.as_deref()` projection in the absent arm",
28113            );
28114        }
28115    }
28116
28117    #[test]
28118    fn wit_contract_subject_borrows_from_subject_storage() {
28119        // The borrow-not-copy pin: [`WitContract::subject`] must return
28120        // an `Option<&str>` whose `Some` arm borrows from the typed
28121        // slot's own [`String`] storage — same-address invariant with
28122        // `c.subject.as_deref().unwrap()`. Pins against a future silent
28123        // detour that allocated a fresh `String`
28124        // (`self.subject.clone().map(...)` in the body would type-check
28125        // but silently drop the borrow, and every downstream consumer
28126        // that assumed the returned slice outlives `&self` would break
28127        // on a stale-reference use-after-free — the [`WitContract::target`]
28128        // PubSub-arm payload extraction rebinds the returned
28129        // `Option<&str>` through `.ok_or_else(...)` and threads the
28130        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
28131        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
28132        // [`ContratoIdentity`] dedup key threads the returned
28133        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
28134        // from the WitContract's own storage and each would silently
28135        // misbehave if this accessor produced a detached copy). Peer of
28136        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
28137        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
28138        // shaped optional-scalar axis — second extension of the
28139        // `Option<&str>` borrow-not-copy discipline onto the
28140        // per-`:contratos` payload-carrier family, this time on the
28141        // pub-sub arm.
28142        let c = WitContract {
28143            de: "cart".into(),
28144            para: "notifier".into(),
28145            wit: "nats:pub-sub".into(),
28146            endpoint: None,
28147            subject: Some("orders.paid".into()),
28148            slot: None,
28149        };
28150        let sub = c.subject().expect("Some arm");
28151        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
28152        assert_eq!(
28153            sub.as_ptr(),
28154            storage_slice.as_ptr(),
28155            "WitContract::subject must borrow from the .subject \
28156             String's backing storage — a fresh allocation here means \
28157             the accessor no longer names the substrate-primitive typed \
28158             dispatch and every downstream consumer would silently \
28159             carry a detached copy",
28160        );
28161        assert_eq!(
28162            sub.len(),
28163            storage_slice.len(),
28164            "WitContract::subject and .subject.as_deref() must byte-\
28165             equal in length as well as in address",
28166        );
28167    }
28168
28169    #[test]
28170    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
28171        // The canonical per-`:contratos` key/value-store-shaped
28172        // `:slot`-scalar pin: [`WitContract::slot`] must return the
28173        // `:contratos :slot` field byte-for-byte, borrowed from the
28174        // typed slot's own `Option<String>` storage. Peer of the
28175        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
28176        // [`WitContract::subject`] (90de675) accessor pins on the M3
28177        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
28178        // optional-scalar axis — same "the substrate-primitive
28179        // accessor must byte-equal the raw field access verbatim
28180        // across every author-declared value" discipline extended to
28181        // the store arm. Pins against a future silent detour that
28182        // re-canonicalized the slot template (an accidental
28183        // `.to_lowercase()` bucket-prefix normalization that didn't
28184        // reach the peer field-access site at the dedup key, a per-CR
28185        // fully-qualified prefix rewrite the operator authors on one
28186        // consumer without the other, or an M4 typed-key-template
28187        // `Display` re-canonicalization that silently drifted the
28188        // printer output from the source `caixa.lisp`). Four values
28189        // sweep the wasi:keyvalue accept-set every store-shaped
28190        // author-declared slot lands on (flat bucket, single-param
28191        // template, multi-param template, nested-hierarchy template).
28192        for slot in [
28193            "sessions",
28194            "carts/{cart_id}",
28195            "orders/{tenant}/{order_id}",
28196            "cache/tenant-a/orders/{id}",
28197        ] {
28198            let c = WitContract {
28199                de: "cart".into(),
28200                para: "kv".into(),
28201                wit: "wasi:keyvalue/store".into(),
28202                endpoint: None,
28203                subject: None,
28204                slot: Some(slot.into()),
28205            };
28206            assert_eq!(
28207                c.slot(),
28208                Some(slot),
28209                "WitContract::slot must return :contratos :slot \
28210                 verbatim (got {:?}, expected Some({slot:?}))",
28211                c.slot(),
28212            );
28213            assert_eq!(
28214                c.slot(),
28215                c.slot.as_deref(),
28216                "WitContract::slot must byte-equal the .slot field's \
28217                 `.as_deref()` projection",
28218            );
28219        }
28220    }
28221
28222    #[test]
28223    fn wit_contract_slot_none_when_field_is_none() {
28224        // The absent-`:slot` arm of the per-`:contratos` store-shaped
28225        // payload-carrier accessor pin: when the typed slot is absent —
28226        // the canonical shape under a non-store `:wit` world per the
28227        // [`WitContract::target`]-enforced shape ↔ target partition
28228        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
28229        // carries `:subject`, [`WitTarget::Capability`] carries none) —
28230        // [`WitContract::slot`] must return `None`. Pins against a
28231        // future silent detour that projected the absent slot to a
28232        // `Some("")` empty-string default (the canonical
28233        // `Option<String>` → `String` collapse footgun the sibling M2
28234        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
28235        // emptiness predicates already guard on the peer M2 typed-slot
28236        // surfaces), a `Some("None")` stringified-None round-trip, or
28237        // a `Some` arm whose contents were derived from a sibling
28238        // slot (an accidental fallback to the `:endpoint` / `:subject`
28239        // payload that read the HTTP / pub-sub payload into the store
28240        // axis). Three contracts sweep the accept-set every non-store
28241        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
28242        // payload-less capability.
28243        for (wit, endpoint, subject) in [
28244            ("wasi:http/proxy", Some("/lookup"), None),
28245            ("nats:pub-sub", None, Some("orders.paid")),
28246            ("wasi:cli/environment", None, None),
28247        ] {
28248            let c = WitContract {
28249                de: "cart".into(),
28250                para: "downstream".into(),
28251                wit: wit.into(),
28252                endpoint: endpoint.map(str::to_string),
28253                subject: subject.map(str::to_string),
28254                slot: None,
28255            };
28256            assert!(
28257                c.slot().is_none(),
28258                "WitContract::slot must return None when the typed \
28259                 slot is absent under :wit {wit:?} (got {:?})",
28260                c.slot(),
28261            );
28262            assert_eq!(
28263                c.slot(),
28264                c.slot.as_deref(),
28265                "WitContract::slot must byte-equal the .slot field's \
28266                 `.as_deref()` projection in the absent arm",
28267            );
28268        }
28269    }
28270
28271    #[test]
28272    fn wit_contract_slot_borrows_from_slot_storage() {
28273        // The borrow-not-copy pin: [`WitContract::slot`] must return
28274        // an `Option<&str>` whose `Some` arm borrows from the typed
28275        // slot's own [`String`] storage — same-address invariant with
28276        // `c.slot.as_deref().unwrap()`. Pins against a future silent
28277        // detour that allocated a fresh `String`
28278        // (`self.slot.clone().map(...)` in the body would type-check
28279        // but silently drop the borrow, and every downstream consumer
28280        // that assumed the returned slice outlives `&self` would
28281        // break on a stale-reference use-after-free — the
28282        // [`WitContract::target`] Store-arm payload extraction rebinds
28283        // the returned `Option<&str>` through `.ok_or_else(...)` and
28284        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
28285        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
28286        // [`ContratoIdentity`] dedup key threads the returned
28287        // `Option<&str>` into the six-tuple's store arm — each borrow
28288        // from the WitContract's own storage and each would silently
28289        // misbehave if this accessor produced a detached copy). Peer
28290        // of the sibling per-`:contratos` [`WitContract::endpoint`]
28291        // (7020470) / [`WitContract::subject`] (90de675)
28292        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
28293        // shaped optional-scalar axis — third and final extension of
28294        // the `Option<&str>` borrow-not-copy discipline onto the
28295        // per-`:contratos` payload-carrier family, this time on the
28296        // store arm.
28297        let c = WitContract {
28298            de: "cart".into(),
28299            para: "kv".into(),
28300            wit: "wasi:keyvalue/store".into(),
28301            endpoint: None,
28302            subject: None,
28303            slot: Some("carts/{cart_id}".into()),
28304        };
28305        let slot = c.slot().expect("Some arm");
28306        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
28307        assert_eq!(
28308            slot.as_ptr(),
28309            storage_slice.as_ptr(),
28310            "WitContract::slot must borrow from the .slot String's \
28311             backing storage — a fresh allocation here means the \
28312             accessor no longer names the substrate-primitive typed \
28313             dispatch and every downstream consumer would silently \
28314             carry a detached copy",
28315        );
28316        assert_eq!(
28317            slot.len(),
28318            storage_slice.len(),
28319            "WitContract::slot and .slot.as_deref() must byte-equal \
28320             in length as well as in address",
28321        );
28322    }
28323
28324    #[test]
28325    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
28326        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
28327        // [`Membro::nome`] must return the `:membros :caixa` field
28328        // byte-for-byte, borrowed from the typed slot's own [`String`]
28329        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
28330        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
28331        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
28332        // slot-atom scalar-value axes — same "the substrate-primitive
28333        // accessor must byte-equal the raw field access verbatim across
28334        // every author-declared value" discipline extended to the
28335        // per-`:membros` member-identity arm. Pins against a future
28336        // silent detour that re-normalized the member identity (an
28337        // accidental `.to_lowercase()` — every `:membros :caixa` is
28338        // validated as a DNS-1123 label upstream via
28339        // [`validate_membro_caixa`], so any re-normalization is
28340        // redundant + a drift surface between the validator and the
28341        // accessor), a namespace-prefix rewrite (an accidental
28342        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
28343        // rewrite that didn't land on the peer axes), or a per-cluster
28344        // alias stamp the operator authors on one consumer without the
28345        // other. Four values sweep the accept-set the DNS-1123 gate
28346        // upstream admits (short single-word / dashed / v-suffixed
28347        // member names).
28348        for name in ["cart", "checkout", "catalog", "orders-v2"] {
28349            let m = Membro {
28350                caixa: name.into(),
28351                versao: "^0.1".into(),
28352            };
28353            assert_eq!(
28354                m.nome(),
28355                name,
28356                "Membro::nome must return :membros :caixa verbatim \
28357                 (got {:?}, expected {name:?})",
28358                m.nome(),
28359            );
28360            assert_eq!(
28361                m.nome(),
28362                m.caixa.as_str(),
28363                "Membro::nome must byte-equal the .caixa field access",
28364            );
28365        }
28366    }
28367
28368    #[test]
28369    fn membro_nome_borrows_from_caixa_storage() {
28370        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
28371        // slice that borrows from the typed slot's own [`String`]
28372        // storage — same-address invariant with `m.caixa.as_str()`. Pins
28373        // against a future silent detour that allocated a fresh `String`
28374        // (`self.caixa.clone()` in the body would type-check but
28375        // silently drop the borrow, and every downstream consumer that
28376        // assumed the returned slice outlives `&self` would break on a
28377        // stale-reference use-after-free — the `HashSet<&str>` collector
28378        // at [`AplicacaoSpec::validate`]'s `names` seed, the
28379        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
28380        // [`AplicacaoSpec::detect_sync_cycles`], the
28381        // [`crate::render::insert_first_seen`] dedup key at
28382        // [`AplicacaoSpec::validate_membros`] — each borrow from the
28383        // Membro's own storage and each would silently misbehave if
28384        // this accessor produced a detached copy). Peer of the sibling
28385        // per-`:contratos` [`WitContract::source`] /
28386        // [`WitContract::destination`] and per-`:entrada`
28387        // [`Entrada::destination`] borrow-invariant pins on the mesh-
28388        // slot-atom scalar-value axes.
28389        let m = Membro {
28390            caixa: "checkout".into(),
28391            versao: "^0.1".into(),
28392        };
28393        let name = m.nome();
28394        let caixa_slice = m.caixa.as_str();
28395        assert_eq!(
28396            name.as_ptr(),
28397            caixa_slice.as_ptr(),
28398            "Membro::nome must borrow from the .caixa String's backing \
28399             storage — a fresh allocation here means the accessor no \
28400             longer names the substrate-primitive typed dispatch and \
28401             every downstream consumer would silently carry a detached \
28402             copy",
28403        );
28404        assert_eq!(
28405            name.len(),
28406            caixa_slice.len(),
28407            "Membro::nome and .caixa.as_str() must byte-equal in length \
28408             as well as in address",
28409        );
28410    }
28411
28412    #[test]
28413    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
28414        // The canonical per-`:membros` member-`:versao`-scalar pin:
28415        // [`Membro::versao_requirement`] must return the
28416        // `:membros :versao` field byte-for-byte, borrowed from the typed
28417        // slot's own [`String`] storage. Sibling of the peer
28418        // `membro_nome_returns_caixa_byte_equal_across_permutations`
28419        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
28420        // — same "the substrate-primitive accessor must byte-equal the
28421        // raw field access verbatim across every author-declared value"
28422        // discipline extended to the per-`:membros` member-`:versao`
28423        // requirement-string arm. Pins against a future silent detour
28424        // that re-canonicalized the requirement (an accidental
28425        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
28426        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
28427        // drifted the printer output away from the source `caixa.lisp`,
28428        // an accidental whitespace trim on `"^ 0.1"` that no consumer
28429        // ever produced from the field-access side, an accidental
28430        // per-cluster lacre-projected concrete-version rewrite that
28431        // didn't land on the peer field-access sites). Five values sweep
28432        // the accept-set the shared
28433        // [`crate::render::require_valid_versao_requirement`] gate
28434        // admits (caret / tilde / exact / wildcard / bare-major).
28435        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
28436            let m = Membro {
28437                caixa: "cart".into(),
28438                versao: req.into(),
28439            };
28440            assert_eq!(
28441                m.versao_requirement(),
28442                req,
28443                "Membro::versao_requirement must return :membros :versao \
28444                 verbatim (got {:?}, expected {req:?})",
28445                m.versao_requirement(),
28446            );
28447            assert_eq!(
28448                m.versao_requirement(),
28449                m.versao.as_str(),
28450                "Membro::versao_requirement must byte-equal the .versao \
28451                 field access",
28452            );
28453        }
28454    }
28455
28456    #[test]
28457    fn membro_versao_requirement_borrows_from_versao_storage() {
28458        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
28459        // return a `&str` slice that borrows from the typed slot's own
28460        // [`String`] storage — same-address invariant with
28461        // `m.versao.as_str()`. Pins against a future silent detour that
28462        // allocated a fresh `String` (`self.versao.clone()` in the body
28463        // would type-check but silently drop the borrow, and every
28464        // downstream consumer that assumed the returned slice outlives
28465        // `&self` would break on a stale-reference use-after-free). Peer
28466        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
28467        // per-`:contratos` [`WitContract::source`] /
28468        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
28469        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
28470        // the mesh-slot-atom scalar-value axes.
28471        let m = Membro {
28472            caixa: "checkout".into(),
28473            versao: "^0.1".into(),
28474        };
28475        let req = m.versao_requirement();
28476        let versao_slice = m.versao.as_str();
28477        assert_eq!(
28478            req.as_ptr(),
28479            versao_slice.as_ptr(),
28480            "Membro::versao_requirement must borrow from the .versao \
28481             String's backing storage — a fresh allocation here means \
28482             the accessor no longer names the substrate-primitive typed \
28483             dispatch and every downstream consumer would silently carry \
28484             a detached copy",
28485        );
28486        assert_eq!(
28487            req.len(),
28488            versao_slice.len(),
28489            "Membro::versao_requirement and .versao.as_str() must byte-\
28490             equal in length as well as in address",
28491        );
28492    }
28493
28494    #[test]
28495    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
28496        // Sibling-pair invariant pin composing both per-`:membros`
28497        // substrate-primitive typed dispatches — [`Membro::nome`]
28498        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
28499        // `(nome(), versao_requirement())` call shape every renderer
28500        // that fans on per-member identity + version pin keys off. The
28501        // invariant, evaluated per-member:
28502        //
28503        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
28504        //
28505        // Closes the last unlifted per-`:membros` scalar axis — every
28506        // downstream consumer that reads the pair now routes through
28507        // exactly two typed dispatches on the substrate primitive, not
28508        // one typed + one open-coded field access. A future refactor
28509        // that silently split either accessor's projection (an
28510        // accidental `nome()` namespace-prefix rewrite that didn't
28511        // reach the peer, an accidental `versao_requirement()` lacre-
28512        // projected concrete-version rewrite that didn't land on the
28513        // `nome()` peer) surfaces at caixa-core build time. Peer of the
28514        // sibling per-`:entrada` `(hostname(), destination())` and
28515        // per-`:contratos` `(source(), destination())` pair invariants
28516        // on the mesh-slot-atom scalar-value axes.
28517        for (caixa, versao) in [
28518            ("cart", "^0.1"),
28519            ("checkout", "~0.1.2"),
28520            ("catalog", "0.1.0"),
28521            ("orders-v2", "*"),
28522        ] {
28523            let m = Membro {
28524                caixa: caixa.into(),
28525                versao: versao.into(),
28526            };
28527            assert_eq!(
28528                (m.nome(), m.versao_requirement()),
28529                (m.caixa.as_str(), m.versao.as_str()),
28530                "(Membro::nome, Membro::versao_requirement) must project \
28531                 (.caixa, .versao) verbatim across every author-declared \
28532                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
28533                m.nome(),
28534                m.versao_requirement(),
28535            );
28536        }
28537    }
28538
28539    #[test]
28540    fn validate_membros_empty_gate_routes_through_nome_accessor() {
28541        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
28542        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
28543        // not the raw `.caixa` field access. Structurally: setting
28544        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
28545        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
28546        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
28547        // (i.e. the empty string) — so the emptiness predicate the
28548        // refusal arm reaches under is the accessor-projected value,
28549        // not a peer field that would silently drift under a future
28550        // accessor-side rewrite.
28551        //
28552        // Pins against a future silent detour that (a) re-derived the
28553        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
28554        // instead of `self.nome().is_empty()`, silently disagreeing with
28555        // every peer consumer (the `validate_membro_caixa(m.nome())`
28556        // per-slot helper — which now owns the emptiness arm outright —
28557        // the dedup-key `insert_first_seen(&mut seen, m.nome(), …)`
28558        // below, and the emit-side per-`programs[]` entry-`name:` at
28559        // caixa-mesh/src/lib.rs:133), (b) accessor-side introduced a
28560        // per-tenant alias arm the caller was unaware of, silently
28561        // rewriting an author-declared `:caixa "checkout"` to `""` —
28562        // the raw-field-access gate would fail-open while the
28563        // accessor-routed peer consumers would fail-closed, splitting
28564        // the diagnostic from the actual failure surface.
28565        //
28566        // Peer of the sibling
28567        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
28568        // (c0110f1) composition pin — same "the shape-gate predicate
28569        // must route through the substrate-primitive typed dispatch"
28570        // discipline extended onto the per-`:membros` empty-`:caixa`
28571        // refusal-arm axis. Closes the last unlifted `.caixa` production-
28572        // code read site on `Membro` — after this converge every
28573        // caixa-core `.caixa` field access outside the accessor's own
28574        // body is either a test-side field-setter (in-module tests
28575        // constructing invalid-shape inputs) or a doc-comment reference.
28576        let mut s = three_member_spec();
28577        s.membros[1].caixa = String::new();
28578        assert!(
28579            s.membros[1].nome().is_empty(),
28580            "Membro::nome must byte-equal the .caixa field access — an \
28581             accessor-side detour that no longer projects the raw field \
28582             would silently split this drift-detection test from the \
28583             validate() refusal arm",
28584        );
28585        assert_eq!(
28586            s.membros[1].nome(),
28587            s.membros[1].caixa.as_str(),
28588            "Membro::nome and .caixa.as_str() must byte-equal on an \
28589             empty-`:caixa` entry — the emptiness gate keys off the \
28590             accessor by construction",
28591        );
28592        assert_eq!(
28593            s.validate().unwrap_err(),
28594            AplicacaoError::MembroCaixaEmpty,
28595            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
28596             on an entry whose accessor-projected `nome()` is empty",
28597        );
28598    }
28599
28600    #[test]
28601    fn validate_membros_empty_arm_is_owned_by_validate_membro_caixa_alone() {
28602        // Convergence pin, paired with the deletion of the redundant
28603        // outer `if m.nome().is_empty() { return Err(MembroCaixaEmpty); }`
28604        // guard formerly inline in [`AplicacaoSpec::validate_membros`]:
28605        // after the collapse, the `MembroCaixaEmpty` refusal on every
28606        // empty-`:caixa` per-member input is owned solely by the shared
28607        // [`validate_membro_caixa`] helper — the same per-slot substrate
28608        // primitive routing empty + shape arms uniformly onto
28609        // [`crate::render::require_valid_dns_1123_label`] that every
28610        // peer M3 mesh-slot per-slot gate ([`validate_placement_cluster`]
28611        // on `:placement :clusters`, [`validate_entrada_para`] on
28612        // `:entrada :para`, [`validate_contrato_caixa`] on `:contratos
28613        // :de`/`:para`) already funnels its own empty arm through.
28614        //
28615        // Two arms pin the collapse:
28616        //
28617        //   (1) The per-slot helper called with the empty string returns
28618        //       byte-equal to the previous inline arm's diagnostic — so
28619        //       a future rebrand of [`validate_membro_caixa`] that
28620        //       (accidentally) stopped returning [`MembroCaixaEmpty`] on
28621        //       empty input (an inadvertent switch to
28622        //       [`AplicacaoError::MembroCaixaInvalid`] via the parse-side
28623        //       `on_invalid` arm, an accidental re-routing to a shared
28624        //       `MembroError::Empty` under a future error-hierarchy
28625        //       flattening) would silently split the drift from the
28626        //       [`validate_membros`] caller and surface the wrong
28627        //       diagnostic on the author-facing empty-`:caixa` footgun.
28628        //
28629        //   (2) The whole-spec equivalence: an empty-`:caixa` entry
28630        //       anywhere in the `:membros` fan-out still trips
28631        //       [`MembroCaixaEmpty`] end-to-end via [`validate`], with
28632        //       no outer inline guard needed. Same shape as the
28633        //       whole-spec arm on [`validate_placement_cluster`] /
28634        //       [`validate_entrada_para`] / [`validate_contrato_caixa`]:
28635        //       one substrate primitive per axis, folding empty + shape.
28636        //
28637        // Same PRIME DIRECTIVE convergence the peer per-slot gate lifts
28638        // (906a5c6 validate_contratos, 20cd523 validate_entrada, f03a154
28639        // MeshPolicy::validate) already extend across the M3 mesh-slot
28640        // family — closes the last per-slot gate on the family carrying
28641        // an inline empty guard duplicating its own helper.
28642        assert_eq!(
28643            validate_membro_caixa(""),
28644            Err(AplicacaoError::MembroCaixaEmpty),
28645            "validate_membro_caixa must own the empty arm outright — a \
28646             regression here would silently split MembroCaixaEmpty from \
28647             validate_membros' end-to-end refusal shape after the outer \
28648             inline `if m.nome().is_empty()` guard collapse",
28649        );
28650        let mut s = three_member_spec();
28651        s.membros[0].caixa = String::new();
28652        assert_eq!(
28653            s.validate().unwrap_err(),
28654            AplicacaoError::MembroCaixaEmpty,
28655            "an empty-`:caixa` :membros head entry must trip \
28656             MembroCaixaEmpty end-to-end via validate() with the outer \
28657             inline guard removed — the per-slot helper alone is now \
28658             load-bearing",
28659        );
28660        let mut s = three_member_spec();
28661        s.membros[2].caixa = String::new();
28662        assert_eq!(
28663            s.validate().unwrap_err(),
28664            AplicacaoError::MembroCaixaEmpty,
28665            "an empty-`:caixa` :membros tail entry must trip \
28666             MembroCaixaEmpty end-to-end via validate() with the outer \
28667             inline guard removed — the per-slot helper alone reaches \
28668             every fan-out position",
28669        );
28670    }
28671
28672    #[test]
28673    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
28674        // The canonical per-`:placement` Akka-cluster-sharding
28675        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
28676        // the `:placement :shard-key` field byte-for-byte, borrowed
28677        // from the typed slot's own `Option<String>` storage. Peer of
28678        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
28679        // per-`:contratos` [`WitContract::source`] /
28680        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
28681        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
28682        // slot-atom scalar-value axes — same "the substrate-primitive
28683        // accessor must byte-equal the raw field access verbatim across
28684        // every author-declared value" discipline extended to the
28685        // per-`:placement` Akka-cluster-sharding key extractor arm.
28686        // Pins against a future silent detour that re-normalized the
28687        // key (an accidental `.to_lowercase()` — every non-empty
28688        // `:shard-key` is validated as a printable-ASCII single-token
28689        // reference upstream via [`validate_placement_shard_key`], so
28690        // any re-normalization is redundant + a drift surface between
28691        // the validator and the accessor), a per-cluster alias rewrite
28692        // the operator authors on one consumer without the other, or an
28693        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
28694        // that didn't land on the peer field-access sites. Four values
28695        // sweep the accept-set the shape gate admits — bare identifier,
28696        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
28697        // the four canonical Akka-style entity-id extractor shapes the
28698        // future M4 cluster-sharding reconciler hashes.
28699        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
28700            let p = Placement {
28701                estrategia: PlacementStrategy::Sharded,
28702                clusters: vec!["rio".into()],
28703                affinity: None,
28704                shard_key: Some(key.into()),
28705            };
28706            assert_eq!(
28707                p.shard_key(),
28708                Some(key),
28709                "Placement::shard_key must return :placement :shard-key \
28710                 verbatim (got {:?}, expected Some({key:?}))",
28711                p.shard_key(),
28712            );
28713            assert_eq!(
28714                p.shard_key(),
28715                p.shard_key.as_deref(),
28716                "Placement::shard_key must byte-equal the .shard_key \
28717                 field's `.as_deref()` projection",
28718            );
28719        }
28720    }
28721
28722    #[test]
28723    fn placement_shard_key_none_when_field_is_none() {
28724        // The absent-`:shard-key` arm of the per-`:placement`
28725        // Akka-cluster-sharding accessor pin: when the typed slot is
28726        // absent — the canonical shape under `:estrategia Replicated` /
28727        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
28728        // enforced `shard_key.is_some() == matches!(estrategia,
28729        // Sharded)` partition — [`Placement::shard_key`] must return
28730        // `None`. Pins against a future silent detour that projected
28731        // the absent slot to a `Some("")` empty-string default (the
28732        // canonical `Option<String>` → `String` collapse footgun the
28733        // sibling M2 [`crate::LimitsSpec::is_empty`] /
28734        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
28735        // already guard on the peer M2 typed-slot surfaces), a
28736        // `Some("None")` stringified-None round-trip, or a `Some` arm
28737        // whose contents were derived from a sibling slot (an
28738        // accidental fallback to `estrategia.as_str()` that read the
28739        // strategy discriminator into the key axis). Two placements
28740        // sweep the accept-set every `validate`-passing non-`Sharded`
28741        // shape lands on — `Replicated` (Erlang/OTP distributed-app
28742        // takeover) and `SingleNode` (single-node hosting).
28743        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
28744            let p = Placement {
28745                estrategia,
28746                clusters: vec!["rio".into()],
28747                affinity: None,
28748                shard_key: None,
28749            };
28750            assert!(
28751                p.shard_key().is_none(),
28752                "Placement::shard_key must return None when the typed \
28753                 slot is absent under :estrategia {estrategia:?} (got {:?})",
28754                p.shard_key(),
28755            );
28756            assert_eq!(
28757                p.shard_key(),
28758                p.shard_key.as_deref(),
28759                "Placement::shard_key must byte-equal the .shard_key \
28760                 field's `.as_deref()` projection in the absent arm",
28761            );
28762        }
28763    }
28764
28765    #[test]
28766    fn placement_shard_key_borrows_from_shard_key_storage() {
28767        // The borrow-not-copy pin: [`Placement::shard_key`] must return
28768        // an `Option<&str>` whose `Some` arm borrows from the typed
28769        // slot's own [`String`] storage — same-address invariant with
28770        // `p.shard_key.as_deref().unwrap()`. Pins against a future
28771        // silent detour that allocated a fresh `String`
28772        // (`self.shard_key.clone().map(...)` in the body would type-
28773        // check but silently drop the borrow, and every downstream
28774        // consumer that assumed the returned slice outlives `&self`
28775        // would break on a stale-reference use-after-free — the
28776        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
28777        // gate's `Some(k)`-bound match arm reads `k: &str` under the
28778        // accessor's return type and would silently misbehave if this
28779        // accessor produced a detached copy). Peer of the sibling
28780        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
28781        // [`WitContract::source`] / [`WitContract::destination`]
28782        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
28783        // (6db982c) borrow-invariant pins on the mesh-slot-atom
28784        // scalar-value axes — first extension of the discipline onto
28785        // an `Option<String>`-shaped optional-scalar axis.
28786        let p = Placement {
28787            estrategia: PlacementStrategy::Sharded,
28788            clusters: vec!["rio".into()],
28789            affinity: None,
28790            shard_key: Some("tenantId".into()),
28791        };
28792        let key = p.shard_key().expect("Some arm");
28793        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
28794        assert_eq!(
28795            key.as_ptr(),
28796            storage_slice.as_ptr(),
28797            "Placement::shard_key must borrow from the .shard_key \
28798             String's backing storage — a fresh allocation here means \
28799             the accessor no longer names the substrate-primitive typed \
28800             dispatch and every downstream consumer would silently \
28801             carry a detached copy",
28802        );
28803        assert_eq!(
28804            key.len(),
28805            storage_slice.len(),
28806            "Placement::shard_key and .shard_key.as_deref() must byte-\
28807             equal in length as well as in address",
28808        );
28809    }
28810
28811    #[test]
28812    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
28813        // The canonical per-`:placement` M3-Adaptive-compression-hint
28814        // scalar pin: [`Placement::affinity`] must return the
28815        // `:placement :affinity` field byte-for-byte, borrowed from the
28816        // typed slot's own `Option<String>` storage. Peer of the sibling
28817        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
28818        // pin on the sibling `Option<&str>` optional-scalar axis — same
28819        // "the substrate-primitive accessor must byte-equal the raw
28820        // field access verbatim across every author-declared value"
28821        // discipline extended to the peer per-`:placement` M3-Adaptive-
28822        // compression-hint arm. Pins against a future silent detour
28823        // that re-normalized the hint (an accidental `.to_lowercase()`
28824        // — every `:affinity` is already validated as a DNS-1123 label
28825        // upstream via [`validate_placement_affinity`], so any re-
28826        // normalization is redundant + a drift surface between the
28827        // validator and the accessor), a per-cluster alias rewrite the
28828        // operator authors on one consumer without the other, or an
28829        // accidental hint-family collapse (`low-latency` → `latency`
28830        // that dropped the qualifier prefix). Four values sweep the
28831        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
28832        // canonical adaptive-compression-weight biases the future M4
28833        // placement engine reads.
28834        for hint in [
28835            "data-locality",
28836            "low-latency",
28837            "high-throughput",
28838            "cost-optimized",
28839        ] {
28840            let p = Placement {
28841                estrategia: PlacementStrategy::Replicated,
28842                clusters: vec!["rio".into()],
28843                affinity: Some(hint.into()),
28844                shard_key: None,
28845            };
28846            assert_eq!(
28847                p.affinity(),
28848                Some(hint),
28849                "Placement::affinity must return :placement :affinity \
28850                 verbatim (got {:?}, expected Some({hint:?}))",
28851                p.affinity(),
28852            );
28853            assert_eq!(
28854                p.affinity(),
28855                p.affinity.as_deref(),
28856                "Placement::affinity must byte-equal the .affinity \
28857                 field's `.as_deref()` projection",
28858            );
28859        }
28860    }
28861
28862    #[test]
28863    fn placement_affinity_none_when_field_is_none() {
28864        // The absent-`:affinity` arm of the per-`:placement`
28865        // M3-Adaptive-compression-hint accessor pin: when the typed
28866        // slot is absent — the canonical shape of an Aplicacao that
28867        // leaves the compression weighting up to the placement engine's
28868        // cluster-default arm — [`Placement::affinity`] must return
28869        // `None`. Pins against a future silent detour that projected
28870        // the absent slot to a `Some("")` empty-string default (the
28871        // canonical `Option<String>` → `String` collapse footgun the
28872        // sibling M2 [`crate::LimitsSpec::is_empty`] /
28873        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
28874        // already guard on the peer M2 typed-slot surfaces), a
28875        // `Some("None")` stringified-None round-trip, a `Some` arm
28876        // whose contents were derived from a sibling slot (an
28877        // accidental fallback to `estrategia.as_str()` that read the
28878        // strategy discriminator into the hint axis), or a
28879        // `Some("default")` implicit-default that would silently biases
28880        // the routing without the author having written one. Three
28881        // placements sweep the accept-set every `validate`-passing
28882        // `:affinity None` shape lands on — one per PlacementStrategy
28883        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
28884        // with a shard-key), since `:affinity` is orthogonal to
28885        // `:estrategia` in the typed grammar.
28886        for (estrategia, shard_key) in [
28887            (PlacementStrategy::SingleNode, None),
28888            (PlacementStrategy::Replicated, None),
28889            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
28890        ] {
28891            let p = Placement {
28892                estrategia,
28893                clusters: vec!["rio".into()],
28894                affinity: None,
28895                shard_key,
28896            };
28897            assert!(
28898                p.affinity().is_none(),
28899                "Placement::affinity must return None when the typed \
28900                 slot is absent under :estrategia {estrategia:?} (got {:?})",
28901                p.affinity(),
28902            );
28903            assert_eq!(
28904                p.affinity(),
28905                p.affinity.as_deref(),
28906                "Placement::affinity must byte-equal the .affinity \
28907                 field's `.as_deref()` projection in the absent arm",
28908            );
28909        }
28910    }
28911
28912    #[test]
28913    fn placement_affinity_borrows_from_affinity_storage() {
28914        // The borrow-not-copy pin: [`Placement::affinity`] must return
28915        // an `Option<&str>` whose `Some` arm borrows from the typed
28916        // slot's own [`String`] storage — same-address invariant with
28917        // `p.affinity.as_deref().unwrap()`. Pins against a future
28918        // silent detour that allocated a fresh `String`
28919        // (`self.affinity.clone().map(...)` in the body would type-
28920        // check but silently drop the borrow, and every downstream
28921        // consumer that assumed the returned slice outlives `&self`
28922        // would break on a stale-reference use-after-free — the
28923        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
28924        // gate reads the accessor's `&str` return through the
28925        // [`validate_placement_affinity`] `&str` parameter and would
28926        // silently misbehave if this accessor produced a detached
28927        // copy). Peer of the sibling per-`:placement`
28928        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
28929        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
28930        // extends the discipline onto the sibling per-`:placement`
28931        // M3-Adaptive-compression-hint arm.
28932        let p = Placement {
28933            estrategia: PlacementStrategy::Replicated,
28934            clusters: vec!["rio".into()],
28935            affinity: Some("data-locality".into()),
28936            shard_key: None,
28937        };
28938        let hint = p.affinity().expect("Some arm");
28939        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
28940        assert_eq!(
28941            hint.as_ptr(),
28942            storage_slice.as_ptr(),
28943            "Placement::affinity must borrow from the .affinity \
28944             String's backing storage — a fresh allocation here means \
28945             the accessor no longer names the substrate-primitive typed \
28946             dispatch and every downstream consumer would silently \
28947             carry a detached copy",
28948        );
28949        assert_eq!(
28950            hint.len(),
28951            storage_slice.len(),
28952            "Placement::affinity and .affinity.as_deref() must byte-\
28953             equal in length as well as in address",
28954        );
28955    }
28956
28957    #[test]
28958    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
28959        // The canonical per-`:placement` distribution-strategy-scalar
28960        // pin: [`Placement::estrategia`] must return the `:placement
28961        // :estrategia` field verbatim as a [`PlacementStrategy`],
28962        // `Copy`-projected from the typed slot's own `PlacementStrategy`
28963        // storage across every variant in the closed accept-set
28964        // (`SingleNode` — Erlang/OTP distributed-app takeover;
28965        // `Replicated` — active-active across every named cluster;
28966        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
28967        // against a future silent detour that re-derived the strategy
28968        // from a peer axis (an accidental fallback to
28969        // `if shard_key.is_some() { Sharded } else { Replicated }`
28970        // collapse that read the shard-key axis into the strategy
28971        // discriminator), a variant remap the operator authors on one
28972        // consumer without the other, or a stale-derive detour that
28973        // substituted [`PlacementStrategy::default`] when the field
28974        // held any explicit variant (which would silently collapse the
28975        // distinction between "author explicitly declared `:estrategia
28976        // Replicated`" and "author omitted the slot and inherited the
28977        // default" the future per-cluster override slot depends on).
28978        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
28979        // pin on the `Copy`-return `u16` scalar axis — same "the
28980        // substrate-primitive accessor must byte-equal the raw field
28981        // access verbatim across every author-declared value" discipline
28982        // extended onto the per-`:placement` distribution-strategy
28983        // `Copy`-composite-enum scalar axis.
28984        for estrategia in [
28985            PlacementStrategy::SingleNode,
28986            PlacementStrategy::Replicated,
28987            PlacementStrategy::Sharded,
28988        ] {
28989            // Route the paired `:shard-key` fixture-builder through the
28990            // typed cross-slot invariant predicate
28991            // [`PlacementStrategy::requires_shard_key`] rather than the
28992            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
28993            // arm-identity predicate — same discipline the sibling
28994            // `placement_strategy_variants_round_trip` fixture builder now
28995            // reads through.
28996            let shard_key = estrategia
28997                .requires_shard_key()
28998                .then(|| "tenantId".to_string());
28999            let p = Placement {
29000                estrategia,
29001                clusters: vec!["rio".into()],
29002                affinity: None,
29003                shard_key,
29004            };
29005            assert_eq!(
29006                p.estrategia(),
29007                estrategia,
29008                "Placement::estrategia must return :placement :estrategia \
29009                 verbatim (got {:?}, expected {estrategia:?})",
29010                p.estrategia(),
29011            );
29012            assert_eq!(
29013                p.estrategia(),
29014                p.estrategia,
29015                "Placement::estrategia accessor and .estrategia field \
29016                 access must byte-equal — the accessor is the substrate-\
29017                 primitive typed dispatch every downstream distribution-\
29018                 strategy consumer must route through",
29019            );
29020        }
29021    }
29022
29023    #[test]
29024    fn validate_placement_reads_through_lifted_estrategia_accessor() {
29025        // Three-consumer coherence pin: the
29026        // [`AplicacaoSpec::validate_placement`]
29027        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
29028        // `estrategia:` field (which reads through
29029        // [`Placement::estrategia`] to name the strategy the empty
29030        // `:clusters` list was declared against), the same method's
29031        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
29032        // reads through [`Placement::estrategia`] to fan across the
29033        // shape-gate cascades), and the non-`Sharded`-arm
29034        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
29035        // `estrategia:` field (which reads through
29036        // [`Placement::estrategia`] to name the strategy the declared-
29037        // but-inert `:shard-key` was authored under) must all key off
29038        // the lifted accessor, so any future rebrand on the typed
29039        // slot's reader shape lands at exactly one place. Pins the
29040        // three-site coherence by exercising each error surface end-
29041        // to-end and asserting the surfaced `estrategia:` field byte-
29042        // equals the accessor's return. Peer of the sibling per-
29043        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
29044        // pin on the M3 mesh-slot `Copy`-return scalar axis.
29045
29046        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
29047        // whose `estrategia:` field must byte-equal the accessor's return
29048        // for every variant in the closed accept-set.
29049        for estrategia in [
29050            PlacementStrategy::SingleNode,
29051            PlacementStrategy::Replicated,
29052            PlacementStrategy::Sharded,
29053        ] {
29054            let mut spec = three_member_spec();
29055            spec.placement.estrategia = estrategia;
29056            spec.placement.clusters = Vec::new();
29057            // Route the paired `:shard-key` spec-mutator through the typed
29058            // cross-slot invariant predicate
29059            // [`PlacementStrategy::requires_shard_key`] rather than the
29060            // [`gen_platform::IsVariant`]-derived
29061            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
29062            // same discipline the sibling
29063            // `placement_strategy_variants_round_trip` and
29064            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
29065            // fixture builders now read through.
29066            spec.placement.shard_key = estrategia
29067                .requires_shard_key()
29068                .then(|| "tenantId".to_string());
29069            let err = spec.validate().unwrap_err();
29070            match err {
29071                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
29072                    assert_eq!(
29073                        e,
29074                        spec.placement.estrategia(),
29075                        "PlacementWithoutClusters.estrategia must byte-equal \
29076                         Placement::estrategia() — the error carrier reads \
29077                         through the lifted accessor",
29078                    );
29079                }
29080                other => panic!(
29081                    "expected PlacementWithoutClusters, got {other:?} for \
29082                     estrategia={estrategia:?}"
29083                ),
29084            }
29085        }
29086
29087        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
29088        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
29089        // must byte-equal the accessor's return for both non-`Sharded`
29090        // strategies.
29091        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
29092            let mut spec = three_member_spec();
29093            spec.placement.estrategia = estrategia;
29094            spec.placement.shard_key = Some("tenantId".into());
29095            let err = spec.validate().unwrap_err();
29096            match err {
29097                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
29098                    assert_eq!(
29099                        e,
29100                        spec.placement.estrategia(),
29101                        "ShardKeyOnNonSharded.estrategia must byte-equal \
29102                         Placement::estrategia() — the non-Sharded-arm \
29103                         refusal reads through the lifted accessor",
29104                    );
29105                }
29106                other => panic!(
29107                    "expected ShardKeyOnNonSharded, got {other:?} for \
29108                     estrategia={estrategia:?}"
29109                ),
29110            }
29111        }
29112    }
29113
29114    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
29115    //
29116    // The [`Placement::clusters`] accessor lift is the second slice-return
29117    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
29118    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
29119    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
29120    // below cover (1) the accessor's byte-equal projection against the raw
29121    // field access across the empty / singleton / cohort fixtures the
29122    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
29123    // and the per-cluster validate loop fan between, and (2) the two-
29124    // consumer coherence of the paired pre-flight refusal probe and the
29125    // per-cluster validate loop routing through the accessor on both arms.
29126
29127    #[test]
29128    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
29129        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
29130        // [`Placement::clusters`] must return the `:placement :clusters`
29131        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
29132        // the same backing buffer the raw `self.clusters.as_slice()`
29133        // field access borrows from, byte-equal across every
29134        // representative fixture in the accept-set — the empty slice
29135        // (the pre-validation sentinel every
29136        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
29137        // the singleton slice (the minimal `SingleNode`-shape cohort),
29138        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
29139        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
29140        //
29141        // Pins against a future silent detour that returned
29142        // `&Vec<String>` (which would type-check but leak the storage-
29143        // side `Vec`'s grow/push/reserve surface no consumer of the
29144        // typed view reaches for), a fresh-allocated `Vec<String>` copy
29145        // (which would type-check via a coercion but silently break
29146        // every downstream caller that relied on the slice sharing the
29147        // backing buffer's identity), or an out-of-order or length-
29148        // drifted projection (which would silently split the paired
29149        // pre-flight `.is_empty()` refusal probe's input from the per-
29150        // cluster validate loop's traversal input).
29151        //
29152        // Peer of the sibling M2
29153        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
29154        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
29155        // `:supervisor` static-child-list axis, extended onto the M3
29156        // per-`:placement` distribution-target-list `Vec`-carry axis.
29157        let fixtures: Vec<Vec<String>> = vec![
29158            Vec::new(),
29159            vec!["rio".into()],
29160            vec!["rio".into(), "mar".into()],
29161            vec!["rio".into(), "mar".into(), "plo".into()],
29162        ];
29163        for clusters in fixtures {
29164            let p = Placement {
29165                clusters: clusters.clone(),
29166                ..Placement::default()
29167            };
29168            assert_eq!(
29169                p.clusters(),
29170                clusters.as_slice(),
29171                "Placement::clusters must return :placement :clusters \
29172                 verbatim (got {:?}, expected {:?})",
29173                p.clusters(),
29174                clusters.as_slice(),
29175            );
29176            assert_eq!(
29177                p.clusters(),
29178                p.clusters.as_slice(),
29179                "Placement::clusters accessor and .clusters.as_slice() \
29180                 field access must byte-equal — the accessor is the \
29181                 substrate-primitive typed dispatch every downstream \
29182                 cluster-pool consumer must route through",
29183            );
29184            assert_eq!(
29185                p.clusters().len(),
29186                p.clusters.len(),
29187                "Placement::clusters().len() must byte-equal \
29188                 self.clusters.len() — a length-drift would silently \
29189                 split the paired pre-flight `.is_empty()` refusal \
29190                 probe input from the per-cluster validate loop's \
29191                 traversal input",
29192            );
29193        }
29194    }
29195
29196    #[test]
29197    fn validate_placement_reads_through_lifted_clusters_accessor() {
29198        // Two-consumer coherence pin: the
29199        // [`AplicacaoSpec::validate_placement`] pre-flight
29200        // `self.placement.clusters().is_empty()` refusal probe (which
29201        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
29202        // the accessor projects the empty slice) and the per-cluster
29203        // validate loop's `for c in self.placement.clusters()`
29204        // traversal (which must reach every entry in the same order
29205        // the accessor projects, so both the per-entry value-shape
29206        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
29207        // and the duplicate-detection HashSet insert that trips
29208        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
29209        // accessor's projection) must both key off the lifted
29210        // accessor, so any future rebrand on the typed slot's reader
29211        // shape lands at exactly one place. Pins the two-site
29212        // coherence by exercising each production consumer end-to-end:
29213        // (1) the `PlacementWithoutClusters` refusal under the empty
29214        // slice, (2) the `PlacementClusterInvalid` refusal fires on
29215        // the second entry of a two-cluster cohort whose head is
29216        // valid but tail is not (which requires the loop to reach the
29217        // second entry through the accessor), and (3) the
29218        // `PlacementClusterDuplicate` refusal fires on the second
29219        // entry of a two-cluster cohort that shares a name (which
29220        // requires the loop to reach both entries — a first-entry-only
29221        // projection would silently pass since the dedup HashSet has
29222        // room for the first insert).
29223        //
29224        // Peer of the sibling M2
29225        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
29226        // (bc92bce) coherence pin on the per-`:supervisor` static-
29227        // child-list axis, extended onto the M3 per-`:placement`
29228        // distribution-target-list `Vec`-carry axis.
29229
29230        // (1) Pre-flight `.is_empty()` probe: the empty slice must
29231        // trip `PlacementWithoutClusters`.
29232        let mut spec = three_member_spec();
29233        spec.placement.clusters = Vec::new();
29234        match spec.validate().unwrap_err() {
29235            AplicacaoError::PlacementWithoutClusters { .. } => {}
29236            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
29237        }
29238        assert!(
29239            spec.placement.clusters().is_empty(),
29240            "the pre-flight refusal input must be the empty slice per \
29241             the accessor's projection",
29242        );
29243
29244        // (2) Per-cluster validate loop: a two-cluster cohort with an
29245        // invalid tail entry must trip `PlacementClusterInvalid` on
29246        // the tail — the loop must reach the second entry through
29247        // the accessor.
29248        let mut spec = three_member_spec();
29249        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
29250        match spec.validate().unwrap_err() {
29251            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
29252                assert_eq!(
29253                    cluster, "BAD_CLUSTER",
29254                    "PlacementClusterInvalid.cluster must carry the \
29255                     tail entry the loop reached through the accessor",
29256                );
29257            }
29258            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
29259        }
29260        assert_eq!(
29261            spec.placement.clusters().len(),
29262            2,
29263            "the per-cluster validate loop's traversal input must be \
29264             a two-element slice per the accessor's projection",
29265        );
29266
29267        // (3) Per-cluster validate loop: a two-cluster cohort that
29268        // shares a name must trip `PlacementClusterDuplicate` on the
29269        // second entry — the loop must reach both entries through the
29270        // accessor for the dedup HashSet's second insert to collide.
29271        let mut spec = three_member_spec();
29272        spec.placement.clusters = vec!["rio".into(), "rio".into()];
29273        match spec.validate().unwrap_err() {
29274            AplicacaoError::PlacementClusterDuplicate { cluster } => {
29275                assert_eq!(
29276                    cluster, "rio",
29277                    "PlacementClusterDuplicate.cluster must carry the \
29278                     shared cluster name verbatim",
29279                );
29280            }
29281            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
29282        }
29283        assert_eq!(
29284            spec.placement.clusters().len(),
29285            2,
29286            "the per-cluster validate loop's traversal input must be \
29287             a two-element slice per the accessor's projection",
29288        );
29289    }
29290
29291    #[test]
29292    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
29293        // The canonical per-`:membros` member-list-slice-shape pin:
29294        // [`AplicacaoSpec::membros`] must return the `:membros` typed
29295        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
29296        // same backing buffer the raw `self.membros.as_slice()` field
29297        // access borrows from, byte-equal across every representative
29298        // fixture in the accept-set — the empty slice (the pre-
29299        // validation sentinel every [`AplicacaoError::NoMembros`]
29300        // refusal keys off), the singleton slice (the minimal one-
29301        // Servico Aplicacao shape), and multi-entry cohorts (the peer
29302        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
29303        // load-bearing identity of the application graph).
29304        //
29305        // Pins against a future silent detour that returned
29306        // `&Vec<Membro>` (which would type-check but leak the storage-
29307        // side `Vec`'s grow/push/reserve surface no consumer of the
29308        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
29309        // (which would type-check via a coercion but silently break
29310        // every downstream caller that relied on the slice sharing the
29311        // backing buffer's identity), or an out-of-order or length-
29312        // drifted projection (which would silently split the paired
29313        // `HashSet<&str>` name-set seed's collect input from the
29314        // pre-flight `.is_empty()` refusal probe's input from the per-
29315        // member validate loop's traversal input from the
29316        // programs.yaml emitter's per-entry fan-out loop's input from
29317        // the `feira app graph` per-member print traversal's input).
29318        //
29319        // Peer of the sibling M2
29320        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
29321        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
29322        // `:supervisor` static-child-list axis and the sibling M3
29323        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
29324        // (a6e18d7) `&[String]` byte-equal pin on the per-
29325        // `:placement` distribution-target-list axis — extends the
29326        // slice-return-accessor byte-equal-projection discipline onto
29327        // the outermost M3 mesh-slot type's per-Aplicacao member-list
29328        // `Vec`-carry axis.
29329        let fixtures: Vec<Vec<Membro>> = vec![
29330            Vec::new(),
29331            vec![membro("catalog", "^0.1")],
29332            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
29333            vec![
29334                membro("catalog", "^0.1"),
29335                membro("cart", "^0.1"),
29336                membro("payment", "^0.2"),
29337            ],
29338        ];
29339        for membros in fixtures {
29340            let s = AplicacaoSpec {
29341                membros: membros.clone(),
29342                contratos: Vec::new(),
29343                politicas: MeshPolicy::default(),
29344                placement: Placement::default(),
29345                entrada: None,
29346            };
29347            assert_eq!(
29348                s.membros(),
29349                membros.as_slice(),
29350                "AplicacaoSpec::membros must return :membros verbatim \
29351                 (got {:?}, expected {:?})",
29352                s.membros(),
29353                membros.as_slice(),
29354            );
29355            assert_eq!(
29356                s.membros(),
29357                s.membros.as_slice(),
29358                "AplicacaoSpec::membros accessor and .membros.as_slice() \
29359                 field access must byte-equal — the accessor is the \
29360                 substrate-primitive typed dispatch every downstream \
29361                 member-list consumer must route through",
29362            );
29363            assert_eq!(
29364                s.membros().len(),
29365                s.membros.len(),
29366                "AplicacaoSpec::membros().len() must byte-equal \
29367                 self.membros.len() — a length-drift would silently \
29368                 split the paired `HashSet<&str>` name-set seed's \
29369                 collect input from the pre-flight `.is_empty()` \
29370                 refusal probe input from the per-member validate \
29371                 loop's traversal input",
29372            );
29373        }
29374    }
29375
29376    #[test]
29377    fn validate_reads_through_lifted_membros_accessor() {
29378        // Three-consumer coherence pin: the
29379        // [`AplicacaoSpec::validate_membros`] pre-flight
29380        // `self.membros().is_empty()` refusal probe (which must trip
29381        // [`AplicacaoError::NoMembros`] when the accessor projects the
29382        // empty slice), the same method's per-member validate loop's
29383        // `for m in self.membros()` traversal (which must reach every
29384        // entry in the same order the accessor projects, so both the
29385        // per-entry empty-`:caixa` gate that trips
29386        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
29387        // detection `insert_first_seen` that trips
29388        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
29389        // projection), and the peer [`AplicacaoSpec::validate`]'s
29390        // `HashSet<&str>` name-set seed's
29391        // `self.membros().iter().map(Membro::nome).collect()` collect
29392        // input (which every `:contratos` `:de` / `:para` membership
29393        // lookup rejects an unknown name against) must all three key
29394        // off the lifted accessor, so any future rebrand on the typed
29395        // slot's reader shape lands at exactly one place. Pins the
29396        // three-site coherence by exercising each production consumer
29397        // end-to-end: (1) the `NoMembros` refusal under the empty
29398        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
29399        // second entry of a two-member cohort whose head is valid but
29400        // tail has an empty `:caixa` (which requires the loop to
29401        // reach the second entry through the accessor), and (3) the
29402        // `MembroDuplicate` refusal fires on the second entry of a
29403        // two-member cohort that shares a `:caixa` name (which
29404        // requires the loop to reach both entries through the
29405        // accessor for the dedup HashSet's second insert to collide).
29406        //
29407        // Peer of the sibling M2
29408        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
29409        // (bc92bce) coherence pin on the per-`:supervisor` static-
29410        // child-list axis and the sibling M3
29411        // `validate_placement_reads_through_lifted_clusters_accessor`
29412        // (a6e18d7) coherence pin on the per-`:placement` distribution-
29413        // target-list axis — extends the slice-return-accessor
29414        // multi-consumer coherence discipline onto the outermost M3
29415        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
29416
29417        // (1) Pre-flight `.is_empty()` probe: the empty slice must
29418        // trip `NoMembros`.
29419        let mut spec = three_member_spec();
29420        spec.membros = Vec::new();
29421        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
29422        assert!(
29423            spec.membros().is_empty(),
29424            "the pre-flight refusal input must be the empty slice per \
29425             the accessor's projection",
29426        );
29427
29428        // (2) Per-member validate loop: a two-member cohort with an
29429        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
29430        // the tail — the loop must reach the second entry through
29431        // the accessor.
29432        let mut spec = three_member_spec();
29433        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
29434        assert_eq!(
29435            spec.validate().unwrap_err(),
29436            AplicacaoError::MembroCaixaEmpty,
29437        );
29438        assert_eq!(
29439            spec.membros().len(),
29440            2,
29441            "the per-member validate loop's traversal input must be \
29442             a two-element slice per the accessor's projection",
29443        );
29444
29445        // (3) Per-member validate loop: a two-member cohort that
29446        // shares a `:caixa` name must trip `MembroDuplicate` on the
29447        // second entry — the loop must reach both entries through the
29448        // accessor for the dedup HashSet's second insert to collide.
29449        let mut spec = three_member_spec();
29450        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
29451        match spec.validate().unwrap_err() {
29452            AplicacaoError::MembroDuplicate { caixa } => {
29453                assert_eq!(
29454                    caixa, "catalog",
29455                    "MembroDuplicate.caixa must carry the shared \
29456                     member name verbatim",
29457                );
29458            }
29459            other => panic!("expected MembroDuplicate, got {other:?}"),
29460        }
29461        assert_eq!(
29462            spec.membros().len(),
29463            2,
29464            "the per-member validate loop's traversal input must be \
29465             a two-element slice per the accessor's projection",
29466        );
29467    }
29468
29469    #[test]
29470    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
29471        // The canonical per-`:contratos` contract-list-slice-shape pin:
29472        // [`AplicacaoSpec::contratos`] must return the `:contratos`
29473        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
29474        // slice-view over the same backing buffer the raw
29475        // `self.contratos.as_slice()` field access borrows from, byte-
29476        // equal across every representative fixture in the accept-set —
29477        // the empty slice (the pre-validation "internal-only mesh" shape
29478        // an Aplicacao whose members exchange no typed edges renders
29479        // through), the singleton slice (the minimal one-edge Aplicacao
29480        // shape), and multi-entry cohorts (the peer multi-edge shapes
29481        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
29482        // of the application graph).
29483        //
29484        // Pins against a future silent detour that returned
29485        // `&Vec<WitContract>` (which would type-check but leak the
29486        // storage-side `Vec`'s grow/push/reserve surface no consumer of
29487        // the typed view reaches for), a fresh-allocated
29488        // `Vec<WitContract>` copy (which would type-check via a coercion
29489        // but silently break every downstream caller that relied on the
29490        // slice sharing the backing buffer's identity), or an out-of-
29491        // order or length-drifted projection (which would silently split
29492        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
29493        // seed's traversal input from the `detect_sync_cycles` per-edge
29494        // adjacency-list seed's traversal input from the
29495        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
29496        // BTreeMap grouping loop's traversal input from the
29497        // `feira app graph` per-contract print traversal's input).
29498        //
29499        // Peer of the immediately-adjacent sibling M3
29500        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
29501        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
29502        // node-list axis, the sibling M3
29503        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
29504        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
29505        // distribution-target-list axis, and the sibling M2
29506        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
29507        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
29508        // `:supervisor` static-child-list axis — extends the slice-
29509        // return-accessor byte-equal-projection discipline onto the
29510        // outermost M3 mesh-slot type's per-Aplicacao contract-list
29511        // `Vec`-carry axis, closing the last unlifted per-
29512        // `AplicacaoSpec` `Vec`-carry axis.
29513        let fixtures: Vec<Vec<WitContract>> = vec![
29514            Vec::new(),
29515            vec![contract_http("cart", "catalog", "/products/:id")],
29516            vec![
29517                contract_http("cart", "catalog", "/products/:id"),
29518                contract_http("cart", "payment", "/charge"),
29519            ],
29520            vec![
29521                contract_http("cart", "catalog", "/products/:id"),
29522                contract_http("cart", "payment", "/charge"),
29523                contract_http("payment", "catalog", "/audit"),
29524            ],
29525        ];
29526        for contratos in fixtures {
29527            let s = AplicacaoSpec {
29528                membros: vec![
29529                    membro("catalog", "^0.1"),
29530                    membro("cart", "^0.1"),
29531                    membro("payment", "^0.2"),
29532                ],
29533                contratos: contratos.clone(),
29534                politicas: MeshPolicy::default(),
29535                placement: Placement::default(),
29536                entrada: None,
29537            };
29538            assert_eq!(
29539                s.contratos(),
29540                contratos.as_slice(),
29541                "AplicacaoSpec::contratos must return :contratos verbatim \
29542                 (got {:?}, expected {:?})",
29543                s.contratos(),
29544                contratos.as_slice(),
29545            );
29546            assert_eq!(
29547                s.contratos(),
29548                s.contratos.as_slice(),
29549                "AplicacaoSpec::contratos accessor and \
29550                 .contratos.as_slice() field access must byte-equal — \
29551                 the accessor is the substrate-primitive typed dispatch \
29552                 every downstream contract-list consumer must route \
29553                 through",
29554            );
29555            assert_eq!(
29556                s.contratos().len(),
29557                s.contratos.len(),
29558                "AplicacaoSpec::contratos().len() must byte-equal \
29559                 self.contratos.len() — a length-drift would silently \
29560                 split the paired per-edge validate-loop's traversal \
29561                 input from the sync-cycle adjacency-list seed's \
29562                 traversal input from the cilium_network_policies \
29563                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
29564                 input from the `feira app graph` per-contract print \
29565                 traversal's input",
29566            );
29567        }
29568    }
29569
29570    #[test]
29571    fn validate_reads_through_lifted_contratos_accessor() {
29572        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
29573        // per-`:contratos` validate-loop's `for c in self.contratos()`
29574        // traversal (which must reach every entry in the same order the
29575        // accessor projects, so both the per-entry
29576        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
29577        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
29578        // dedup `HashSet` insert key off the accessor's projection),
29579        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
29580        // `for c in self.contratos()` adjacency-list seed (which drives
29581        // the sync-subgraph deadlock-detection gate via
29582        // [`AplicacaoError::SyncCycle`]), and the peer
29583        // [`caixa_mesh::cilium_network_policies`]'s
29584        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
29585        // grouping loop (which drives the per-CNP fan-out) must all
29586        // three key off the lifted accessor, so any future rebrand on
29587        // the typed slot's reader shape lands at exactly one place. Pins
29588        // the three-site coherence by exercising the two caixa-core
29589        // production consumers end-to-end: (1) the empty-`:contratos`
29590        // slice must validate without a per-edge diagnostic (the
29591        // per-edge loop is a no-op under the empty projection), (2) the
29592        // `ContratoMemberMissing` refusal fires on the second entry of a
29593        // two-edge cohort whose head references a valid member but tail
29594        // references a phantom name (which requires the loop to reach
29595        // the second entry through the accessor), and (3) the
29596        // `SyncCycle` refusal fires on a self-referential two-edge
29597        // cohort through the sync-cycle detector's peer projection
29598        // (which requires the detector to iterate the accessor's
29599        // projection to add the back-edge to its adjacency list).
29600        //
29601        // Peer of the sibling M3
29602        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
29603        // three-consumer coherence pin on the per-`:membros` node-list
29604        // axis and the sibling M3
29605        // `validate_placement_reads_through_lifted_clusters_accessor`
29606        // (a6e18d7) coherence pin on the per-`:placement` distribution-
29607        // target-list axis — extends the slice-return-accessor multi-
29608        // consumer coherence discipline onto the outermost M3 mesh-slot
29609        // type's per-Aplicacao contract-list `Vec`-carry axis.
29610
29611        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
29612        // and no per-edge diagnostic surfaces. Validate succeeds on
29613        // the well-formed `:membros` head.
29614        let mut spec = three_member_spec();
29615        spec.contratos = Vec::new();
29616        assert!(
29617            spec.validate().is_ok(),
29618            "empty :contratos must validate — the per-edge loop is a \
29619             no-op under the accessor's empty projection",
29620        );
29621        assert!(
29622            spec.contratos().is_empty(),
29623            "the per-edge validate loop's traversal input must be the \
29624             empty slice per the accessor's projection",
29625        );
29626
29627        // (2) Per-edge validate loop: a two-edge cohort whose tail
29628        // references a phantom `:para` member must trip
29629        // `ContratoMemberMissing` on the tail — the loop must reach
29630        // the second entry through the accessor for the membership
29631        // lookup to fail on the phantom name.
29632        let mut spec = three_member_spec();
29633        spec.contratos = vec![
29634            contract_http("cart", "catalog", "/products/:id"),
29635            contract_http("cart", "phantom", "/x"),
29636        ];
29637        let err = spec.validate().unwrap_err();
29638        assert!(
29639            matches!(
29640                err,
29641                AplicacaoError::ContratoMemberMissing { ref caixa }
29642                    if caixa == "phantom"
29643            ),
29644            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
29645        );
29646        assert_eq!(
29647            spec.contratos().len(),
29648            2,
29649            "the per-edge validate loop's traversal input must be \
29650             a two-element slice per the accessor's projection",
29651        );
29652
29653        // (3) Sync-cycle detector: a two-edge synchronous cohort
29654        // whose second edge closes the sync-subgraph back onto the
29655        // first must trip [`AplicacaoError::ContratoCycle`] — the
29656        // detector must iterate the accessor's projection to add
29657        // both edges to its adjacency list, so a length-drift on
29658        // the accessor's projection would silently disagree with
29659        // the sync-cycle detector on which edge closes the loop.
29660        // Peer projection to the `validate` per-edge loop above:
29661        // the sync-cycle detector routes through the same lifted
29662        // accessor, so a rebrand of the reader shape lands at one
29663        // place. Uses a two-edge cohort (cart → catalog → cart)
29664        // because the per-edge `ContratoSelfLoop` gate fires before
29665        // the sync-cycle detector on a single self-referential edge
29666        // (`cart → cart`) — the cycle-detector's input must be a
29667        // multi-edge cohort for its per-edge traversal input to be
29668        // observably wider than the per-edge validate loop's input.
29669        let mut spec = three_member_spec();
29670        spec.contratos = vec![
29671            contract_http("cart", "catalog", "/products/:id"),
29672            contract_http("catalog", "cart", "/callback"),
29673        ];
29674        let err = spec.validate().unwrap_err();
29675        assert!(
29676            matches!(err, AplicacaoError::ContratoCycle { .. }),
29677            "expected ContratoCycle from the sync-cycle detector on a \
29678             two-edge back-edge cohort, got {err:?}",
29679        );
29680        assert_eq!(
29681            spec.contratos().len(),
29682            2,
29683            "the sync-cycle detector's traversal input must be a \
29684             two-element slice per the accessor's projection",
29685        );
29686    }
29687
29688    #[test]
29689    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
29690        // The canonical per-`:politicas` outer-composite-reference-shape
29691        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
29692        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
29693        // the same backing storage the raw `&self.politicas` field
29694        // access borrows from, byte-equal across every representative
29695        // fixture in the accept-set — the default `MeshPolicy` (the
29696        // author-empty "no policy on any axis" shape whose
29697        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
29698        // shapes carrying one axis at a time
29699        // (`{mtls_required, timeout, retries, circuit_breaker,
29700        // rate_limit}` — the minimal five-axis fan-out over the
29701        // per-axis lifted accessor family every downstream mesh-artifact
29702        // emitter dispatches on), and the multi-axis composite (the
29703        // canonical `three_member_spec` fixture's `{timeout, retries,
29704        // mtls_required}` triple — the load-bearing shape every
29705        // Aplicacao-scoped fixture in this suite constructs).
29706        //
29707        // Pins against a future silent detour that returned a fresh-
29708        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
29709        // impl but silently break every downstream caller that relied
29710        // on the reference sharing the composite's backing identity), a
29711        // reference to an operator-resolved overlay (the future
29712        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
29713        // acknowledges — its resolution must land at exactly this
29714        // accessor body, not silently divert the raw slot away from a
29715        // second consumer), or an axis-shuffled projection (a future
29716        // detour that swapped `timeout` and `retries` through the
29717        // accessor would silently split the paired `validate_politicas`
29718        // per-axis bracket-dispatch's traversal input from the peer
29719        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
29720        // emitter's fan-out input from the peer
29721        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
29722        // overlay emitter's fan-out input).
29723        //
29724        // Peer of the sibling M3
29725        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
29726        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
29727        // node-list `Vec`-carry axis and the sibling M3
29728        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
29729        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
29730        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
29731        // accessor byte-equal-projection discipline onto the outermost
29732        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
29733        // reference axis, the first `&Composite`-return accessor on the
29734        // outer [`AplicacaoSpec`] type.
29735        let fixtures: Vec<MeshPolicy> = vec![
29736            MeshPolicy::default(),
29737            MeshPolicy {
29738                mtls_required: Some(true),
29739                ..MeshPolicy::default()
29740            },
29741            MeshPolicy {
29742                mtls_required: Some(false),
29743                ..MeshPolicy::default()
29744            },
29745            MeshPolicy {
29746                timeout: Some(Duration::from_secs(30)),
29747                ..MeshPolicy::default()
29748            },
29749            MeshPolicy {
29750                retries: Some(3),
29751                ..MeshPolicy::default()
29752            },
29753            MeshPolicy {
29754                circuit_breaker: Some(CircuitBreaker {
29755                    max_failures: 5,
29756                    window: Duration::from_secs(30),
29757                }),
29758                ..MeshPolicy::default()
29759            },
29760            MeshPolicy {
29761                rate_limit: Some(RateLimit {
29762                    rate: 100,
29763                    window: Duration::from_secs(1),
29764                }),
29765                ..MeshPolicy::default()
29766            },
29767            MeshPolicy {
29768                timeout: Some(Duration::from_secs(30)),
29769                retries: Some(3),
29770                mtls_required: Some(true),
29771                ..MeshPolicy::default()
29772            },
29773        ];
29774        for politicas in fixtures {
29775            let s = AplicacaoSpec {
29776                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
29777                contratos: Vec::new(),
29778                politicas: politicas.clone(),
29779                placement: Placement::default(),
29780                entrada: None,
29781            };
29782            assert_eq!(
29783                *s.politicas(),
29784                politicas,
29785                "AplicacaoSpec::politicas must return :politicas verbatim \
29786                 (got {:?}, expected {:?})",
29787                s.politicas(),
29788                politicas,
29789            );
29790            assert!(
29791                std::ptr::eq(s.politicas(), &s.politicas),
29792                "AplicacaoSpec::politicas accessor and &self.politicas \
29793                 field access must borrow the same backing storage — \
29794                 the accessor is the substrate-primitive typed dispatch \
29795                 every downstream mesh-policy composite consumer must \
29796                 route through, and a reference-identity split would \
29797                 silently break every consumer that relied on the \
29798                 borrow sharing the composite's storage",
29799            );
29800            assert_eq!(
29801                s.politicas().is_empty(),
29802                s.politicas.is_empty(),
29803                "AplicacaoSpec::politicas().is_empty() must byte-equal \
29804                 self.politicas.is_empty() — an emptiness-drift would \
29805                 silently split the paired `validate_politicas` \
29806                 per-axis bracket-dispatch's seed from the peer \
29807                 caixa-mesh CNP mTLS-overlay emitter's key from the \
29808                 peer caixa-mesh HTTPRoute timeout+retry overlay \
29809                 emitter's key",
29810            );
29811        }
29812    }
29813
29814    #[test]
29815    fn validate_politicas_reads_through_lifted_politicas_accessor() {
29816        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
29817        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
29818        // followed by the per-axis fan-out `p.timeout()` /
29819        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
29820        // the lifted axis-level accessor family) must key off the
29821        // lifted outer accessor, so any future rebrand on the typed
29822        // slot's outer-composite reader shape lands at exactly one
29823        // place. Pins the multi-axis coherence by exercising each
29824        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
29825        // a `Some(Duration::ZERO)` timeout under the outer accessor's
29826        // reference projection, (2) `PolicyRetriesZero` fires on a
29827        // `Some(0)` retries under the same projection, and (3) an
29828        // empty [`MeshPolicy::default`] passes `validate_politicas` —
29829        // the outer accessor's reference-projection reaches every
29830        // per-axis branch without silently short-circuiting any.
29831        //
29832        // Peer of the sibling M3
29833        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
29834        // three-consumer coherence pin on the per-`:membros` node-list
29835        // axis and the sibling M3
29836        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
29837        // three-consumer coherence pin on the per-`:contratos`
29838        // edge-list axis — extends the multi-consumer coherence
29839        // discipline onto the outermost M3 mesh-slot type's per-
29840        // Aplicacao mesh-policy composite-reference axis, the first
29841        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
29842        // type.
29843
29844        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
29845        // reference projection: a `Some(Duration::ZERO)` timeout must
29846        // trip the zero-floor gate. The bracket-dispatch's first arm
29847        // reads `p.timeout()` on the reference returned by the outer
29848        // accessor.
29849        let mut spec = three_member_spec();
29850        spec.politicas.timeout = Some(Duration::ZERO);
29851        spec.politicas.retries = None;
29852        spec.politicas.circuit_breaker = None;
29853        spec.politicas.rate_limit = None;
29854        assert_eq!(
29855            spec.validate().unwrap_err(),
29856            AplicacaoError::PolicyTimeoutZero,
29857        );
29858        assert!(
29859            std::ptr::eq(spec.politicas(), &spec.politicas),
29860            "the `validate_politicas` per-axis bracket-dispatch's \
29861             traversal input must be the same backing composite the \
29862             accessor's reference projection borrows from",
29863        );
29864
29865        // (2) `PolicyRetriesZero` refusal under the outer accessor's
29866        // reference projection: a `Some(0)` retries must trip the
29867        // zero-floor gate. The bracket-dispatch's second arm reads
29868        // `p.retries()` on the reference returned by the outer accessor.
29869        let mut spec = three_member_spec();
29870        spec.politicas.timeout = None;
29871        spec.politicas.retries = Some(0);
29872        spec.politicas.circuit_breaker = None;
29873        spec.politicas.rate_limit = None;
29874        assert_eq!(
29875            spec.validate().unwrap_err(),
29876            AplicacaoError::PolicyRetriesZero,
29877        );
29878
29879        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
29880        // — every per-axis arm short-circuits on `None`, so the outer
29881        // accessor's reference projection reaches the fall-through
29882        // `Ok(())` without any per-axis refusal firing.
29883        let mut spec = three_member_spec();
29884        spec.politicas = MeshPolicy::default();
29885        assert!(
29886            spec.validate().is_ok(),
29887            "an empty `MeshPolicy` must pass `validate_politicas` — \
29888             every per-axis arm short-circuits on `None` under the \
29889             outer accessor's reference projection",
29890        );
29891        assert!(
29892            spec.politicas().is_empty(),
29893            "the outer accessor's reference projection must be the \
29894             empty composite per the `MeshPolicy::default()` fixture",
29895        );
29896    }
29897
29898    #[test]
29899    #[allow(clippy::too_many_lines)]
29900    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
29901        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
29902        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
29903        // must both key off the lifted axis-level accessors
29904        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
29905        // the peer `:circuit-breaker` / `:rate-limit` arms already
29906        // routing through [`MeshPolicy::circuit_breaker`] /
29907        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
29908        // per axis on the substrate primitive" shape at the fan-out
29909        // (four axes, four accessors, no raw-field-access site
29910        // anywhere on the bracket-dispatch). Pins the per-axis
29911        // coherence at the accept-set boundaries the bracket carves:
29912        //   1. accessor byte-equal to raw field on every representative
29913        //      accept-set value (`None`, sub-cap, at-cap, past-cap
29914        //      sentinel) — a future accessor drift that no longer
29915        //      shipped the raw slot verbatim would surface here,
29916        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
29917        //      routed through the accessor's projection, proving the
29918        //      first arm reads through the accessor rather than a
29919        //      silent-detour peer-axis field access,
29920        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
29921        //      through the accessor's projection, proving the second
29922        //      arm reads through the accessor,
29923        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
29924        //      passes validate under the accessor projection (paired
29925        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
29926        //      sibling axis), pinning the upper-boundary accept-arm
29927        //      also routes through the accessor.
29928        //
29929        // Peer of the sibling M3
29930        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
29931        // outer-composite-reference coherence pin (which asserts the
29932        // `let p = self.politicas()` seed); extends the discipline onto
29933        // the per-axis fan-out layer that consumes the seed's
29934        // reference. Same shape as
29935        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
29936        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
29937        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
29938        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
29939
29940        // (1) Accessor byte-equal to raw field on the `:timeout` axis
29941        // across the accept-set boundaries the bracket dispatch's
29942        // three-arm gate carves out
29943        // ([`crate::render::require_positive_canonical_bounded_duration`]
29944        // — zero-floor + canonical-form + upper-cap).
29945        for timeout in [
29946            None,
29947            Some(Duration::ZERO),
29948            Some(Duration::from_millis(1)),
29949            Some(POLICY_TIMEOUT_MAX),
29950        ] {
29951            let p = MeshPolicy {
29952                timeout,
29953                ..MeshPolicy::default()
29954            };
29955            assert_eq!(
29956                p.timeout(),
29957                p.timeout,
29958                "MeshPolicy::timeout accessor must byte-equal the raw \
29959                 .timeout field across every accept-set boundary the \
29960                 validate_politicas :timeout arm carves out — a drift \
29961                 here would silently split the validate bracket's arm \
29962                 from the peer caixa-mesh HTTPRoute timeout-overlay \
29963                 emitter's read",
29964            );
29965        }
29966
29967        // (2) Accessor byte-equal to raw field on the `:retries` axis
29968        // across the accept-set boundaries the bracket dispatch's
29969        // two-arm gate carves out
29970        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
29971        // + upper-cap).
29972        for retries in [
29973            None,
29974            Some(0u32),
29975            Some(1u32),
29976            Some(POLICY_RETRIES_MAX),
29977            Some(POLICY_RETRIES_MAX + 1),
29978            Some(u32::MAX),
29979        ] {
29980            let p = MeshPolicy {
29981                retries,
29982                ..MeshPolicy::default()
29983            };
29984            assert_eq!(
29985                p.retries(),
29986                p.retries,
29987                "MeshPolicy::retries accessor must byte-equal the raw \
29988                 .retries field across every accept-set boundary the \
29989                 validate_politicas :retries arm carves out — a drift \
29990                 here would silently split the validate bracket's arm \
29991                 from the peer caixa-mesh HTTPRoute retry-overlay \
29992                 emitter's read",
29993            );
29994        }
29995
29996        // (3) `PolicyTimeoutZero` fires on the accessor-projected
29997        // zero-floor boundary. A silent detour that no longer read
29998        // through `p.timeout()` (a peer-axis field read, an accidental
29999        // Option::and-then chain that collapsed the None arm to Some,
30000        // an accessor rebrand that clamped the return through the
30001        // upper cap) would fail to refuse here.
30002        let mut spec = three_member_spec();
30003        spec.politicas.timeout = Some(Duration::ZERO);
30004        spec.politicas.retries = None;
30005        spec.politicas.circuit_breaker = None;
30006        spec.politicas.rate_limit = None;
30007        assert_eq!(
30008            spec.politicas().timeout(),
30009            Some(Duration::ZERO),
30010            "the accessor projection must reflect the fixture's \
30011             `Some(Duration::ZERO)` :timeout verbatim",
30012        );
30013        assert_eq!(
30014            spec.validate().unwrap_err(),
30015            AplicacaoError::PolicyTimeoutZero,
30016            "the validate_politicas :timeout zero-floor arm must fire \
30017             through the lifted accessor's projection — a silent \
30018             detour to a peer-axis field would fail to refuse",
30019        );
30020
30021        // (4) `PolicyRetriesZero` fires on the accessor-projected
30022        // zero-floor boundary on the sibling `:retries` axis.
30023        let mut spec = three_member_spec();
30024        spec.politicas.timeout = None;
30025        spec.politicas.retries = Some(0);
30026        spec.politicas.circuit_breaker = None;
30027        spec.politicas.rate_limit = None;
30028        assert_eq!(
30029            spec.politicas().retries(),
30030            Some(0),
30031            "the accessor projection must reflect the fixture's \
30032             `Some(0)` :retries verbatim",
30033        );
30034        assert_eq!(
30035            spec.validate().unwrap_err(),
30036            AplicacaoError::PolicyRetriesZero,
30037            "the validate_politicas :retries zero-floor arm must fire \
30038             through the lifted accessor's projection — a silent \
30039             detour to a peer-axis field would fail to refuse",
30040        );
30041
30042        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
30043        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
30044        // must pass validate under the accessor projection — pins the
30045        // upper-boundary accept-arm also routes through the lifted
30046        // accessor (a drift that clamped or short-circuited at the
30047        // upper boundary would fail the whole-spec validate here).
30048        let mut spec = three_member_spec();
30049        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
30050        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
30051        spec.politicas.circuit_breaker = None;
30052        spec.politicas.rate_limit = None;
30053        assert_eq!(
30054            spec.politicas().timeout(),
30055            Some(POLICY_TIMEOUT_MAX),
30056            "the accessor projection must reflect the fixture's \
30057             at-cap :timeout verbatim",
30058        );
30059        assert_eq!(
30060            spec.politicas().retries(),
30061            Some(POLICY_RETRIES_MAX),
30062            "the accessor projection must reflect the fixture's \
30063             at-cap :retries verbatim",
30064        );
30065        assert!(
30066            spec.validate().is_ok(),
30067            "at-cap :timeout + :retries must pass validate under the \
30068             accessor projection — the upper-boundary accept-arm on \
30069             both axes routes through the lifted accessor",
30070        );
30071    }
30072
30073    #[test]
30074    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
30075        // The canonical per-`:placement` outer-composite-reference-shape
30076        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
30077        // typed `Placement` verbatim as a `&Placement` reference over the
30078        // same backing storage the raw `&self.placement` field access
30079        // borrows from, byte-equal across every representative fixture in
30080        // the accept-set — the default `Placement` (the substrate seed
30081        // shape whose [`PlacementStrategy::default`] evaluates to
30082        // `SingleNode` with an empty `:clusters` pool and both
30083        // optional-scalar axes `None`), and every canonical strategy /
30084        // cluster-pool / optional-scalar combination the
30085        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
30086        // three [`PlacementStrategy`] variants — `SingleNode`,
30087        // `Replicated`, `Sharded` — cross-projected with a non-empty
30088        // `:clusters` pool and, on the `Sharded` arm, a non-empty
30089        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
30090        // canonical `three_member_spec` `Replicated` fixture's
30091        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
30092        //
30093        // Pins against a future silent detour that returned a fresh-
30094        // cloned `Placement` copy (which would type-check via a `Clone`
30095        // impl but silently break every downstream caller that relied on
30096        // the reference sharing the composite's backing identity), a
30097        // reference to an operator-resolved overlay (the future per-
30098        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
30099        // acknowledges — its resolution must land at exactly this
30100        // accessor body, not silently divert the raw slot away from a
30101        // second consumer), or an axis-shuffled projection (a future
30102        // detour that swapped `clusters` and `affinity` through the
30103        // accessor would silently split the paired `validate_placement`
30104        // per-axis bracket-dispatch's traversal input from the peer
30105        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
30106        // programs.yaml distribution-annotation emitter's fan-out input
30107        // from the peer `feira app graph` per-Aplicacao print line's
30108        // input).
30109        //
30110        // Peer of the sibling M3
30111        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
30112        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
30113        // outer mesh-policy composite-reference axis, and of the sibling
30114        // slice-return `aplicacao_spec_membros_returns_membros_slice_
30115        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
30116        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
30117        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
30118        // the outer-accessor byte-equal-projection discipline onto the
30119        // outermost M3 mesh-slot type's per-Aplicacao distribution
30120        // composite-reference axis, the second `&Composite`-return
30121        // accessor on the outer [`AplicacaoSpec`] type.
30122        let fixtures: Vec<Placement> = vec![
30123            Placement::default(),
30124            Placement {
30125                estrategia: PlacementStrategy::SingleNode,
30126                clusters: vec!["rio".into()],
30127                affinity: None,
30128                shard_key: None,
30129            },
30130            Placement {
30131                estrategia: PlacementStrategy::Replicated,
30132                clusters: vec!["rio".into(), "mar".into()],
30133                affinity: None,
30134                shard_key: None,
30135            },
30136            Placement {
30137                estrategia: PlacementStrategy::Replicated,
30138                clusters: vec!["rio".into(), "mar".into()],
30139                affinity: Some("data-locality".into()),
30140                shard_key: None,
30141            },
30142            Placement {
30143                estrategia: PlacementStrategy::Sharded,
30144                clusters: vec!["rio".into(), "mar".into()],
30145                affinity: None,
30146                shard_key: Some("tenantId".into()),
30147            },
30148            Placement {
30149                estrategia: PlacementStrategy::Sharded,
30150                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
30151                affinity: Some("low-latency".into()),
30152                shard_key: Some("metadata.tenantId".into()),
30153            },
30154        ];
30155        for placement in fixtures {
30156            let s = AplicacaoSpec {
30157                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
30158                contratos: Vec::new(),
30159                politicas: MeshPolicy::default(),
30160                placement: placement.clone(),
30161                entrada: None,
30162            };
30163            assert_eq!(
30164                *s.placement(),
30165                placement,
30166                "AplicacaoSpec::placement must return :placement verbatim \
30167                 (got {:?}, expected {:?})",
30168                s.placement(),
30169                placement,
30170            );
30171            assert!(
30172                std::ptr::eq(s.placement(), &s.placement),
30173                "AplicacaoSpec::placement accessor and &self.placement \
30174                 field access must borrow the same backing storage — the \
30175                 accessor is the substrate-primitive typed dispatch every \
30176                 downstream distribution-composite consumer must route \
30177                 through, and a reference-identity split would silently \
30178                 break every consumer that relied on the borrow sharing \
30179                 the composite's storage",
30180            );
30181            assert_eq!(
30182                s.placement().estrategia(),
30183                s.placement.estrategia,
30184                "AplicacaoSpec::placement().estrategia() must byte-equal \
30185                 self.placement.estrategia — a strategy-drift would \
30186                 silently split the paired `validate_placement` \
30187                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
30188                 peer caixa-mesh programs.yaml `placement.estrategia` \
30189                 emitter's key from the peer `feira app graph` printer's \
30190                 strategy label",
30191            );
30192            assert_eq!(
30193                s.placement().clusters(),
30194                s.placement.clusters.as_slice(),
30195                "AplicacaoSpec::placement().clusters() must byte-equal \
30196                 self.placement.clusters — a cluster-pool drift would \
30197                 silently split the paired `validate_placement` \
30198                 pre-flight `.is_empty()` refusal probe's traversal from \
30199                 the peer caixa-mesh programs.yaml `placement.clusters` \
30200                 emitter's fan-out from the peer `feira app graph` \
30201                 printer's cluster list",
30202            );
30203        }
30204    }
30205
30206    #[test]
30207    fn validate_placement_reads_through_lifted_placement_accessor() {
30208        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
30209        // per-axis bracket-dispatch seed (`let p = self.placement();`,
30210        // followed by the per-axis fan-out `p.clusters()` /
30211        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
30212        // lifted axis-level accessor family) must key off the lifted
30213        // outer accessor, so any future rebrand on the typed slot's
30214        // outer-composite reader shape lands at exactly one place. Pins
30215        // the multi-axis coherence by exercising each per-axis refusal
30216        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
30217        // `:clusters` pool under the outer accessor's reference
30218        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
30219        // strategy with a `None` `:shard-key` under the same projection,
30220        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
30221        // with a `Some` `:shard-key` under the same projection, and
30222        // (4) the canonical `three_member_spec` `Replicated` fixture
30223        // passes `validate_placement` under the outer accessor's
30224        // reference projection — the accessor's reference-projection
30225        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
30226        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
30227        // without silently short-circuiting any.
30228        //
30229        // Peer of the sibling M3
30230        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
30231        // (534dc21) multi-axis coherence pin on the per-`:politicas`
30232        // outer mesh-policy composite-reference axis — extends the
30233        // multi-consumer coherence discipline onto the outermost M3
30234        // mesh-slot type's per-Aplicacao distribution composite-
30235        // reference axis, the second `&Composite`-return accessor on
30236        // the outer [`AplicacaoSpec`] type.
30237
30238        // (1) `PlacementWithoutClusters` refusal under the outer
30239        // accessor's reference projection: an empty `:clusters` pool
30240        // must trip the pre-flight refusal probe. The bracket-dispatch's
30241        // first arm reads `p.clusters()` on the reference returned by
30242        // the outer accessor.
30243        let mut spec = three_member_spec();
30244        spec.placement.clusters = Vec::new();
30245        assert_eq!(
30246            spec.validate().unwrap_err(),
30247            AplicacaoError::PlacementWithoutClusters {
30248                estrategia: PlacementStrategy::Replicated,
30249            },
30250        );
30251        assert!(
30252            std::ptr::eq(spec.placement(), &spec.placement),
30253            "the `validate_placement` per-axis bracket-dispatch's \
30254             traversal input must be the same backing composite the \
30255             accessor's reference projection borrows from",
30256        );
30257
30258        // (2) `ShardedWithoutKey` refusal under the outer accessor's
30259        // reference projection: a `Sharded` strategy with a `None`
30260        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
30261        // The bracket-dispatch's third arm reads `p.estrategia()` for
30262        // the match scrutinee then `p.shard_key()` for the cascade
30263        // scrutinee, both on the reference returned by the outer
30264        // accessor.
30265        let mut spec = three_member_spec();
30266        spec.placement.estrategia = PlacementStrategy::Sharded;
30267        spec.placement.shard_key = None;
30268        assert_eq!(
30269            spec.validate().unwrap_err(),
30270            AplicacaoError::ShardedWithoutKey,
30271        );
30272
30273        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
30274        // reference projection: a non-`Sharded` strategy with a `Some`
30275        // `:shard-key` must trip the declared-but-inert refusal. The
30276        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
30277        // + `p.estrategia()` for the diagnostic on the reference
30278        // returned by the outer accessor.
30279        let mut spec = three_member_spec();
30280        spec.placement.estrategia = PlacementStrategy::Replicated;
30281        spec.placement.shard_key = Some("tenantId".into());
30282        assert_eq!(
30283            spec.validate().unwrap_err(),
30284            AplicacaoError::ShardKeyOnNonSharded {
30285                estrategia: PlacementStrategy::Replicated,
30286                shard_key: "tenantId".into(),
30287            },
30288        );
30289
30290        // (4) Canonical `three_member_spec` `Replicated` fixture passes
30291        // `validate_placement` — every per-axis arm reaches the fall-
30292        // through `Ok(())` without any per-axis refusal firing under the
30293        // outer accessor's reference projection.
30294        let spec = three_member_spec();
30295        assert!(
30296            spec.validate().is_ok(),
30297            "the canonical Replicated placement fixture must pass \
30298             `validate_placement` — every per-axis arm short-circuits on \
30299             valid input under the outer accessor's reference projection",
30300        );
30301        assert_eq!(
30302            spec.placement().estrategia(),
30303            PlacementStrategy::Replicated,
30304            "the outer accessor's reference projection must be the \
30305             canonical Replicated fixture's strategy",
30306        );
30307        assert_eq!(
30308            spec.placement().clusters(),
30309            &["rio", "mar"],
30310            "the outer accessor's reference projection must be the \
30311             canonical Replicated fixture's cluster pool",
30312        );
30313    }
30314
30315    #[test]
30316    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
30317        // The canonical per-`:entrada` outer-composite-optional-
30318        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
30319        // the `:entrada` typed `Option<Entrada>` verbatim as an
30320        // `Option<&Entrada>` reference over the same backing storage
30321        // the raw `self.entrada.as_ref()` field access borrows from,
30322        // byte-equal across every representative fixture in the
30323        // accept-set — the author-omitted `None` shape (the
30324        // "internal-only mesh" partition every downstream external-
30325        // gateway emitter treats as "emit nothing"), the minimal
30326        // singleton `:entrada` composite (host + destination + empty
30327        // paths + default port), the paths-carrying composite (the
30328        // canonical `three_member_spec` fixture's ["/api" "/health"]
30329        // path-list shape every HTTPRoute per-rule fan-out emitter
30330        // reads), and the non-default port composite (the canonical
30331        // custom-port shape the port-fallback resolver reads).
30332        //
30333        // Pins against a future silent detour that returned a fresh-
30334        // cloned `Entrada` copy (which would type-check via a `Clone`
30335        // impl but silently break every downstream caller that
30336        // relied on the reference sharing the composite's backing
30337        // identity), a reference to an operator-resolved overlay
30338        // (the future per-cluster `:entrada-overrides` slot the
30339        // MESH-COMPOSITION §V federation roadmap acknowledges — its
30340        // resolution must land at exactly this accessor body, not
30341        // silently divert the raw slot away from a second consumer),
30342        // a `None` → `Some(Entrada::default)` cluster-default
30343        // projection (which would collapse the load-bearing
30344        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
30345        // the peer `gateway_routes` early-return + `feira app graph`
30346        // internal-only-mesh partition both read), or an axis-
30347        // shuffled projection (a future detour that swapped
30348        // `host` and `para` through the accessor would silently
30349        // split the paired `validate` per-`:entrada` shape-and-
30350        // membership gate's traversal input from the peer
30351        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
30352        // fan-out input from the peer `feira app graph` external-
30353        // gateway summary line).
30354        //
30355        // Peer of the sibling M3
30356        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
30357        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
30358        // `:politicas` outer mesh-policy composite-reference axis
30359        // and of the sibling M3
30360        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
30361        // (9abb8f0) `&Placement` byte-equal pin on the per-
30362        // `:placement` outer distribution-composite composite-
30363        // reference axis — extends the outer-accessor byte-equal-
30364        // projection discipline onto the last unlifted outermost M3
30365        // mesh-slot type's per-Aplicacao external-gateway composite-
30366        // reference axis, the third and final `&Composite`-return
30367        // accessor on the outer [`AplicacaoSpec`] type.
30368        let fixtures: Vec<Option<Entrada>> = vec![
30369            None,
30370            Some(Entrada {
30371                host: "checkout.quero.cloud".into(),
30372                para: "cart".into(),
30373                paths: Vec::new(),
30374                port: DEFAULT_SERVICO_PORT,
30375            }),
30376            Some(Entrada {
30377                host: "checkout.quero.cloud".into(),
30378                para: "cart".into(),
30379                paths: vec!["/api".into(), "/health".into()],
30380                port: DEFAULT_SERVICO_PORT,
30381            }),
30382            Some(Entrada {
30383                host: "checkout.quero.cloud".into(),
30384                para: "cart".into(),
30385                paths: vec!["/api".into()],
30386                port: 9443,
30387            }),
30388        ];
30389        for entrada in fixtures {
30390            let s = AplicacaoSpec {
30391                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
30392                contratos: Vec::new(),
30393                politicas: MeshPolicy::default(),
30394                placement: Placement::default(),
30395                entrada: entrada.clone(),
30396            };
30397            assert_eq!(
30398                s.entrada(),
30399                entrada.as_ref(),
30400                "AplicacaoSpec::entrada must return :entrada verbatim \
30401                 (got {:?}, expected {:?})",
30402                s.entrada(),
30403                entrada.as_ref(),
30404            );
30405            match (s.entrada(), s.entrada.as_ref()) {
30406                (Some(a), Some(b)) => assert!(
30407                    std::ptr::eq(a, b),
30408                    "AplicacaoSpec::entrada accessor and \
30409                     self.entrada.as_ref() field access must borrow \
30410                     the same backing storage — the accessor is the \
30411                     substrate-primitive typed dispatch every \
30412                     downstream external-gateway composite consumer \
30413                     must route through, and a reference-identity \
30414                     split would silently break every consumer that \
30415                     relied on the borrow sharing the composite's \
30416                     storage",
30417                ),
30418                (None, None) => {}
30419                _ => panic!(
30420                    "AplicacaoSpec::entrada presence bit must byte-\
30421                     equal self.entrada.is_some() — a presence-bit \
30422                     drift would silently split the paired `validate` \
30423                     per-`:entrada` shape-and-membership gate's \
30424                     traversal head from the peer \
30425                     caixa-mesh gateway_routes early-return partition \
30426                     from the peer `feira app graph` internal-only-\
30427                     mesh partition",
30428                ),
30429            }
30430            assert_eq!(
30431                s.entrada().is_some(),
30432                s.entrada.is_some(),
30433                "AplicacaoSpec::entrada().is_some() must byte-equal \
30434                 self.entrada.is_some() — a presence-bit drift would \
30435                 silently split every downstream `Option<&Entrada>` \
30436                 consumer's partition on the internal-only-mesh arm",
30437            );
30438        }
30439    }
30440
30441    #[test]
30442    fn validate_reads_through_lifted_entrada_accessor() {
30443        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
30444        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
30445        // self.entrada() { … }`, followed by the per-axis fan-out
30446        // `validate_entrada_para(&e.para)` /
30447        // `EntradaMemberMissing` membership lookup /
30448        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
30449        // per-`e.paths` `validate_entrada_path` traversal) must key
30450        // off the lifted outer accessor, so any future rebrand on
30451        // the typed slot's outer-composite reader shape lands at
30452        // exactly one place. Pins the multi-axis coherence by
30453        // exercising each per-axis refusal end-to-end: (1) the
30454        // author-omitted `None` shape short-circuits past every
30455        // per-`:entrada` refusal (the internal-only mesh partition
30456        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
30457        // fires on a well-shaped but phantom `:para` under the outer
30458        // accessor's reference projection, and (3) the canonical
30459        // `three_member_spec` `:entrada` fixture passes `validate`
30460        // under the outer accessor's reference projection.
30461        //
30462        // Peer of the sibling M3
30463        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
30464        // (534dc21) multi-axis coherence pin on the per-`:politicas`
30465        // outer mesh-policy composite-reference axis and the sibling
30466        // M3
30467        // [`validate_placement_reads_through_lifted_placement_accessor`]
30468        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
30469        // outer distribution-composite composite-reference axis —
30470        // extends the multi-consumer coherence discipline onto the
30471        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
30472        // external-gateway composite-reference axis, the third and
30473        // final `&Composite`-return accessor on the outer
30474        // [`AplicacaoSpec`] type.
30475
30476        // (1) `None` :entrada — the internal-only-mesh partition
30477        // short-circuits past every per-`:entrada` refusal. The outer
30478        // accessor's reference projection reaches the fall-through
30479        // `Ok(())` on the `None` arm without any per-axis refusal
30480        // firing.
30481        let mut spec = three_member_spec();
30482        spec.entrada = None;
30483        assert!(
30484            spec.validate().is_ok(),
30485            "an author-omitted `:entrada` must pass `validate` — the \
30486             internal-only-mesh partition short-circuits past every \
30487             per-`:entrada` refusal under the outer accessor's \
30488             reference projection",
30489        );
30490        assert!(
30491            spec.entrada().is_none(),
30492            "the outer accessor's reference projection must name the \
30493             internal-only-mesh partition per the `None` fixture",
30494        );
30495
30496        // (2) `EntradaMemberMissing` refusal under the outer accessor's
30497        // reference projection: a well-shaped but phantom `:para` must
30498        // trip the membership-lookup refusal. The gate's second arm
30499        // reads `e.para` on the reference returned by the outer
30500        // accessor.
30501        let mut spec = three_member_spec();
30502        if let Some(e) = spec.entrada.as_mut() {
30503            e.para = "phantom".into();
30504        }
30505        assert_eq!(
30506            spec.validate().unwrap_err(),
30507            AplicacaoError::EntradaMemberMissing {
30508                para: "phantom".into(),
30509            },
30510        );
30511        match (spec.entrada(), spec.entrada.as_ref()) {
30512            (Some(a), Some(b)) => assert!(
30513                std::ptr::eq(a, b),
30514                "the `validate` per-`:entrada` gate's traversal head \
30515                 must be the same backing composite the accessor's \
30516                 reference projection borrows from",
30517            ),
30518            _ => panic!("fixture must carry Some(:entrada)"),
30519        }
30520
30521        // (3) Canonical `three_member_spec` `:entrada` fixture passes
30522        // `validate` — every per-axis arm reaches the fall-through
30523        // `Ok(())` without any per-axis refusal firing under the
30524        // outer accessor's reference projection.
30525        let spec = three_member_spec();
30526        assert!(
30527            spec.validate().is_ok(),
30528            "the canonical `:entrada` fixture must pass `validate` — \
30529             every per-axis arm short-circuits on valid input under \
30530             the outer accessor's reference projection",
30531        );
30532        assert!(
30533            spec.entrada().is_some(),
30534            "the outer accessor's reference projection must be the \
30535             canonical `:entrada` fixture's composite",
30536        );
30537    }
30538
30539    #[test]
30540    fn membro_names_matches_inline_membros_projection() {
30541        // Substrate-primitive ≡ inline-projection pin on
30542        // [`AplicacaoSpec::membro_names`]: the lifted membership oracle
30543        // must be byte-for-byte the set the pre-lift inline
30544        // `self.membros().iter().map(Membro::nome).collect()` builder
30545        // produced, on every membership shape the three
30546        // Servico-name-*reference* axes (`:contratos :de`, `:contratos
30547        // :para`, `:entrada :para`) resolve against. Pins the
30548        // projection so a future rebrand of the node-identity axis
30549        // lands at the primitive rather than diverging between the
30550        // per-`:contratos` membership arms still inline at `validate`
30551        // and the lifted `validate_entrada` gate.
30552        for membros in [
30553            vec![],
30554            vec![membro("cart", "^0.1")],
30555            vec![
30556                membro("catalog", "^0.1"),
30557                membro("cart", "^0.1"),
30558                membro("payment", "^0.2"),
30559            ],
30560        ] {
30561            let mut spec = three_member_spec();
30562            spec.membros = membros;
30563            let inline: std::collections::HashSet<&str> =
30564                spec.membros().iter().map(Membro::nome).collect();
30565            assert_eq!(
30566                spec.membro_names(),
30567                inline,
30568                "the lifted membership oracle must discriminate the \
30569                 same node set as the pre-lift inline projection",
30570            );
30571        }
30572    }
30573
30574    #[test]
30575    fn validate_entrada_matches_gate_on_every_per_axis_shape() {
30576        // Per-slot-gate ≡ validate equivalence pin on the lifted
30577        // [`AplicacaoSpec::validate_entrada`]: the named per-slot gate
30578        // must discriminate the same set as [`AplicacaoSpec::validate`]
30579        // on every `:entrada`-covered input, so a future consumer that
30580        // re-validates the one slot (the M4 admission webhook
30581        // re-checking `:entrada` after a gateway-host patch) accepts
30582        // exactly what `feira build` accepts and surfaces the same
30583        // diagnostic on the same input. Covers each of the five gated
30584        // axes plus the two clean-pass shapes (`None` — the
30585        // internal-only-mesh partition — and the canonical fixture).
30586        //
30587        // Peer of the sibling per-slot equivalence pins
30588        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
30589        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
30590        // `:politicas` slot's compound entry gate, extended here onto
30591        // the `:entrada` slot's newly-named per-slot gate.
30592        /// One `:entrada` equivalence case: a label, the per-axis
30593        /// mutation applied to the canonical fixture's composite, and
30594        /// the diagnostic both the per-slot gate and `validate` must
30595        /// surface on it (`None` = clean pass).
30596        type EntradaCase = (&'static str, fn(&mut Entrada), Option<AplicacaoError>);
30597
30598        let cases: &[EntradaCase] = &[
30599            (
30600                ":para shape — empty",
30601                |e| e.para = String::new(),
30602                Some(AplicacaoError::EntradaParaEmpty),
30603            ),
30604            (
30605                ":para membership — well-shaped phantom",
30606                |e| e.para = "phantom".into(),
30607                Some(AplicacaoError::EntradaMemberMissing {
30608                    para: "phantom".into(),
30609                }),
30610            ),
30611            (
30612                ":host emptiness",
30613                |e| e.host = String::new(),
30614                Some(AplicacaoError::EmptyEntradaHost),
30615            ),
30616            (
30617                ":port structural floor",
30618                |e| e.port = 0,
30619                Some(AplicacaoError::EntradaPortZero),
30620            ),
30621            (
30622                ":paths per-entry emptiness",
30623                |e| e.paths = vec![String::new()],
30624                Some(AplicacaoError::EntradaPathEmpty),
30625            ),
30626            (
30627                ":paths leading-slash grammar",
30628                |e| e.paths = vec!["api/cart".into()],
30629                Some(AplicacaoError::EntradaPathNotAbsolute {
30630                    path: "api/cart".into(),
30631                }),
30632            ),
30633            (
30634                ":paths set-not-multiset",
30635                |e| e.paths = vec!["/api/cart".into(), "/api/cart".into()],
30636                Some(AplicacaoError::EntradaPathDuplicate {
30637                    path: "/api/cart".into(),
30638                }),
30639            ),
30640            ("clean pass — canonical fixture", |_| {}, None),
30641        ];
30642        for (label, mutate, expected) in cases {
30643            let mut spec = three_member_spec();
30644            mutate(spec.entrada.as_mut().expect("fixture carries :entrada"));
30645            assert_eq!(
30646                spec.validate_entrada().err(),
30647                *expected,
30648                "per-slot gate disagreed with the expected diagnostic on {label}",
30649            );
30650            assert_eq!(
30651                spec.validate().err(),
30652                *expected,
30653                "`validate` disagreed with the per-slot gate on {label}",
30654            );
30655        }
30656
30657        // The `None` arm is the internal-only-mesh partition: a clean
30658        // pass through both the per-slot gate and `validate`, not a
30659        // refusal.
30660        let mut spec = three_member_spec();
30661        spec.entrada = None;
30662        assert_eq!(spec.validate_entrada().err(), None);
30663        assert_eq!(spec.validate().err(), None);
30664    }
30665
30666    #[test]
30667    fn validate_entrada_resolves_membership_through_own_oracle() {
30668        // Self-containment pin on the lifted per-slot gate:
30669        // [`AplicacaoSpec::validate_entrada`] resolves `:entrada :para`
30670        // against the oracle *it* builds through
30671        // [`AplicacaoSpec::membro_names`], not one threaded down from
30672        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
30673        // longer contains the `:entrada :para` target must trip
30674        // `EntradaMemberMissing` when the per-slot gate is called
30675        // directly — the shape a future single-slot re-validator
30676        // (the M4 admission webhook) reaches the axis through, without
30677        // re-walking `:membros` / `:contratos` / the sync-cycle
30678        // detector first. Same self-contained posture
30679        // [`AplicacaoSpec::detect_sync_cycles`] already carries for
30680        // the M4 per-edge policy resolver.
30681        let mut spec = three_member_spec();
30682        spec.membros.retain(|m| m.nome() != "cart");
30683        assert_eq!(
30684            spec.validate_entrada().unwrap_err(),
30685            AplicacaoError::EntradaMemberMissing {
30686                para: "cart".into(),
30687            },
30688            "the per-slot gate must resolve `:para` against the oracle \
30689             it builds itself, with no membership set threaded in",
30690        );
30691        assert!(
30692            !spec.membro_names().contains("cart"),
30693            "fixture must have dropped the `:entrada :para` target \
30694             from the graph's node set",
30695        );
30696    }
30697
30698    #[test]
30699    fn validate_contratos_matches_gate_on_every_per_axis_shape() {
30700        // Per-slot-gate ≡ validate equivalence pin on the lifted
30701        // [`AplicacaoSpec::validate_contratos`]: the named per-slot
30702        // gate must discriminate the same set as
30703        // [`AplicacaoSpec::validate`] on every `:contratos`-covered
30704        // input, so a future consumer that re-validates the one slot
30705        // (the M4 admission webhook re-checking `:contratos` after a
30706        // per-`(:de, :para)` edge patch, the per-`:contratos`-edge
30707        // `:politicas` override MESH-COMPOSITION §III.2 #3
30708        // acknowledges — which resolves an effective per-edge
30709        // [`MeshPolicy`] and must re-check the edge's identity closure
30710        // before it can key a per-edge override off the endpoint
30711        // tuple) accepts exactly what `feira build` accepts and
30712        // surfaces the same diagnostic on the same input. Covers each
30713        // of the six gated axes (`:de`/`:para` per-arm shape,
30714        // per-arm graph-membership, structural self-loop, `:wit`
30715        // emptiness) plus the clean-pass canonical fixture; the
30716        // reason-carrying arms (`ContratoCaixaInvalid` on `:de`/`:para`
30717        // shape, `ContratoWitInvalid` on WIT-shape ↔ target dispatch,
30718        // `ContratoDuplicate` on whole-edge dedup) whose `reason:` /
30719        // `target:` carriers depend on library implementation
30720        // details are pinned separately below with a `matches!`
30721        // predicate on the arm identity plus the mirror equivalence
30722        // between the two entry points.
30723        //
30724        // Peer of the sibling per-slot equivalence pins
30725        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
30726        // / `_on_cross_axis_and_clean_pass_shapes` (f03a154) on the
30727        // `:politicas` slot's compound entry gate, and
30728        // `validate_entrada_matches_gate_on_every_per_axis_shape`
30729        // (20cd523) on the `:entrada` slot's per-slot gate — extended
30730        // here onto the `:contratos` slot's newly-named per-slot gate,
30731        // closing the last unlifted per-slot gate on the M3 mesh-slot
30732        // family.
30733        /// One `:contratos` equivalence case: a label, the per-axis
30734        /// mutation applied to the canonical fixture's spec, and the
30735        /// diagnostic both the per-slot gate and `validate` must
30736        /// surface on it (`None` = clean pass).
30737        type ContratoCase = (&'static str, fn(&mut AplicacaoSpec), Option<AplicacaoError>);
30738
30739        let cases: &[ContratoCase] = &[
30740            (
30741                ":de shape — empty",
30742                |s| s.contratos[0].de = String::new(),
30743                Some(AplicacaoError::ContratoCaixaEmpty {
30744                    slot: crate::render::CONTRATO_AUTHOR_KEY_DE,
30745                }),
30746            ),
30747            (
30748                ":para shape — empty",
30749                |s| s.contratos[0].para = String::new(),
30750                Some(AplicacaoError::ContratoCaixaEmpty {
30751                    slot: crate::render::CONTRATO_AUTHOR_KEY_PARA,
30752                }),
30753            ),
30754            (
30755                ":de membership — well-shaped phantom",
30756                |s| s.contratos[0].de = "phantom".into(),
30757                Some(AplicacaoError::ContratoMemberMissing {
30758                    caixa: "phantom".into(),
30759                }),
30760            ),
30761            (
30762                ":para membership — well-shaped phantom",
30763                |s| s.contratos[0].para = "phantom".into(),
30764                Some(AplicacaoError::ContratoMemberMissing {
30765                    caixa: "phantom".into(),
30766                }),
30767            ),
30768            (
30769                "structural self-loop",
30770                |s| s.contratos[0].para = "cart".into(),
30771                Some(AplicacaoError::ContratoSelfLoop {
30772                    caixa: "cart".into(),
30773                    wit: "wasi:http/proxy".into(),
30774                }),
30775            ),
30776            (
30777                ":wit emptiness",
30778                |s| s.contratos[0].wit = String::new(),
30779                Some(AplicacaoError::EmptyWit {
30780                    de: "cart".into(),
30781                    para: "catalog".into(),
30782                }),
30783            ),
30784            ("clean pass — canonical fixture", |_| {}, None),
30785        ];
30786        for (label, mutate, expected) in cases {
30787            let mut spec = three_member_spec();
30788            mutate(&mut spec);
30789            assert_eq!(
30790                spec.validate_contratos().err(),
30791                *expected,
30792                "per-slot gate disagreed with the expected diagnostic on {label}",
30793            );
30794            assert_eq!(
30795                spec.validate().err(),
30796                *expected,
30797                "`validate` disagreed with the per-slot gate on {label}",
30798            );
30799        }
30800    }
30801
30802    #[test]
30803    fn validate_contratos_matches_gate_on_reason_carrying_arms() {
30804        // Companion pin to
30805        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]:
30806        // the per-slot gate ≡ `validate` equivalence on the three
30807        // `:contratos` refusal arms whose diagnostic carries a
30808        // library-owned string ([`AplicacaoError::ContratoCaixaInvalid`]
30809        // and [`AplicacaoError::ContratoWrongTarget`] via the paired
30810        // `is_dns_1123_label` / `WitContract::target` shape helpers,
30811        // and [`AplicacaoError::ContratoDuplicate`] via [`WitTarget::label`]'s
30812        // library-formatted `target:` scalar). Value equality between
30813        // the per-slot gate and `validate` outputs pins the full
30814        // `Option<AplicacaoError>` (including reason-strings), and the
30815        // per-arm `matches!` predicate pins the arm-discriminator
30816        // identity on the specific `Contrato*` variant. Split from
30817        // the primary equivalence pin so each pin body stays under
30818        // [`clippy::too_many_lines`], the same shape the peer
30819        // `validate_matches_gate_on_per_axis_and_phase_boundary_shapes`
30820        // / `_on_cross_axis_and_clean_pass_shapes` split (f03a154)
30821        // carries on the `:politicas` slot's compound entry gate.
30822        type ContratoReasonCase = (
30823            &'static str,
30824            fn(&mut AplicacaoSpec),
30825            fn(&AplicacaoError) -> bool,
30826        );
30827        let cases: &[ContratoReasonCase] = &[
30828            (
30829                ":de shape — DNS-1123 invalid",
30830                |s| s.contratos[0].de = "Cart".into(),
30831                |err| {
30832                    matches!(
30833                        err,
30834                        AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. }
30835                            if *slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
30836                    )
30837                },
30838            ),
30839            (
30840                ":wit target-shape mismatch — payload on capability arm",
30841                |s| s.contratos[0].wit = "wasi:junk/nope".into(),
30842                |err| {
30843                    matches!(
30844                        err,
30845                        AplicacaoError::ContratoWrongTarget { de, para, wit, .. }
30846                            if de == "cart" && para == "catalog" && wit == "wasi:junk/nope"
30847                    )
30848                },
30849            ),
30850            (
30851                "whole-edge dedup — six-axis identity collision",
30852                |s| {
30853                    let dup = s.contratos[0].clone();
30854                    s.contratos.push(dup);
30855                },
30856                |err| {
30857                    matches!(
30858                        err,
30859                        AplicacaoError::ContratoDuplicate { de, para, wit, .. }
30860                            if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
30861                    )
30862                },
30863            ),
30864        ];
30865        for (label, mutate, arm_matches) in cases {
30866            let mut spec = three_member_spec();
30867            mutate(&mut spec);
30868            let per_slot = spec.validate_contratos().err();
30869            let gate = spec.validate().err();
30870            assert_eq!(
30871                per_slot, gate,
30872                "per-slot gate and `validate` must return byte-equal \
30873                 `Option<AplicacaoError>` on {label} (including \
30874                 library-owned reason strings)",
30875            );
30876            let err = per_slot
30877                .as_ref()
30878                .unwrap_or_else(|| panic!("expected refusal on {label}, got clean pass"));
30879            assert!(
30880                arm_matches(err),
30881                "per-slot gate surfaced the wrong arm on {label}: got {err:?}",
30882            );
30883        }
30884    }
30885
30886    #[test]
30887    fn validate_contratos_resolves_membership_through_own_oracle() {
30888        // Self-containment pin on the lifted per-slot gate:
30889        // [`AplicacaoSpec::validate_contratos`] resolves each edge's
30890        // `:de` / `:para` against the oracle *it* builds through
30891        // [`AplicacaoSpec::membro_names`], not one threaded down from
30892        // [`AplicacaoSpec::validate`]. A spec whose `:membros` no
30893        // longer contains a `:contratos` edge's endpoint must trip
30894        // `ContratoMemberMissing` when the per-slot gate is called
30895        // directly — the shape a future single-slot re-validator
30896        // (the M4 admission webhook re-checking `:contratos` after a
30897        // per-`(:de, :para)` edge patch, the M4 per-edge policy
30898        // resolver on the `:politicas` override axis) reaches the
30899        // axis through, without re-walking `:membros` / `:entrada` /
30900        // `:placement` / `:politicas` first. Same self-contained
30901        // posture the peer per-slot gates
30902        // [`AplicacaoSpec::detect_sync_cycles`] and
30903        // [`AplicacaoSpec::validate_entrada`] already carry for the
30904        // same M4 consumers.
30905        let mut spec = three_member_spec();
30906        spec.membros.retain(|m| m.nome() != "catalog");
30907        assert_eq!(
30908            spec.validate_contratos().unwrap_err(),
30909            AplicacaoError::ContratoMemberMissing {
30910                caixa: "catalog".into(),
30911            },
30912            "the per-slot gate must resolve `:de` / `:para` against \
30913             the oracle it builds itself, with no membership set \
30914             threaded in",
30915        );
30916        assert!(
30917            !spec.membro_names().contains("catalog"),
30918            "fixture must have dropped the `:contratos` edge's \
30919             `:para` target from the graph's node set",
30920        );
30921    }
30922
30923    #[test]
30924    fn validate_contratos_folds_cycle_axis_matches_gate() {
30925        // Fold-into-per-slot-gate equivalence pin on the
30926        // cross-edge cycle axis: an [`AplicacaoError::ContratoCycle`]
30927        // surfaces byte-equal through both
30928        // [`AplicacaoSpec::validate_contratos`] and
30929        // [`AplicacaoSpec::validate`] on a fixture whose only defect is
30930        // a synchronous-edge cycle in `:contratos`. Pins the fold that
30931        // moved the cross-edge cycle axis onto the per-slot gate — a
30932        // future silent regression that de-folded the axis back to the
30933        // outer [`AplicacaoSpec::validate`] dispatch (a rebase artifact,
30934        // a peer per-slot gate lift that skipped the cross-axis half of
30935        // the [`MeshPolicy::validate`]-analogous discipline) would
30936        // surface here as `Some(ContratoCycle)` from `validate` and
30937        // `None` from `validate_contratos`.
30938        //
30939        // Cycle fixture is the same shape as the peer
30940        // [`rejects_three_node_synchronous_cycle`] test carries: a
30941        // clean 3-cycle over the HTTP subgraph (catalog → cart →
30942        // payment → catalog), so the per-entry cascade (shape +
30943        // membership + self-loop + `:wit` emptiness + WIT-target +
30944        // whole-edge dedup) passes cleanly and the sole surviving
30945        // refusal shape is the cross-edge cycle axis. The `cycle`
30946        // vector is normalized to a sorted body set for the equality
30947        // compare (the traversal path's starting node depends on
30948        // BTreeMap iteration order, which is deterministic but is not
30949        // the load-bearing property this pin covers).
30950        //
30951        // Peer of the sibling per-slot ≡ `validate` equivalence pins
30952        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
30953        // (per-entry axes) and
30954        // [`validate_contratos_matches_gate_on_reason_carrying_arms`]
30955        // (parser-owned reason arms) already carry on the six
30956        // per-entry axes — this extends the discipline onto the
30957        // cross-edge cycle axis newly folded into the per-slot gate,
30958        // matching the peer per-slot compound gate
30959        // [`AplicacaoSpec::validate_politicas`] (f03a154) which folded
30960        // both per-axis and cross-axis surfaces on `:politicas`.
30961        let mut spec = three_member_spec();
30962        spec.contratos = vec![
30963            contract_http("catalog", "cart", "/x"),
30964            contract_http("cart", "payment", "/y"),
30965            contract_http("payment", "catalog", "/z"),
30966        ];
30967        let per_slot_err = spec.validate_contratos().unwrap_err();
30968        let gate_err = spec.validate().unwrap_err();
30969        assert_eq!(
30970            per_slot_err, gate_err,
30971            "the per-slot gate and `validate` must return byte-equal \
30972             `AplicacaoError::ContratoCycle` on a cycle-only fixture \
30973             — the fold pins the cross-edge axis onto the per-slot \
30974             gate the same way the peer `validate_politicas` fold \
30975             pinned the `:politicas` cross-axis surface",
30976        );
30977        match per_slot_err {
30978            AplicacaoError::ContratoCycle { ref cycle } => {
30979                assert_eq!(
30980                    cycle.first(),
30981                    cycle.last(),
30982                    "cycle traversal must close on the back-edge \
30983                     target — the diagnostic shape the peer \
30984                     `rejects_three_node_synchronous_cycle` pins",
30985                );
30986                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
30987                assert_eq!(body.len(), 3, "3-cycle must visit 3 distinct nodes");
30988                assert!(body.contains("cart"));
30989                assert!(body.contains("catalog"));
30990                assert!(body.contains("payment"));
30991            }
30992            other => panic!("expected ContratoCycle, got {other:?}"),
30993        }
30994    }
30995
30996    #[test]
30997    fn validate_contratos_per_entry_arm_fires_before_cycle_arm() {
30998        // Diagnostic-ordering pin on the fold: a `:contratos` fixture
30999        // carrying *both* a per-entry defect (a self-loop, the
31000        // structural-self-edge arm on the per-entry cascade — chosen
31001        // because it never masks or is masked by the cycle diagnostic
31002        // on the peer arms) *and* a would-be synchronous-edge cycle in
31003        // the remaining edges must surface the per-entry diagnostic
31004        // first through both [`AplicacaoSpec::validate_contratos`] and
31005        // [`AplicacaoSpec::validate`] — pinning the fold's canonical
31006        // per-entry-before-cross-edge dispatch ordering, byte-equal to
31007        // the pre-fold `validate`-side sequence
31008        // (`validate_contratos()? → detect_sync_cycles()?`) the
31009        // dispatch encoded verbatim. A silent regression that reversed
31010        // the ordering inside the fold would surface here as a cycle
31011        // diagnostic on a fixture carrying an earlier per-entry defect
31012        // — masking the narrower "this edge is degenerate" arm behind
31013        // the coarser "this graph deadlocks" arm.
31014        //
31015        // Peer of the diagnostic-ordering property the pre-fold
31016        // dispatch encoded at the [`AplicacaoSpec::validate`]
31017        // altitude (`validate_contratos()? → detect_sync_cycles()?`),
31018        // now enforced inside the per-slot gate's own body, so a future
31019        // consumer that reaches only the per-slot gate (the M4
31020        // admission webhook re-checking `:contratos` after a per-edge
31021        // patch) inherits the ordering property by construction.
31022        let mut spec = three_member_spec();
31023        // The three-member fixture already has cart → catalog and
31024        // cart → payment; adding catalog → cart closes a 2-cycle on
31025        // the HTTP subgraph.
31026        spec.contratos
31027            .push(contract_http("catalog", "cart", "/refresh"));
31028        // Add a self-loop on `payment` — the per-entry structural-
31029        // self-edge arm — which must surface first.
31030        spec.contratos
31031            .push(contract_http("payment", "payment", "/loop"));
31032        let per_slot_err = spec.validate_contratos().unwrap_err();
31033        let gate_err = spec.validate().unwrap_err();
31034        assert_eq!(
31035            per_slot_err, gate_err,
31036            "per-slot gate and `validate` must agree on the ordering \
31037             fixture's surfaced diagnostic — a divergence here means \
31038             the fold reshaped one dispatch's ordering without the \
31039             other",
31040        );
31041        assert!(
31042            matches!(
31043                per_slot_err,
31044                AplicacaoError::ContratoSelfLoop { ref caixa, .. }
31045                    if caixa == "payment"
31046            ),
31047            "the per-entry structural-self-edge arm must fire before \
31048             the cross-edge cycle arm — pinning the fold's per-entry-\
31049             before-cross-edge dispatch ordering byte-equal to the \
31050             pre-fold `validate_contratos()? → detect_sync_cycles()?` \
31051             sequence; got {per_slot_err:?}",
31052        );
31053    }
31054
31055    #[test]
31056    fn validate_contratos_cycle_axis_is_self_contained_on_slot() {
31057        // Self-containment pin on the folded cross-edge cycle axis:
31058        // [`AplicacaoSpec::validate_contratos`] surfaces
31059        // [`AplicacaoError::ContratoCycle`] directly against `&self`
31060        // without depending on the peer per-slot gates
31061        // ([`AplicacaoSpec::validate_membros`],
31062        // [`AplicacaoSpec::validate_entrada`],
31063        // [`AplicacaoSpec::validate_placement`],
31064        // [`AplicacaoSpec::validate_politicas`]) running first — the
31065        // shape a future single-slot re-validator (the M4 admission
31066        // webhook re-checking `:contratos` after a per-`(:de, :para)`
31067        // edge patch, the per-edge policy resolver MESH-COMPOSITION
31068        // §III.2 #3 acknowledges) reaches *both* structural axes on
31069        // the slot through one call. A spec with a per-`:politicas`
31070        // refusal shape (zero `:timeout`, the first per-axis arm the
31071        // peer [`MeshPolicy::validate`] gate covers) AND a
31072        // synchronous-edge cycle in `:contratos` must:
31073        //
31074        //   - surface [`AplicacaoError::ContratoCycle`] through the
31075        //     per-slot gate `validate_contratos` directly (proves the
31076        //     cycle axis reaches the per-slot altitude without the
31077        //     peer `:politicas` gate running first);
31078        //   - surface [`AplicacaoError::ContratoCycle`] through
31079        //     `validate` (which reaches `validate_contratos` before
31080        //     `validate_politicas` per the fixed dispatch order), so
31081        //     the fold's cross-slot ordering (`:membros` →
31082        //     `:contratos` → `:entrada` → `:placement` → `:politicas`)
31083        //     is byte-equal to the pre-fold dispatch's ordering.
31084        //
31085        // Same self-contained-on-`&self` posture the peer per-slot
31086        // gates [`AplicacaoSpec::validate_entrada`] (20cd523),
31087        // [`AplicacaoSpec::validate_contratos`] per-entry axis
31088        // (906a5c6), and [`AplicacaoSpec::validate_politicas`]
31089        // (f03a154) already carry — extended here onto the newly-
31090        // folded cross-edge cycle axis. Peer of the sibling per-slot
31091        // self-containment pins
31092        // `validate_entrada_resolves_membership_through_own_oracle`
31093        // and `validate_contratos_resolves_membership_through_own_oracle`
31094        // on the per-entry membership axis — extends the discipline
31095        // onto the cross-edge cycle axis of the same per-slot gate.
31096        let mut spec = three_member_spec();
31097        // Poison `:politicas` — zero-`:timeout` trips the first per-
31098        // axis arm the [`MeshPolicy::validate`] gate covers, so any
31099        // dispatch that reached `:politicas` would surface a
31100        // `:politicas` diagnostic instead of `ContratoCycle`.
31101        spec.politicas.timeout = Some(Duration::from_secs(0));
31102        // Close a synchronous-edge cycle on the HTTP subgraph.
31103        spec.contratos
31104            .push(contract_http("catalog", "cart", "/refresh"));
31105        let per_slot_err = spec.validate_contratos().unwrap_err();
31106        assert!(
31107            matches!(per_slot_err, AplicacaoError::ContratoCycle { .. }),
31108            "the per-slot gate must surface `ContratoCycle` directly \
31109             against `&self` — a peer per-slot gate's regression \
31110             would surface a non-`ContratoCycle` diagnostic here; \
31111             got {per_slot_err:?}",
31112        );
31113        let gate_err = spec.validate().unwrap_err();
31114        assert!(
31115            matches!(gate_err, AplicacaoError::ContratoCycle { .. }),
31116            "`validate`'s five-slot dispatch must reach the fold's \
31117             cross-edge cycle axis on `:contratos` before the peer \
31118             `:politicas` gate — a dispatch-order regression would \
31119             surface a `:politicas` diagnostic here; got {gate_err:?}",
31120        );
31121        // Sanity: the poisoned `:politicas` alone would trip
31122        // [`MeshPolicy::validate`] under the peer per-slot gate, so
31123        // the cycle-first surfacing above is a real ordering property,
31124        // not a case where the `:politicas` axis silently accepts the
31125        // fixture.
31126        let mut politicas_only = three_member_spec();
31127        politicas_only.politicas.timeout = Some(Duration::from_secs(0));
31128        assert!(
31129            politicas_only.validate_politicas().is_err(),
31130            "the poisoned `:politicas` fixture must trip the peer \
31131             per-slot gate on its own — otherwise the self-contained \
31132             cycle-first surfacing above would not be an ordering \
31133             property",
31134        );
31135    }
31136
31137    #[test]
31138    fn wit_contract_require_endpoints_in_folds_per_arm_membership_cascade() {
31139        // Fail-before-pass-after equivalence pin on the lifted
31140        // per-edge substrate primitive [`WitContract::require_endpoints_in`]:
31141        // both arms (`:de` phantom and `:para` phantom) must fire the
31142        // `AplicacaoError::ContratoMemberMissing` diagnostic with a
31143        // `caixa` carrier byte-equal to the offending accessor's
31144        // projection, and `:de` must fire before `:para` when both
31145        // arms would trip on the same call — preserving the canonical
31146        // edge-direction order the peer per-arm shape gate
31147        // [`validate_contrato_caixa`], the [`WitContract::is_self_loop`]
31148        // diagnostic, and every peer per-arm ordering in
31149        // [`AplicacaoSpec::validate_contratos`] already carry.
31150        //
31151        // Two-endpoint oracle covers exactly enough graph nodes to
31152        // exercise each arm in isolation: the `:de` arm fires when
31153        // the source is off-oracle and the destination is on-oracle,
31154        // the `:para` arm fires when the source is on-oracle and the
31155        // destination is off-oracle, and the `:de`-before-`:para`
31156        // ordering falls out from a probe where *both* endpoints are
31157        // off-oracle — the diagnostic's `caixa` field must byte-equal
31158        // the source, not the destination, pinning the primitive's
31159        // arm ordering as `:de` first.
31160        let mut names: std::collections::HashSet<&str> = std::collections::HashSet::new();
31161        names.insert("cart");
31162        names.insert("catalog");
31163
31164        // `:de` phantom, `:para` on-oracle
31165        let de_phantom = contract_http("phantom-de", "catalog", "/x");
31166        let err = de_phantom.require_endpoints_in(&names).unwrap_err();
31167        assert_eq!(
31168            err,
31169            AplicacaoError::ContratoMemberMissing {
31170                caixa: de_phantom.source().to_string(),
31171            },
31172            "the `:de` phantom arm must fire ContratoMemberMissing \
31173             with `caixa` byte-equal to `WitContract::source` — a \
31174             bypass here (a raw `.de.clone()` regression, a divergent \
31175             accessor on a per-CR alias table) would silently split \
31176             the primitive's diagnostic from the substrate-primitive \
31177             scalar accessor every downstream consumer routes through",
31178        );
31179
31180        // `:de` on-oracle, `:para` phantom
31181        let para_phantom = contract_http("cart", "phantom-para", "/x");
31182        let err = para_phantom.require_endpoints_in(&names).unwrap_err();
31183        assert_eq!(
31184            err,
31185            AplicacaoError::ContratoMemberMissing {
31186                caixa: para_phantom.destination().to_string(),
31187            },
31188            "the `:para` phantom arm must fire ContratoMemberMissing \
31189             with `caixa` byte-equal to `WitContract::destination` — \
31190             symmetric callee-side pin to the `:de` arm above",
31191        );
31192
31193        // Both endpoints off-oracle: the `:de` arm must fire first,
31194        // pinning the primitive's canonical edge-direction order.
31195        let both_phantom = contract_http("phantom-de", "phantom-para", "/x");
31196        let err = both_phantom.require_endpoints_in(&names).unwrap_err();
31197        assert_eq!(
31198            err,
31199            AplicacaoError::ContratoMemberMissing {
31200                caixa: both_phantom.source().to_string(),
31201            },
31202            "when both endpoints are off-oracle, the `:de` arm must \
31203             fire before the `:para` arm — preserving byte-equal \
31204             ordering with the pre-lift inline cascade in \
31205             `validate_contratos` and with every peer per-arm \
31206             ordering the sibling per-edge substrate primitives \
31207             already carry",
31208        );
31209
31210        // Both endpoints on-oracle: clean pass.
31211        let clean = contract_http("cart", "catalog", "/x");
31212        clean.require_endpoints_in(&names).unwrap();
31213    }
31214
31215    #[test]
31216    fn validate_contratos_membership_gate_routes_through_require_endpoints_in() {
31217        // Convergence pin: the whole-spec end-to-end route through
31218        // [`AplicacaoSpec::validate_contratos`] must reach the
31219        // per-edge substrate primitive
31220        // [`WitContract::require_endpoints_in`] on every membership
31221        // arm — the diagnostic fired at the per-slot altitude must
31222        // byte-equal the diagnostic the primitive fires when called
31223        // directly on the same edge and the same oracle. Pins the
31224        // primitive as the sole load-bearing gate on the membership
31225        // axis, so any future silent detour that re-inlined the twin
31226        // `if !names.contains(...)` cascade back into the per-slot
31227        // gate (a rebase-artifact regression, an M4 admission-webhook
31228        // consumer that bypassed the primitive) would surface here as
31229        // a byte-equal miss between the two dispatches.
31230        //
31231        // Same equivalence-pin discipline the peer
31232        // [`validate_contratos_matches_gate_on_every_per_axis_shape`]
31233        // pin already carries on the per-slot gate ≡ `validate` axis,
31234        // extended here onto the per-slot gate ≡ per-edge primitive
31235        // axis at one altitude deeper.
31236        for phantom_edge in [
31237            contract_http("phantom-de", "catalog", "/x"),
31238            contract_http("cart", "phantom-para", "/x"),
31239        ] {
31240            let mut spec = three_member_spec();
31241            spec.contratos.push(phantom_edge.clone());
31242            let per_slot_err = spec.validate_contratos().unwrap_err();
31243            let primitive_err = phantom_edge
31244                .require_endpoints_in(&spec.membro_names())
31245                .unwrap_err();
31246            assert_eq!(
31247                per_slot_err, primitive_err,
31248                "the per-slot gate must reach the per-edge substrate \
31249                 primitive on every membership arm — a bypass here \
31250                 would silently split the two dispatches on the \
31251                 same edge + same oracle input",
31252            );
31253            // And the diagnostic's `caixa` carrier must byte-equal
31254            // the offending accessor's projection at both altitudes,
31255            // pinning the accessor routing across the whole-spec
31256            // path.
31257            let AplicacaoError::ContratoMemberMissing { ref caixa } = per_slot_err else {
31258                panic!("expected ContratoMemberMissing, got {per_slot_err:?}");
31259            };
31260            let expected = if spec.membro_names().contains(phantom_edge.source()) {
31261                phantom_edge.destination()
31262            } else {
31263                phantom_edge.source()
31264            };
31265            assert_eq!(
31266                caixa, expected,
31267                "the whole-spec ContratoMemberMissing.caixa carrier \
31268                 must byte-equal the offending edge's accessor \
31269                 projection — a bypass here would silently split \
31270                 the wrap envelope's `caixa` field from the \
31271                 substrate-primitive scalar accessor every \
31272                 downstream consumer routes through",
31273            );
31274        }
31275    }
31276
31277    #[test]
31278    fn port_for_destination_reads_through_lifted_entrada_accessor() {
31279        // Peer coherence pin: the
31280        // [`AplicacaoSpec::port_for_destination`] per-destination
31281        // L4-port fallback resolver's composite-projection seed
31282        // (`self.entrada().filter(…).map_or(…)`) must key off the
31283        // lifted outer accessor. Pins the coherence by exercising
31284        // the resolver end-to-end: (1) the `None` `:entrada` shape
31285        // falls through to `DEFAULT_SERVICO_PORT` under the outer
31286        // accessor's reference projection, (2) a non-matching
31287        // destination falls through to `DEFAULT_SERVICO_PORT` under
31288        // the outer accessor's reference projection, and (3) the
31289        // matching destination resolves to the `:entrada :port`
31290        // value under the outer accessor's reference projection.
31291        //
31292        // Peer of the sibling
31293        // [`validate_reads_through_lifted_entrada_accessor`] multi-
31294        // consumer coherence pin on the same per-`:entrada` outer-
31295        // composite axis — extends the multi-consumer coherence
31296        // discipline onto the second per-`:entrada` production
31297        // consumer, the L4-port fallback resolver.
31298
31299        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
31300        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
31301        // arm under the outer accessor's reference projection.
31302        let mut spec = three_member_spec();
31303        spec.entrada = None;
31304        assert_eq!(
31305            spec.port_for_destination("cart"),
31306            DEFAULT_SERVICO_PORT,
31307            "the port-fallback resolver must fall through to \
31308             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
31309             under the outer accessor's reference projection",
31310        );
31311
31312        // (2) Non-matching destination — the resolver's `filter(…)`
31313        // arm rejects a mismatched destination and falls through
31314        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
31315        // reference projection.
31316        let mut spec = three_member_spec();
31317        if let Some(e) = spec.entrada.as_mut() {
31318            e.para = "cart".into();
31319            e.port = 9443;
31320        }
31321        assert_eq!(
31322            spec.port_for_destination("catalog"),
31323            DEFAULT_SERVICO_PORT,
31324            "the port-fallback resolver must fall through to \
31325             DEFAULT_SERVICO_PORT on a non-matching destination \
31326             under the outer accessor's reference projection",
31327        );
31328
31329        // (3) Matching destination — the resolver's `map_or(…)` arm
31330        // returns the `:entrada :port` value under the outer
31331        // accessor's reference projection.
31332        let mut spec = three_member_spec();
31333        if let Some(e) = spec.entrada.as_mut() {
31334            e.para = "cart".into();
31335            e.port = 9443;
31336        }
31337        assert_eq!(
31338            spec.port_for_destination("cart"),
31339            9443,
31340            "the port-fallback resolver must return the \
31341             `:entrada :port` value on a matching destination \
31342             under the outer accessor's reference projection",
31343        );
31344    }
31345
31346    #[test]
31347    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
31348        // The canonical per-`:politicas` `:mtls-required` mTLS-
31349        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
31350        // must return the `:politicas :mtls-required` typed bool
31351        // verbatim as an `Option<bool>`, byte-equal to the raw field
31352        // access across every value in the three-way accept-set —
31353        // `None` (cluster default applies), `Some(true)` (mTLS
31354        // handshake enforced — the sandboxing-by-default arm the
31355        // MeshPolicy's docstring names), `Some(false)` (handshake
31356        // skipped — the explicit debug-edge opt-out).
31357        //
31358        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
31359        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
31360        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
31361        // shape — first `Option<Copy-T>`-return accessor on the M3
31362        // mesh-slot family. Pins against a future silent detour that
31363        // re-derived the toggle from a peer axis (an accidental
31364        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
31365        // whenever a breaker is set), a `None` → `Some(false)` cluster-
31366        // default projection (the canonical `Option<bool>` → `bool`
31367        // collapse footgun the surrounding `is_empty()` predicate
31368        // guards on the peer emptiness axis), or a `Some(true)` /
31369        // `Some(false)` variant swap that landed on one consumer
31370        // without the other.
31371        for required in [None, Some(true), Some(false)] {
31372            let p = MeshPolicy {
31373                mtls_required: required,
31374                ..MeshPolicy::default()
31375            };
31376            assert_eq!(
31377                p.mtls_required(),
31378                required,
31379                "MeshPolicy::mtls_required must return :politicas \
31380                 :mtls-required verbatim (got {:?}, expected {required:?})",
31381                p.mtls_required(),
31382            );
31383            assert_eq!(
31384                p.mtls_required(),
31385                p.mtls_required,
31386                "MeshPolicy::mtls_required must byte-equal the raw \
31387                 .mtls_required field access across every value in the \
31388                 three-way accept-set",
31389            );
31390        }
31391    }
31392
31393    #[test]
31394    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
31395        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
31396        // arm must key off [`MeshPolicy::mtls_required`], not the raw
31397        // `.mtls_required` field access. Structurally: toggling ONLY
31398        // the `mtls_required` slot on an otherwise-default MeshPolicy
31399        // must flip `is_empty()` from `true` (all-`None`) to `false`
31400        // (one axis carries a value); the flip must be observed for
31401        // both `Some(true)` and `Some(false)` since the emptiness
31402        // semantic reads "any axis carries a value" — not "any axis
31403        // carries a truthy value" — the same non-collapsing shape the
31404        // sibling M2 [`crate::LimitsSpec::is_empty`] /
31405        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
31406        // peer `Option<T>`-typed slot surfaces.
31407        //
31408        // Pins against a future silent detour that re-derived the
31409        // emptiness predicate off a peer axis (an accidental
31410        // `.rate_limit.is_none()`-only chain that dropped the
31411        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
31412        // collapse to a truthy-only check (which would silently
31413        // classify `Some(false)` as empty), or an accessor-side
31414        // detour that no longer names the substrate-primitive typed
31415        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
31416        // == false` fallback in the accessor that would silently
31417        // classify both `None` and `Some(false)` as the same value).
31418        //
31419        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
31420        // (7cd2a28) accessor-composition pin on the sibling optional-
31421        // scalar axis — same "the emptiness / shape-gate predicate
31422        // must route through the substrate-primitive typed dispatch"
31423        // discipline extended onto the peer per-`:politicas` emptiness
31424        // predicate.
31425        let empty = MeshPolicy::default();
31426        assert!(
31427            empty.is_empty(),
31428            "MeshPolicy::default() must be is_empty() — every axis \
31429             defaults to None",
31430        );
31431        for required in [Some(true), Some(false)] {
31432            let p = MeshPolicy {
31433                mtls_required: required,
31434                ..MeshPolicy::default()
31435            };
31436            assert!(
31437                !p.is_empty(),
31438                "MeshPolicy::is_empty must return false when \
31439                 :mtls-required is {required:?} — the emptiness \
31440                 predicate reads \"any axis carries a value\", not \
31441                 \"any axis carries a truthy value\"",
31442            );
31443            assert_eq!(
31444                p.mtls_required().is_none(),
31445                p.is_empty(),
31446                "when :mtls-required is the only set axis, \
31447                 is_empty() must equal mtls_required().is_none() — \
31448                 the accessor and the emptiness predicate must \
31449                 route through the same substrate-primitive typed \
31450                 dispatch on the :mtls-required arm",
31451            );
31452        }
31453    }
31454
31455    #[test]
31456    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
31457        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
31458        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
31459        // accessor must return by value, not by reference. Peer of the
31460        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
31461        // borrow-invariant pin on the sibling `Option<String>` slot,
31462        // but extended onto the peer `Option<bool>` copy-invariant
31463        // shape — the accessor's returned `Option<bool>` must outlive
31464        // `&self` (multiple calls must return equal values from a
31465        // dropped-`&self` copy, since the returned Option carries no
31466        // borrow), and calling the accessor twice on the same
31467        // MeshPolicy must yield the same `Option<bool>` verbatim
31468        // (idempotent, no side effects on `&self`).
31469        //
31470        // Pins against a future silent detour that returned
31471        // `Option<&bool>` (which would type-check but silently break
31472        // every downstream caller — [`single_field_overlay`]'s first
31473        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
31474        // detached copy at the call site), an accidental
31475        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
31476        // would also type-check but return `Option<&bool>`), or a
31477        // one-arm-only accessor that reads `Some(*b)` in the Some arm
31478        // but reads a fresh Default::default() in the None arm.
31479        for required in [None, Some(true), Some(false)] {
31480            let p = MeshPolicy {
31481                mtls_required: required,
31482                ..MeshPolicy::default()
31483            };
31484            let first = p.mtls_required();
31485            let second = p.mtls_required();
31486            assert_eq!(
31487                first, second,
31488                "MeshPolicy::mtls_required must be idempotent — two \
31489                 successive calls on the same &self must return the \
31490                 same Option<bool>",
31491            );
31492            assert_eq!(
31493                first, required,
31494                "MeshPolicy::mtls_required must return :politicas \
31495                 :mtls-required verbatim by copy — got {first:?}, \
31496                 expected {required:?}",
31497            );
31498        }
31499    }
31500
31501    #[test]
31502    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
31503        // The canonical per-`:politicas` `:retries` transient-failure-
31504        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
31505        // the `:politicas :retries` typed `u32` verbatim as an
31506        // `Option<u32>`, byte-equal to the raw field access across every
31507        // representative value in the accept-set — `None` (cluster
31508        // default applies — typically "no retries beyond a single
31509        // dispatch attempt" the caixa-mesh `retry_overlay` builder
31510        // documents), `Some(1)` (the lower boundary of the
31511        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
31512        // `AplicacaoSpec::validate_politicas` gate carves out on the
31513        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
31514        // (the upper boundary the same gate carves out on the sibling
31515        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
31516        // past-the-guard sentinel that pins the accessor doesn't perform
31517        // a silent bounds-collapse at the return path).
31518        //
31519        // Sibling of the peer per-`:politicas`
31520        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
31521        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
31522        // peer per-`:politicas` `Option<u32>` shape — second
31523        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
31524        // Pins against a future silent detour that re-derived the retry
31525        // cap from a peer axis (an accidental `.circuit_breaker
31526        // .as_ref().map(|b| b.max_failures)` collapse that read the
31527        // breaker's max-failure count as a retry budget), a
31528        // `None → Some(0)` cluster-default projection (which would
31529        // silently re-introduce the `PolicyRetriesZero` refusal case at
31530        // the emit boundary), or a bounds-collapsing accessor that
31531        // clamped the return through `POLICY_RETRIES_MAX` (the
31532        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
31533        // must ship the raw slot verbatim so a validate-time gate
31534        // regression surfaces at the emit boundary rather than being
31535        // silently absorbed).
31536        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
31537            let p = MeshPolicy {
31538                retries,
31539                ..MeshPolicy::default()
31540            };
31541            assert_eq!(
31542                p.retries(),
31543                retries,
31544                "MeshPolicy::retries must return :politicas :retries \
31545                 verbatim (got {:?}, expected {retries:?})",
31546                p.retries(),
31547            );
31548            assert_eq!(
31549                p.retries(),
31550                p.retries,
31551                "MeshPolicy::retries must byte-equal the raw .retries \
31552                 field access across every value in the accept-set",
31553            );
31554        }
31555    }
31556
31557    #[test]
31558    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
31559        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
31560        // must key off [`MeshPolicy::retries`], not the raw `.retries`
31561        // field access. Structurally: toggling ONLY the `retries` slot
31562        // on an otherwise-default MeshPolicy must flip `is_empty()`
31563        // from `true` (all-`None`) to `false` (one axis carries a
31564        // value); the flip must be observed for every value in the
31565        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
31566        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
31567        // the emptiness semantic reads "any axis carries a value" —
31568        // not "any axis carries a value the validate gate accepts" —
31569        // the same non-collapsing shape the peer M2
31570        // [`crate::LimitsSpec::is_empty`] /
31571        // [`crate::BehaviorSpec::is_empty`] predicates carry.
31572        //
31573        // Pins against a future silent detour that re-derived the
31574        // emptiness predicate off a peer axis (an accidental
31575        // `.rate_limit.is_none()`-only chain that dropped the
31576        // `retries` arm entirely), a `retries == Some(_)` collapse
31577        // that key-off a validate-gate-clamped bounds check (which
31578        // would silently classify a past-the-guard `Some(u32::MAX)`
31579        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
31580        // check), or an accessor-side detour that no longer names the
31581        // substrate-primitive typed dispatch.
31582        //
31583        // Sibling of the peer per-`:politicas`
31584        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
31585        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
31586        // same "the emptiness predicate must route through the
31587        // substrate-primitive typed dispatch" discipline extended onto
31588        // the peer per-`:politicas` `Option<u32>` axis.
31589        let empty = MeshPolicy::default();
31590        assert!(
31591            empty.is_empty(),
31592            "MeshPolicy::default() must be is_empty() — every axis \
31593             defaults to None",
31594        );
31595        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
31596            let p = MeshPolicy {
31597                retries,
31598                ..MeshPolicy::default()
31599            };
31600            assert!(
31601                !p.is_empty(),
31602                "MeshPolicy::is_empty must return false when \
31603                 :retries is {retries:?} — the emptiness \
31604                 predicate reads \"any axis carries a value\", not \
31605                 \"any axis carries a value the validate gate \
31606                 accepts\"",
31607            );
31608            assert_eq!(
31609                p.retries().is_none(),
31610                p.is_empty(),
31611                "when :retries is the only set axis, is_empty() \
31612                 must equal retries().is_none() — the accessor and \
31613                 the emptiness predicate must route through the same \
31614                 substrate-primitive typed dispatch on the :retries \
31615                 arm",
31616            );
31617        }
31618    }
31619
31620    #[test]
31621    fn mesh_policy_retries_projects_option_u32_by_copy() {
31622        // The by-copy pin: [`MeshPolicy::retries`] returns
31623        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
31624        // accessor must return by value, not by reference. Sibling of
31625        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
31626        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
31627        // extended onto the sibling `Option<u32>` copy-invariant
31628        // shape — the accessor's returned `Option<u32>` must outlive
31629        // `&self` (multiple calls must return equal values from a
31630        // dropped-`&self` copy, since the returned Option carries no
31631        // borrow), and calling the accessor twice on the same
31632        // MeshPolicy must yield the same `Option<u32>` verbatim
31633        // (idempotent, no side effects on `&self`).
31634        //
31635        // Pins against a future silent detour that returned
31636        // `Option<&u32>` (which would type-check but silently break
31637        // every downstream caller — [`crate::render::single_field_overlay`]'s
31638        // first parameter is `Option<T: Clone>`, and `&u32` would
31639        // fold to a detached copy at the call site), an accidental
31640        // `Option::as_ref()` projection (`self.retries.as_ref()` would
31641        // also type-check but return `Option<&u32>`), or a one-arm-
31642        // only accessor that reads `Some(*n)` in the Some arm but
31643        // reads a fresh `Default::default()` (`0_u32`) in the None
31644        // arm.
31645        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
31646            let p = MeshPolicy {
31647                retries,
31648                ..MeshPolicy::default()
31649            };
31650            let first = p.retries();
31651            let second = p.retries();
31652            assert_eq!(
31653                first, second,
31654                "MeshPolicy::retries must be idempotent — two \
31655                 successive calls on the same &self must return the \
31656                 same Option<u32>",
31657            );
31658            assert_eq!(
31659                first, retries,
31660                "MeshPolicy::retries must return :politicas :retries \
31661                 verbatim by copy — got {first:?}, expected {retries:?}",
31662            );
31663        }
31664    }
31665
31666    #[test]
31667    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
31668        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
31669        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
31670        // return the `:politicas :timeout` typed [`Duration`] verbatim
31671        // as an `Option<Duration>`, byte-equal to the raw field access
31672        // across every representative value in the accept-set — `None`
31673        // (cluster default applies — typically the gateway class's
31674        // implementation-side per-request wall-clock cap the caixa-mesh
31675        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
31676        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
31677        // set the surrounding `AplicacaoSpec::validate_politicas` gate
31678        // carves out on the sibling `PolicyTimeoutZero` /
31679        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
31680        // (the upper boundary the same gate carves out on the sibling
31681        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
31682        // (a past-the-guard sentinel that pins the accessor doesn't
31683        // perform a silent bounds-collapse into `None` on the zero-
31684        // Duration arm — validate rejects zero but the accessor must
31685        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
31686        // past-the-guard sentinel that pins the accessor doesn't
31687        // perform a silent bounds-collapse at the return path).
31688        //
31689        // Sibling of the peer per-`:politicas`
31690        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
31691        // `Option<u32>` optional-scalar axis and the peer per-
31692        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
31693        // pin on the sibling `Option<bool>` optional-scalar axis,
31694        // extended onto the peer per-`:politicas` `Option<Duration>`
31695        // shape — third `Option<Copy-T>`-return accessor on the M3
31696        // mesh-slot family. Pins against a future silent detour that
31697        // re-derived the per-call cap from a peer axis (an accidental
31698        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
31699        // read the breaker's rolling-window duration as a per-call
31700        // deadline), a `None → Some(Duration::MAX)` cluster-default
31701        // projection (which would silently re-introduce the
31702        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
31703        // blocking" arm at the emit boundary), or a bounds-collapsing
31704        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
31705        // (the `AplicacaoSpec::validate` gate owns the bounds; the
31706        // accessor must ship the raw slot verbatim so a validate-time
31707        // gate regression surfaces at the emit boundary rather than
31708        // being silently absorbed).
31709        for timeout in [
31710            None,
31711            Some(Duration::from_millis(1)),
31712            Some(POLICY_TIMEOUT_MAX),
31713            Some(Duration::ZERO),
31714            Some(Duration::MAX),
31715        ] {
31716            let p = MeshPolicy {
31717                timeout,
31718                ..MeshPolicy::default()
31719            };
31720            assert_eq!(
31721                p.timeout(),
31722                timeout,
31723                "MeshPolicy::timeout must return :politicas :timeout \
31724                 verbatim (got {:?}, expected {timeout:?})",
31725                p.timeout(),
31726            );
31727            assert_eq!(
31728                p.timeout(),
31729                p.timeout,
31730                "MeshPolicy::timeout must byte-equal the raw .timeout \
31731                 field access across every value in the accept-set",
31732            );
31733        }
31734    }
31735
31736    #[test]
31737    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
31738        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
31739        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
31740        // field access. Structurally: toggling ONLY the `timeout` slot
31741        // on an otherwise-default MeshPolicy must flip `is_empty()`
31742        // from `true` (all-`None`) to `false` (one axis carries a
31743        // value); the flip must be observed for every value in the
31744        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
31745        // gate accepts (`Some(Duration::from_millis(1))`,
31746        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
31747        // reads "any axis carries a value" — not "any axis carries a
31748        // value the validate gate accepts" — the same non-collapsing
31749        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
31750        // [`crate::BehaviorSpec::is_empty`] predicates carry.
31751        //
31752        // Pins against a future silent detour that re-derived the
31753        // emptiness predicate off a peer axis (an accidental
31754        // `.rate_limit.is_none()`-only chain that dropped the
31755        // `timeout` arm entirely), a `timeout == Some(_)` collapse
31756        // that key-off a validate-gate-clamped bounds check (which
31757        // would silently classify a past-the-guard `Some(Duration::MAX)`
31758        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
31759        // check), or an accessor-side detour that no longer names the
31760        // substrate-primitive typed dispatch.
31761        //
31762        // Sibling of the peer per-`:politicas`
31763        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
31764        // the sibling `Option<u32>` optional-scalar axis and the peer
31765        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
31766        // accessor-composition pin on the sibling `Option<bool>`
31767        // optional-scalar axis — same "the emptiness predicate must
31768        // route through the substrate-primitive typed dispatch"
31769        // discipline extended onto the peer per-`:politicas`
31770        // `Option<Duration>` axis.
31771        let empty = MeshPolicy::default();
31772        assert!(
31773            empty.is_empty(),
31774            "MeshPolicy::default() must be is_empty() — every axis \
31775             defaults to None",
31776        );
31777        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
31778            let p = MeshPolicy {
31779                timeout,
31780                ..MeshPolicy::default()
31781            };
31782            assert!(
31783                !p.is_empty(),
31784                "MeshPolicy::is_empty must return false when \
31785                 :timeout is {timeout:?} — the emptiness \
31786                 predicate reads \"any axis carries a value\", not \
31787                 \"any axis carries a value the validate gate \
31788                 accepts\"",
31789            );
31790            assert_eq!(
31791                p.timeout().is_none(),
31792                p.is_empty(),
31793                "when :timeout is the only set axis, is_empty() \
31794                 must equal timeout().is_none() — the accessor and \
31795                 the emptiness predicate must route through the same \
31796                 substrate-primitive typed dispatch on the :timeout \
31797                 arm",
31798            );
31799        }
31800    }
31801
31802    #[test]
31803    fn mesh_policy_timeout_projects_option_duration_by_copy() {
31804        // The by-copy pin: [`MeshPolicy::timeout`] returns
31805        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
31806        // and the accessor must return by value, not by reference.
31807        // Sibling of the peer per-`:politicas`
31808        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
31809        // sibling `Option<u32>` optional-scalar axis and the peer
31810        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
31811        // by-copy pin on the sibling `Option<bool>` optional-scalar
31812        // axis, extended onto the peer per-`:politicas`
31813        // `Option<Duration>` copy-invariant shape — the accessor's
31814        // returned `Option<Duration>` must outlive `&self` (multiple
31815        // calls must return equal values from a dropped-`&self`
31816        // copy, since the returned Option carries no borrow), and
31817        // calling the accessor twice on the same MeshPolicy must
31818        // yield the same `Option<Duration>` verbatim (idempotent, no
31819        // side effects on `&self`).
31820        //
31821        // Pins against a future silent detour that returned
31822        // `Option<&Duration>` (which would type-check but silently
31823        // break every downstream caller — [`crate::render::single_field_overlay`]'s
31824        // first parameter is `Option<T: Clone>`, and `&Duration`
31825        // would fold to a detached copy at the call site), an
31826        // accidental `Option::as_ref()` projection
31827        // (`self.timeout.as_ref()` would also type-check but return
31828        // `Option<&Duration>`), or a one-arm-only accessor that
31829        // reads `Some(*d)` in the Some arm but reads a fresh
31830        // `Default::default()` (`Duration::ZERO`) in the None arm
31831        // (which would silently re-classify every unset `:timeout`
31832        // as the `PolicyTimeoutZero`-refused zero-Duration value at
31833        // the accessor boundary).
31834        for timeout in [
31835            None,
31836            Some(Duration::from_millis(1)),
31837            Some(POLICY_TIMEOUT_MAX),
31838            Some(Duration::ZERO),
31839            Some(Duration::MAX),
31840        ] {
31841            let p = MeshPolicy {
31842                timeout,
31843                ..MeshPolicy::default()
31844            };
31845            let first = p.timeout();
31846            let second = p.timeout();
31847            assert_eq!(
31848                first, second,
31849                "MeshPolicy::timeout must be idempotent — two \
31850                 successive calls on the same &self must return the \
31851                 same Option<Duration>",
31852            );
31853            assert_eq!(
31854                first, timeout,
31855                "MeshPolicy::timeout must return :politicas :timeout \
31856                 verbatim by copy — got {first:?}, expected {timeout:?}",
31857            );
31858        }
31859    }
31860
31861    #[test]
31862    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
31863        // The canonical per-`:politicas` `:rate-limit` Envoy-
31864        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
31865        // [`MeshPolicy::rate_limit`] must return the `:politicas
31866        // :rate-limit` typed [`RateLimit`] verbatim as an
31867        // `Option<RateLimit>`, byte-equal to the raw field access
31868        // across every representative value in the accept-set — `None`
31869        // (cluster default applies — no per-Aplicacao rate declaration,
31870        // the gateway-class per-listener default arm the future caixa-
31871        // mesh `local_rate_limit_overlay` emitter documents),
31872        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
31873        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
31874        // accept-set the surrounding
31875        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
31876        // sibling `PolicyRateLimitZero` refusal, paired with the
31877        // canonical-window "1 second" arm of the three-unit
31878        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
31879        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
31880        // (the upper boundary the same gate carves out on the sibling
31881        // `PolicyRateLimitExceedsCap` refusal, paired with the
31882        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
31883        // (a past-the-guard sentinel that pins the accessor doesn't
31884        // perform a silent bounds-collapse into `None` on the
31885        // zero-rate/zero-window arm — validate rejects zero but the
31886        // accessor must ship the raw slot verbatim so a validate-time
31887        // gate regression surfaces at the emit boundary rather than
31888        // being silently absorbed), and
31889        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
31890        // (a past-the-guard sentinel that pins the accessor doesn't
31891        // perform a silent bounds-collapse at the return path).
31892        //
31893        // First `Option<Copy-composite-T>`-return accessor pin on the
31894        // M3 mesh-slot family (peer of the sibling per-`:politicas`
31895        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
31896        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
31897        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
31898        // Copy accessor pins, extended onto the peer per-`:politicas`
31899        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
31900        // and the accessor returns by value). Pins against a future
31901        // silent detour that re-derived the rate declaration from a
31902        // peer axis (an accidental
31903        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
31904        // collapse that read the breaker's trip threshold + rolling
31905        // window as a rate declaration), a `None → Some(default())`
31906        // cluster-default projection (which would silently re-
31907        // introduce a "cluster default is 0/s" arm the emit boundary
31908        // would take as "declared but inert" — the canonical
31909        // declared-but-inert footgun the sibling
31910        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
31911        // amplification-shape axis), a bounds-collapsing accessor
31912        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
31913        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
31914        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
31915        // accessor must ship the raw slot verbatim), or a
31916        // by-reference detour (`Option<&RateLimit>`) that broke every
31917        // downstream consumer keying off `Option<RateLimit>` by-copy.
31918        for rl in [
31919            None,
31920            Some(RateLimit {
31921                rate: 1,
31922                window: Duration::from_secs(1),
31923            }),
31924            Some(RateLimit {
31925                rate: POLICY_RATE_LIMIT_MAX,
31926                window: Duration::from_secs(3600),
31927            }),
31928            Some(RateLimit {
31929                rate: 0,
31930                window: Duration::ZERO,
31931            }),
31932            Some(RateLimit {
31933                rate: u32::MAX,
31934                window: Duration::MAX,
31935            }),
31936        ] {
31937            let p = MeshPolicy {
31938                rate_limit: rl,
31939                ..MeshPolicy::default()
31940            };
31941            assert_eq!(
31942                p.rate_limit(),
31943                rl,
31944                "MeshPolicy::rate_limit must return :politicas :rate-limit \
31945                 verbatim (got {:?}, expected {rl:?})",
31946                p.rate_limit(),
31947            );
31948            assert_eq!(
31949                p.rate_limit(),
31950                p.rate_limit,
31951                "MeshPolicy::rate_limit must byte-equal the raw \
31952                 .rate_limit field access across every value in the \
31953                 accept-set",
31954            );
31955        }
31956    }
31957
31958    #[test]
31959    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
31960        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
31961        // must key off [`MeshPolicy::rate_limit`], not the raw
31962        // `.rate_limit` field access. Structurally: toggling ONLY the
31963        // `rate_limit` slot on an otherwise-default MeshPolicy must
31964        // flip `is_empty()` from `true` (all-`None`) to `false` (one
31965        // axis carries a value); the flip must be observed for every
31966        // representative value in the accept-set the surrounding
31967        // [`AplicacaoSpec::validate_politicas`] gate accepts
31968        // (`Some(RateLimit { rate: 1, window: 1s })`,
31969        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
31970        // since the emptiness semantic reads "any axis carries a
31971        // value" — not "any axis carries a value the validate gate
31972        // accepts" — the same non-collapsing shape the peer M2
31973        // [`crate::LimitsSpec::is_empty`] /
31974        // [`crate::BehaviorSpec::is_empty`] predicates carry.
31975        //
31976        // Pins against a future silent detour that re-derived the
31977        // emptiness predicate off a peer axis (an accidental
31978        // `.timeout.is_none()`-only chain that dropped the
31979        // `rate_limit` arm entirely — the last unlifted inline field
31980        // access on `is_empty` before this lift), a `rate_limit ==
31981        // Some(_)` collapse that key-off a validate-gate-clamped
31982        // bounds check (which would silently classify a past-the-
31983        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
31984        // because it fails the value-shape gate), or an accessor-
31985        // side detour that no longer names the substrate-primitive
31986        // typed dispatch.
31987        //
31988        // Fourth "the emptiness predicate must route through the
31989        // substrate-primitive typed dispatch" composition pin on the
31990        // M3 mesh-slot family — closes the last unlifted composition
31991        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
31992        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
31993        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
31994        // 7073d0f is_empty-composition pins on the sibling primitive-
31995        // Copy axes, extended onto the peer per-`:politicas`
31996        // composite-Copy `Option<RateLimit>` axis).
31997        let empty = MeshPolicy::default();
31998        assert!(
31999            empty.is_empty(),
32000            "MeshPolicy::default() must be is_empty() — every axis \
32001             defaults to None",
32002        );
32003        for rl in [
32004            RateLimit {
32005                rate: 1,
32006                window: Duration::from_secs(1),
32007            },
32008            RateLimit {
32009                rate: POLICY_RATE_LIMIT_MAX,
32010                window: Duration::from_secs(3600),
32011            },
32012        ] {
32013            let p = MeshPolicy {
32014                rate_limit: Some(rl),
32015                ..MeshPolicy::default()
32016            };
32017            assert!(
32018                !p.is_empty(),
32019                "MeshPolicy::is_empty must return false when \
32020                 :rate-limit is {rl:?} — the emptiness predicate \
32021                 reads \"any axis carries a value\", not \"any axis \
32022                 carries a value the validate gate accepts\"",
32023            );
32024            assert_eq!(
32025                p.rate_limit().is_none(),
32026                p.is_empty(),
32027                "when :rate-limit is the only set axis, is_empty() \
32028                 must equal rate_limit().is_none() — the accessor \
32029                 and the emptiness predicate must route through the \
32030                 same substrate-primitive typed dispatch on the \
32031                 :rate-limit arm",
32032            );
32033        }
32034    }
32035
32036    #[test]
32037    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
32038        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32039        // `:rate-limit` value-shape gate must key off
32040        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
32041        // field bind. Structurally: a `MeshPolicy` whose only set
32042        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
32043        // the `PolicyRateLimitZero` refusal exactly, and the same
32044        // MeshPolicy with the rate at the canonical lower boundary
32045        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
32046        // The pair jointly pins the accessor + validate-gate
32047        // composition: any future silent detour that had the accessor
32048        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
32049        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
32050        // silently absorb the `PolicyRateLimitZero` refusal at the
32051        // accessor boundary — the composition pin catches that at
32052        // caixa-core build time.
32053        //
32054        // Sibling of the peer [`validate_politicas`]
32055        // `:mtls-required` / `:retries` / `:timeout` composition pins
32056        // on the sibling primitive-Copy optional-scalar axes — same
32057        // "the validate / shape-gate predicate must route through the
32058        // substrate-primitive typed dispatch" discipline extended
32059        // onto the peer per-`:politicas` composite-Copy
32060        // `Option<RateLimit>` axis. Second composition-with-accessor
32061        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
32062        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
32063        let mut spec = three_member_spec();
32064        spec.politicas = MeshPolicy {
32065            rate_limit: Some(RateLimit {
32066                rate: 0,
32067                window: Duration::from_secs(1),
32068            }),
32069            ..MeshPolicy::default()
32070        };
32071        assert!(
32072            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
32073            "validate_politicas must reject rate == 0 with \
32074             PolicyRateLimitZero — the accessor and the validate gate \
32075             must route through the same substrate-primitive typed \
32076             dispatch on the :rate-limit zero-floor arm",
32077        );
32078        spec.politicas = MeshPolicy {
32079            rate_limit: Some(RateLimit {
32080                rate: 1,
32081                window: Duration::from_secs(1),
32082            }),
32083            ..MeshPolicy::default()
32084        };
32085        assert!(
32086            spec.validate().is_ok(),
32087            "validate_politicas must accept rate == 1 (the canonical \
32088             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
32089             set) with a canonical 1s window",
32090        );
32091    }
32092
32093    #[test]
32094    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
32095        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
32096        // `outlier_detection`-mesh consecutive-failure-ejection scalar
32097        // pin: [`MeshPolicy::circuit_breaker`] must return the
32098        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
32099        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
32100        // raw field access across every representative value in the
32101        // accept-set — `None` (cluster default applies — no
32102        // per-Aplicacao breaker declaration, the gateway-class per-
32103        // listener default arm the future caixa-mesh
32104        // `outlier_detection_overlay` emitter documents),
32105        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
32106        // (the lower boundary of the accept-set the surrounding
32107        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
32108        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
32109        // refusals),
32110        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
32111        // (the upper boundary the same gate carves out on the sibling
32112        // `PolicyBreakerMaxFailuresExceedsCap` /
32113        // `PolicyBreakerWindowExceedsCap` refusals),
32114        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
32115        // (a past-the-guard sentinel that pins the accessor doesn't
32116        // perform a silent bounds-collapse into `None` on the
32117        // zero-failures/zero-window arm — validate rejects zero but
32118        // the accessor must ship the raw slot verbatim so a validate-
32119        // time gate regression surfaces at the emit boundary rather
32120        // than being silently absorbed), and
32121        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
32122        // (a past-the-guard sentinel that pins the accessor doesn't
32123        // perform a silent bounds-collapse at the return path).
32124        //
32125        // Second `Option<Copy-composite-T>`-return accessor pin on the
32126        // M3 mesh-slot family (peer of the sibling per-`:politicas`
32127        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
32128        // composite-Copy accessor pin, and of the sibling per-
32129        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
32130        // [`MeshPolicy::retries`] bdfb399 /
32131        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
32132        // accessor pins). Pins against a future silent detour that
32133        // re-derived the breaker declaration from a peer axis (an
32134        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
32135        // collapse that read the rate-limit's bucket capacity + refill
32136        // period as a breaker declaration), a `None → Some(default())`
32137        // cluster-default projection (which would silently re-
32138        // introduce the `PolicyBreakerZeroFailures` /
32139        // `PolicyBreakerZeroWindow` refusal cases at the emit
32140        // boundary), a bounds-collapsing accessor that clamped
32141        // `cb.max_failures` through
32142        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
32143        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
32144        // [`AplicacaoSpec::validate`] gate owns the bounds; the
32145        // accessor must ship the raw slot verbatim), or a
32146        // by-reference detour (`Option<&CircuitBreaker>`) that broke
32147        // every downstream consumer keying off `Option<CircuitBreaker>`
32148        // by-copy.
32149        for cb in [
32150            None,
32151            Some(CircuitBreaker {
32152                max_failures: 1,
32153                window: Duration::from_millis(1),
32154            }),
32155            Some(CircuitBreaker {
32156                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
32157                window: POLICY_BREAKER_WINDOW_MAX,
32158            }),
32159            Some(CircuitBreaker {
32160                max_failures: 0,
32161                window: Duration::ZERO,
32162            }),
32163            Some(CircuitBreaker {
32164                max_failures: u32::MAX,
32165                window: Duration::MAX,
32166            }),
32167        ] {
32168            let p = MeshPolicy {
32169                circuit_breaker: cb,
32170                ..MeshPolicy::default()
32171            };
32172            assert_eq!(
32173                p.circuit_breaker(),
32174                cb,
32175                "MeshPolicy::circuit_breaker must return :politicas \
32176                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
32177                p.circuit_breaker(),
32178            );
32179            assert_eq!(
32180                p.circuit_breaker(),
32181                p.circuit_breaker,
32182                "MeshPolicy::circuit_breaker must byte-equal the raw \
32183                 .circuit_breaker field access across every value in \
32184                 the accept-set",
32185            );
32186        }
32187    }
32188
32189    #[test]
32190    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
32191        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
32192        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
32193        // `.circuit_breaker` field access. Structurally: toggling ONLY
32194        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
32195        // must flip `is_empty()` from `true` (all-`None`) to `false`
32196        // (one axis carries a value); the flip must be observed for
32197        // every representative value in the accept-set the surrounding
32198        // [`AplicacaoSpec::validate_politicas`] gate accepts
32199        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
32200        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
32201        // since the emptiness semantic reads "any axis carries a
32202        // value" — not "any axis carries a value the validate gate
32203        // accepts" — the same non-collapsing shape the peer M2
32204        // [`crate::LimitsSpec::is_empty`] /
32205        // [`crate::BehaviorSpec::is_empty`] predicates carry.
32206        //
32207        // Pins against a future silent detour that re-derived the
32208        // emptiness predicate off a peer axis (an accidental
32209        // `.rate_limit.is_none()`-only chain that dropped the
32210        // `circuit_breaker` arm entirely — the last unlifted inline
32211        // field access on `is_empty` before this lift), a
32212        // `circuit_breaker == Some(_)` collapse that key-off a
32213        // validate-gate-clamped bounds check (which would silently
32214        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
32215        // 0, window: 0s })` as empty because it fails the value-shape
32216        // gate), or an accessor-side detour that no longer names the
32217        // substrate-primitive typed dispatch.
32218        //
32219        // Fifth "the emptiness predicate must route through the
32220        // substrate-primitive typed dispatch" composition pin on the
32221        // M3 mesh-slot family — closes the last unlifted composition
32222        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
32223        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
32224        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
32225        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
32226        // composition pins on the sibling primitive-Copy + composite-
32227        // Copy axes, extended onto the peer per-`:politicas`
32228        // composite-Copy `Option<CircuitBreaker>` axis).
32229        let empty = MeshPolicy::default();
32230        assert!(
32231            empty.is_empty(),
32232            "MeshPolicy::default() must be is_empty() — every axis \
32233             defaults to None",
32234        );
32235        for cb in [
32236            CircuitBreaker {
32237                max_failures: 1,
32238                window: Duration::from_millis(1),
32239            },
32240            CircuitBreaker {
32241                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
32242                window: POLICY_BREAKER_WINDOW_MAX,
32243            },
32244        ] {
32245            let p = MeshPolicy {
32246                circuit_breaker: Some(cb),
32247                ..MeshPolicy::default()
32248            };
32249            assert!(
32250                !p.is_empty(),
32251                "MeshPolicy::is_empty must return false when \
32252                 :circuit-breaker is {cb:?} — the emptiness predicate \
32253                 reads \"any axis carries a value\", not \"any axis \
32254                 carries a value the validate gate accepts\"",
32255            );
32256            assert_eq!(
32257                p.circuit_breaker().is_none(),
32258                p.is_empty(),
32259                "when :circuit-breaker is the only set axis, \
32260                 is_empty() must equal circuit_breaker().is_none() — \
32261                 the accessor and the emptiness predicate must route \
32262                 through the same substrate-primitive typed dispatch \
32263                 on the :circuit-breaker arm",
32264            );
32265        }
32266    }
32267
32268    #[test]
32269    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
32270        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32271        // `:circuit-breaker` value-shape gate must key off
32272        // [`MeshPolicy::circuit_breaker`], not the raw
32273        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
32274        // whose only set axis is a `Some(CircuitBreaker { max_failures:
32275        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
32276        // refusal exactly, and the same MeshPolicy with the breaker at
32277        // the canonical lower boundary
32278        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
32279        // pass validate. The pair jointly pins the accessor +
32280        // validate-gate composition: any future silent detour that had
32281        // the accessor omit the `Some(CircuitBreaker { max_failures:
32282        // 0, .. })` arm (a
32283        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
32284        // collapse) would silently absorb the
32285        // `PolicyBreakerZeroFailures` refusal at the accessor
32286        // boundary — the composition pin catches that at caixa-core
32287        // build time.
32288        //
32289        // Sibling of the peer [`validate_politicas`]
32290        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
32291        // composition pins on the sibling primitive-Copy + composite-
32292        // Copy optional-scalar axes — same "the validate / shape-gate
32293        // predicate must route through the substrate-primitive typed
32294        // dispatch" discipline extended onto the peer per-`:politicas`
32295        // composite-Copy `Option<CircuitBreaker>` axis. Second
32296        // composition-with-accessor pin on the M3 mesh-slot
32297        // `Option<CircuitBreaker>` arm alongside the
32298        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
32299        let mut spec = three_member_spec();
32300        spec.politicas = MeshPolicy {
32301            circuit_breaker: Some(CircuitBreaker {
32302                max_failures: 0,
32303                window: Duration::from_millis(1),
32304            }),
32305            ..MeshPolicy::default()
32306        };
32307        assert!(
32308            matches!(
32309                spec.validate(),
32310                Err(AplicacaoError::PolicyBreakerZeroFailures)
32311            ),
32312            "validate_politicas must reject max_failures == 0 with \
32313             PolicyBreakerZeroFailures — the accessor and the validate \
32314             gate must route through the same substrate-primitive \
32315             typed dispatch on the :circuit-breaker zero-floor arm",
32316        );
32317        spec.politicas = MeshPolicy {
32318            circuit_breaker: Some(CircuitBreaker {
32319                max_failures: 1,
32320                window: Duration::from_millis(1),
32321            }),
32322            ..MeshPolicy::default()
32323        };
32324        assert!(
32325            spec.validate().is_ok(),
32326            "validate_politicas must accept a CircuitBreaker at the \
32327             canonical lower boundary (max_failures = 1, window = \
32328             1ms) — the accessor and the validate gate must route \
32329             through the same substrate-primitive typed dispatch on \
32330             the :circuit-breaker arm",
32331        );
32332    }
32333
32334    #[test]
32335    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
32336        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
32337        // Envoy-outlier-detection trip-threshold scalar pin:
32338        // [`CircuitBreaker::max_failures`] must return the
32339        // `:politicas :circuit-breaker :max-failures` typed `u32`
32340        // verbatim, byte-equal to the raw field access across every
32341        // representative value in the accept-set — `1` (the lower
32342        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
32343        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
32344        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
32345        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
32346        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
32347        // refusal), `0` (a past-the-guard sentinel that pins the accessor
32348        // doesn't perform a silent bounds-collapse into `1` on the zero
32349        // arm — validate rejects zero but the accessor must ship the
32350        // raw slot verbatim so a validate-time gate regression surfaces
32351        // at the emit boundary rather than being silently absorbed),
32352        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
32353        // doesn't perform a silent bounds-collapse through
32354        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
32355        //
32356        // First sub-struct required-scalar accessor pin on the M3
32357        // mesh-slot family — sibling in shape to the peer per-`:membros`
32358        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
32359        // (a40b0e3) required-`String`-carry accessor pins and the peer
32360        // per-`:contratos` [`WitContract::source`] /
32361        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
32362        // accessor pins, extended onto the peer per-`CircuitBreaker`
32363        // required-`u32` scalar-value axis. Pins against a future silent
32364        // detour that re-derived the trip threshold from a peer axis (an
32365        // accidental `self.window.as_secs() as u32` collapse that read
32366        // the breaker's rolling-window duration as a failure count), a
32367        // `0 → 1` cluster-default projection (which would silently absorb
32368        // the `PolicyBreakerZeroFailures` refusal case at the accessor
32369        // boundary), or a bounds-collapsing accessor that clamped the
32370        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
32371        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
32372        // must ship the raw slot verbatim).
32373        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
32374            let cb = CircuitBreaker {
32375                max_failures,
32376                window: Duration::from_secs(60),
32377            };
32378            assert_eq!(
32379                cb.max_failures(),
32380                max_failures,
32381                "CircuitBreaker::max_failures must return :politicas \
32382                 :circuit-breaker :max-failures verbatim (got {}, \
32383                 expected {max_failures})",
32384                cb.max_failures(),
32385            );
32386            assert_eq!(
32387                cb.max_failures(),
32388                cb.max_failures,
32389                "CircuitBreaker::max_failures must byte-equal the raw \
32390                 .max_failures field access across every value in the \
32391                 u32 accept-set",
32392            );
32393        }
32394    }
32395
32396    #[test]
32397    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
32398        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32399        // `:circuit-breaker :max-failures` zero-floor arm must key off
32400        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
32401        // field access. Structurally: a `CircuitBreaker { max_failures:
32402        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
32403        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
32404        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
32405        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
32406        // pass validate. The pair jointly pins the accessor +
32407        // validate-gate composition: any future silent detour that had
32408        // the accessor return a fresh `1` on the zero arm (a
32409        // `.max_failures().max(1)` collapse) would silently absorb the
32410        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
32411        // and the validate gate would accept a struct-literal
32412        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
32413        // catches that at caixa-core build time.
32414        //
32415        // Peer of the sibling per-`:politicas`
32416        // [`MeshPolicy::mtls_required`] (c0110f1) /
32417        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
32418        // (7073d0f) accessor-composition pins on the sibling optional-
32419        // scalar axes — same "the validate / shape-gate predicate must
32420        // route through the substrate-primitive typed dispatch"
32421        // discipline extended onto the peer per-`CircuitBreaker`
32422        // required-scalar composition axis.
32423        let mut spec = three_member_spec();
32424        spec.politicas = MeshPolicy {
32425            circuit_breaker: Some(CircuitBreaker {
32426                max_failures: 0,
32427                window: Duration::from_secs(60),
32428            }),
32429            ..MeshPolicy::default()
32430        };
32431        assert!(
32432            matches!(
32433                spec.validate(),
32434                Err(AplicacaoError::PolicyBreakerZeroFailures)
32435            ),
32436            "validate_politicas must reject max_failures == 0 with \
32437             PolicyBreakerZeroFailures — the accessor and the validate \
32438             gate must route through the same substrate-primitive typed \
32439             dispatch on the :max-failures zero-floor arm",
32440        );
32441        spec.politicas = MeshPolicy {
32442            circuit_breaker: Some(CircuitBreaker {
32443                max_failures: 1,
32444                window: Duration::from_secs(60),
32445            }),
32446            ..MeshPolicy::default()
32447        };
32448        assert!(
32449            spec.validate().is_ok(),
32450            "validate_politicas must accept max_failures == 1 (the \
32451             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
32452             accept-set)",
32453        );
32454    }
32455
32456    #[test]
32457    fn circuit_breaker_max_failures_projects_u32_by_copy() {
32458        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
32459        // `u32` by copy — `u32` is `Copy` and the accessor must return
32460        // by value, not by reference. Peer of the sibling
32461        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
32462        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
32463        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
32464        // optional-scalar axes, extended onto the peer
32465        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
32466        // the accessor's returned `u32` must outlive `&self` (multiple
32467        // calls must return equal values from a dropped-`&self` copy,
32468        // since the returned scalar carries no borrow), and calling
32469        // the accessor twice on the same CircuitBreaker must yield the
32470        // same `u32` verbatim (idempotent, no side effects on `&self`).
32471        //
32472        // Pins against a future silent detour that returned `&u32`
32473        // (which would type-check but silently break every downstream
32474        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
32475        // first parameter is `u32`, and `&u32` would fold to a detached
32476        // copy at the call site with a `*` deref the sibling accessors
32477        // don't need), an accidental `.max_failures.wrapping_add(0)`
32478        // detour that returned a fresh copy through an arithmetic
32479        // no-op (breaking a future `const fn` regression), or a
32480        // one-arm-only accessor that returned a saturating value on
32481        // some sentinel input (breaking the pass-through invariant the
32482        // sibling required-scalar accessors carry).
32483        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
32484            let cb = CircuitBreaker {
32485                max_failures,
32486                window: Duration::from_secs(60),
32487            };
32488            let first = cb.max_failures();
32489            let second = cb.max_failures();
32490            assert_eq!(
32491                first, second,
32492                "CircuitBreaker::max_failures must be idempotent — two \
32493                 successive calls on the same &self must return the \
32494                 same u32",
32495            );
32496            assert_eq!(
32497                first, max_failures,
32498                "CircuitBreaker::max_failures must return :politicas \
32499                 :circuit-breaker :max-failures verbatim by copy — \
32500                 got {first}, expected {max_failures}",
32501            );
32502        }
32503    }
32504
32505    #[test]
32506    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
32507        // The canonical per-`:politicas :circuit-breaker` `:window`
32508        // Envoy-outlier-detection rolling-observation-interval scalar
32509        // pin: [`CircuitBreaker::window`] must return the
32510        // `:politicas :circuit-breaker :window` typed `Duration`
32511        // verbatim, byte-equal to the raw field access across every
32512        // representative value in the accept-set — `Duration::from_millis(1)`
32513        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
32514        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
32515        // gate carves out on the sibling `PolicyBreakerZeroWindow`
32516        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
32517        // same gate carves out on the sibling
32518        // `PolicyBreakerWindowExceedsCap` refusal),
32519        // `Duration::ZERO` (a past-the-guard sentinel that pins the
32520        // accessor doesn't perform a silent bounds-collapse into
32521        // `Duration::from_millis(1)` on the zero arm — validate rejects
32522        // zero but the accessor must ship the raw slot verbatim so a
32523        // validate-time gate regression surfaces at the emit boundary
32524        // rather than being silently absorbed),
32525        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
32526        // far above the 1h cap — that pins the accessor doesn't perform
32527        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
32528        // at the return path).
32529        //
32530        // Second sub-struct required-scalar accessor pin on the M3
32531        // mesh-slot family — sibling in shape to the just-landed
32532        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
32533        // (3a74062) required-`u32` accessor pin on the peer
32534        // per-`CircuitBreaker` required-axis, extended onto the
32535        // per-sub-struct required-`Duration` axis. Pins against a
32536        // future silent detour that re-derived the observation window
32537        // from a peer axis (an accidental
32538        // `Duration::from_secs(self.max_failures as u64)` collapse that
32539        // read the breaker's trip count as an observation-interval
32540        // duration), a `Duration::ZERO → Duration::from_millis(1)`
32541        // cluster-default projection (which would silently absorb the
32542        // `PolicyBreakerZeroWindow` refusal case at the accessor
32543        // boundary), or a bounds-collapsing accessor that clamped the
32544        // return through `POLICY_BREAKER_WINDOW_MAX` (the
32545        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
32546        // must ship the raw slot verbatim).
32547        for window in [
32548            Duration::from_millis(1),
32549            POLICY_BREAKER_WINDOW_MAX,
32550            Duration::ZERO,
32551            Duration::from_secs(86_400),
32552        ] {
32553            let cb = CircuitBreaker {
32554                max_failures: 5,
32555                window,
32556            };
32557            assert_eq!(
32558                cb.window(),
32559                window,
32560                "CircuitBreaker::window must return :politicas \
32561                 :circuit-breaker :window verbatim (got {:?}, \
32562                 expected {window:?})",
32563                cb.window(),
32564            );
32565            assert_eq!(
32566                cb.window(),
32567                cb.window,
32568                "CircuitBreaker::window must byte-equal the raw \
32569                 .window field access across every value in the \
32570                 Duration accept-set",
32571            );
32572        }
32573    }
32574
32575    #[test]
32576    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
32577        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
32578        // `:circuit-breaker :window` zero-floor arm must key off
32579        // [`CircuitBreaker::window`], not the raw `.window` field
32580        // access. Structurally: a `CircuitBreaker { window:
32581        // Duration::ZERO, .. }` embedded in a
32582        // `:politicas :circuit-breaker` slot must surface the
32583        // `PolicyBreakerZeroWindow` refusal exactly, and a
32584        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
32585        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
32586        // accept-set) must pass validate. The pair jointly pins the
32587        // accessor + validate-gate composition: any future silent
32588        // detour that had the accessor return a fresh
32589        // `Duration::from_millis(1)` on the zero arm (a
32590        // `.window().max(Duration::from_millis(1))` collapse) would
32591        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
32592        // accessor boundary and the validate gate would accept a
32593        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
32594        // — the composition pin catches that at caixa-core build time.
32595        //
32596        // Peer of the sibling per-`CircuitBreaker`
32597        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
32598        // pin on the peer required-scalar `:max-failures` axis — same
32599        // "the validate / shape-gate predicate must route through the
32600        // substrate-primitive typed dispatch" discipline extended onto
32601        // the peer per-`CircuitBreaker` required-`Duration` composition
32602        // axis.
32603        let mut spec = three_member_spec();
32604        spec.politicas = MeshPolicy {
32605            circuit_breaker: Some(CircuitBreaker {
32606                max_failures: 5,
32607                window: Duration::ZERO,
32608            }),
32609            ..MeshPolicy::default()
32610        };
32611        assert!(
32612            matches!(
32613                spec.validate(),
32614                Err(AplicacaoError::PolicyBreakerZeroWindow)
32615            ),
32616            "validate_politicas must reject window == Duration::ZERO \
32617             with PolicyBreakerZeroWindow — the accessor and the \
32618             validate gate must route through the same substrate-\
32619             primitive typed dispatch on the :window zero-floor arm",
32620        );
32621        spec.politicas = MeshPolicy {
32622            circuit_breaker: Some(CircuitBreaker {
32623                max_failures: 5,
32624                window: Duration::from_millis(1),
32625            }),
32626            ..MeshPolicy::default()
32627        };
32628        assert!(
32629            spec.validate().is_ok(),
32630            "validate_politicas must accept window == \
32631             Duration::from_millis(1) (the lower boundary of the \
32632             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
32633        );
32634    }
32635
32636    #[test]
32637    fn circuit_breaker_window_projects_duration_by_copy() {
32638        // The by-copy pin: [`CircuitBreaker::window`] returns
32639        // `Duration` by copy — `Duration` is `Copy` and the accessor
32640        // must return by value, not by reference. Peer of the sibling
32641        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
32642        // (3a74062) by-copy pin on the peer required-scalar
32643        // `:max-failures` axis, extended onto the peer
32644        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
32645        // — the accessor's returned `Duration` must outlive `&self`
32646        // (multiple calls must return equal values from a
32647        // dropped-`&self` copy, since the returned scalar carries no
32648        // borrow), and calling the accessor twice on the same
32649        // CircuitBreaker must yield the same `Duration` verbatim
32650        // (idempotent, no side effects on `&self`).
32651        //
32652        // Pins against a future silent detour that returned
32653        // `&Duration` (which would type-check but silently break every
32654        // downstream `Duration`-by-value consumer —
32655        // [`crate::render::require_positive_canonical_bounded_duration`]'s
32656        // first parameter is `Duration`, and `&Duration` would fold to
32657        // a detached copy at the call site with a `*` deref the sibling
32658        // accessors don't need), an accidental `.window + Duration::ZERO`
32659        // detour that returned a fresh copy through an arithmetic
32660        // no-op (breaking a future `const fn` regression), or a
32661        // one-arm-only accessor that returned a saturating value on
32662        // some sentinel input (breaking the pass-through invariant the
32663        // sibling required-scalar accessors carry).
32664        for window in [
32665            Duration::from_millis(1),
32666            POLICY_BREAKER_WINDOW_MAX,
32667            Duration::ZERO,
32668            Duration::from_secs(86_400),
32669        ] {
32670            let cb = CircuitBreaker {
32671                max_failures: 5,
32672                window,
32673            };
32674            let first = cb.window();
32675            let second = cb.window();
32676            assert_eq!(
32677                first, second,
32678                "CircuitBreaker::window must be idempotent — two \
32679                 successive calls on the same &self must return the \
32680                 same Duration",
32681            );
32682            assert_eq!(
32683                first, window,
32684                "CircuitBreaker::window must return :politicas \
32685                 :circuit-breaker :window verbatim by copy — \
32686                 got {first:?}, expected {window:?}",
32687            );
32688        }
32689    }
32690
32691    #[test]
32692    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
32693        // Apex-identity pair-invariant pin composing both substrate-
32694        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
32695        // and [`WitContract::destination`] — at the emit-side call shape
32696        // every per-`(:de, :para)` CNP L4 port reader now takes. The
32697        // invariant, evaluated per-edge:
32698        //
32699        //   spec.port_for_destination(c.destination()) == expected_port
32700        //
32701        // where `expected_port` is `entrada.port` when
32702        // `c.destination() == entrada.destination()` and
32703        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
32704        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
32705        // pin on the per-`:entrada` axis — that pin encodes the apex
32706        // ingress L4 identity via `entrada.destination()`; this pin
32707        // encodes the per-edge L4 identity via `c.destination()`, and
32708        // both compose on the same substrate-primitive resolver so a
32709        // future refactor that silently split either accessor's apex
32710        // behavior surfaces at caixa-core build time.
32711        let mut spec = three_member_spec();
32712        if let Some(e) = spec.entrada.as_mut() {
32713            e.para = "cart".into();
32714            e.port = 8443;
32715        }
32716        let apex_contract = WitContract {
32717            de: "checkout".into(),
32718            para: "cart".into(),
32719            wit: "wasi:http/proxy".into(),
32720            endpoint: Some("/hello".into()),
32721            subject: None,
32722            slot: None,
32723        };
32724        assert_eq!(
32725            spec.port_for_destination(apex_contract.destination()),
32726            8443,
32727            "`spec.port_for_destination(c.destination())` must equal \
32728             `entrada.port` when the contract callee names the ingress \
32729             apex — the CNP per-edge L4 port and the HTTPRoute apex \
32730             backendRef port share this substrate-primitive resolver.",
32731        );
32732        let non_apex_contract = WitContract {
32733            de: "cart".into(),
32734            para: "payment".into(),
32735            wit: "wasi:http/proxy".into(),
32736            endpoint: Some("/charge".into()),
32737            subject: None,
32738            slot: None,
32739        };
32740        assert_eq!(
32741            spec.port_for_destination(non_apex_contract.destination()),
32742            DEFAULT_SERVICO_PORT,
32743            "`spec.port_for_destination(c.destination())` must fall back \
32744             to the substrate-canonical port floor when the contract \
32745             callee is not the ingress apex — the resolver's non-apex \
32746             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
32747        );
32748    }
32749
32750    #[test]
32751    fn membro_key_consts_are_lower_camel_case_shape() {
32752        // Shape-pin: every `MEMBRO_KEY_*` const must be a
32753        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
32754        // `kebab-case` hyphens, no leading colon, no `PascalCase`
32755        // leading capital, no whitespace / dots) — the canonical shape
32756        // the `#[serde(rename_all = "camelCase")]` derive produces on
32757        // [`Membro`]. A future flip to a non-camelCase attribute at
32758        // the derive surfaces both here (this test fails on the
32759        // stale-constant shape) and at
32760        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
32761        // fails on the mismatch between const and derive). Peer with
32762        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
32763        // on the sibling `SupervisorSpec` top-level axis.
32764        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
32765            assert!(
32766                !key.is_empty(),
32767                "MEMBRO_KEY_* must be non-empty (got {key:?})"
32768            );
32769            let first = key.chars().next().unwrap();
32770            assert!(
32771                first.is_ascii_lowercase(),
32772                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
32773                 (got {key:?}, leads with {first:?})",
32774            );
32775            assert!(
32776                key.chars().all(|c| c.is_ascii_alphanumeric()),
32777                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
32778                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
32779            );
32780        }
32781    }
32782
32783    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
32784
32785    #[test]
32786    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
32787        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
32788        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
32789        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
32790        // keys the `#[serde(rename_all = "camelCase")]` attribute on
32791        // [`WitContract`] emits for the required-triad. The three
32792        // sibling payload-arm keys already pin under
32793        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
32794        // `STORE_FIELD_NAME` — pin all six alongside so a future
32795        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
32796        // verbatim-field-name flip at the derive attribute (any of which
32797        // would silently break every downstream JSON consumer that
32798        // reaches for one of the six via `Value::get(...)`) surfaces
32799        // here as a build-time test failure at `aplicacao.rs`, not as an
32800        // apply-time `.get(<stale-canonical-const>)` returning `None`
32801        // far from the derive-attr drift's commit. Peer with the sibling
32802        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
32803        // pin on the M3 `:membros` per-entry axis — same discipline the
32804        // `Membro` per-entry lift established, extended here to the
32805        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
32806        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
32807        // axis on the Aplicacao surface without a lifted serde-key peer.
32808        let c = WitContract {
32809            de: "cart".into(),
32810            para: "catalog".into(),
32811            wit: "wasi:http/proxy".into(),
32812            endpoint: Some("/lookup".into()),
32813            subject: None,
32814            slot: None,
32815        };
32816        let json = serde_json::to_string(&c).unwrap();
32817        for key in [
32818            crate::CONTRATO_KEY_DE,
32819            crate::CONTRATO_KEY_PARA,
32820            crate::CONTRATO_KEY_WIT,
32821            WitTarget::HTTP_FIELD_NAME,
32822        ] {
32823            let quoted = format!("\"{key}\"");
32824            assert!(
32825                json.contains(&quoted),
32826                "serialized WitContract must carry the lifted \
32827                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
32828                 {quoted} verbatim in the JSON emission (got: {json})",
32829            );
32830        }
32831
32832        // Pin the two remaining payload-arm keys by round-tripping a
32833        // `WitContract` under each payload-shape (pub-sub, store) — the
32834        // required-triad appears on every emission but the payload arms
32835        // only surface when their `Option<String>` field is `Some`.
32836        let pubsub = WitContract {
32837            de: "cart".into(),
32838            para: "events".into(),
32839            wit: "nats:pub-sub".into(),
32840            endpoint: None,
32841            subject: Some("orders.placed".into()),
32842            slot: None,
32843        };
32844        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
32845        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
32846        assert!(
32847            pubsub_json.contains(&pubsub_quoted),
32848            "serialized pub-sub WitContract must carry the lifted \
32849             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
32850             verbatim in the JSON emission (got: {pubsub_json})",
32851        );
32852        let store = WitContract {
32853            de: "cart".into(),
32854            para: "sessions".into(),
32855            wit: "wasi:keyvalue/store".into(),
32856            endpoint: None,
32857            subject: None,
32858            slot: Some("cart/$id".into()),
32859        };
32860        let store_json = serde_json::to_string(&store).unwrap();
32861        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
32862        assert!(
32863            store_json.contains(&store_quoted),
32864            "serialized store WitContract must carry the lifted \
32865             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
32866             verbatim in the JSON emission (got: {store_json})",
32867        );
32868    }
32869
32870    #[test]
32871    fn contrato_key_consts_are_pairwise_distinct() {
32872        // Cross-axis drift-detection pin: a future collapse of the six
32873        // canonical [`WitContract`] per-entry byte-strings onto the same
32874        // value (e.g. an accidental copy-paste flip of
32875        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
32876        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
32877        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
32878        // every downstream probe on one axis onto the sibling axis's
32879        // overlay entry and pass every propagation-probe test that
32880        // expected only the stale axis's value. Peer of the sibling
32881        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
32882        // widened here to the six-way axis the `WitContract`
32883        // required-triad + `WitTarget` payload-triad jointly cover.
32884        let all = [
32885            crate::CONTRATO_KEY_DE,
32886            crate::CONTRATO_KEY_PARA,
32887            crate::CONTRATO_KEY_WIT,
32888            WitTarget::HTTP_FIELD_NAME,
32889            WitTarget::PUBSUB_FIELD_NAME,
32890            WitTarget::STORE_FIELD_NAME,
32891        ];
32892        for (i, a) in all.iter().enumerate() {
32893            for b in all.iter().skip(i + 1) {
32894                assert_ne!(
32895                    a, b,
32896                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
32897                     must be pairwise-distinct canonical byte-sequences \
32898                     — got `{a}` == `{b}`",
32899                );
32900            }
32901        }
32902    }
32903
32904    #[test]
32905    fn contrato_key_consts_are_lower_camel_case_shape() {
32906        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
32907        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
32908        // byte-sequence (no `snake_case` underscores, no `kebab-case`
32909        // hyphens, no leading colon, no `PascalCase` leading capital, no
32910        // whitespace / dots) — the canonical shape the
32911        // `#[serde(rename_all = "camelCase")]` derive produces on
32912        // [`WitContract`]. A future flip to a non-camelCase attribute at
32913        // the derive surfaces both here (this test fails on the
32914        // stale-constant shape) and at
32915        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
32916        // (that test fails on the mismatch between const and derive).
32917        // Peer with `membro_key_consts_are_lower_camel_case_shape`
32918        // (ce80ca0) on the sibling `Membro` per-entry axis.
32919        for key in [
32920            crate::CONTRATO_KEY_DE,
32921            crate::CONTRATO_KEY_PARA,
32922            crate::CONTRATO_KEY_WIT,
32923            WitTarget::HTTP_FIELD_NAME,
32924            WitTarget::PUBSUB_FIELD_NAME,
32925            WitTarget::STORE_FIELD_NAME,
32926        ] {
32927            assert!(
32928                !key.is_empty(),
32929                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
32930                 non-empty (got {key:?})"
32931            );
32932            let first = key.chars().next().unwrap();
32933            assert!(
32934                first.is_ascii_lowercase(),
32935                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
32936                 with an ASCII-lowercase byte (got {key:?}, leads with \
32937                 {first:?})",
32938            );
32939            assert!(
32940                key.chars().all(|c| c.is_ascii_alphanumeric()),
32941                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
32942                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
32943                 whitespace (got {key:?})",
32944            );
32945        }
32946    }
32947
32948    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
32949
32950    #[test]
32951    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
32952        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
32953        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
32954        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
32955        // name the exact camelCase JSON keys the
32956        // `#[serde(rename_all = "camelCase")]` attribute on
32957        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
32958        // pin that each canonical byte-sequence appears verbatim in the
32959        // JSON — a future accidental `rename_all = "snake_case"` /
32960        // `"kebab-case"` / verbatim-field-name flip at the derive
32961        // attribute (any of which would silently break every downstream
32962        // JSON consumer that reaches for one of the four consts via
32963        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
32964        // emitter's per-Aplicacao hostname/paths/port projection, the
32965        // future `app-operator` reconciler's per-Aplicacao ingress
32966        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
32967        // materializer's admission-time cross-check) surfaces here as
32968        // a build-time test failure at `aplicacao.rs`, not as an
32969        // apply-time `.get(<stale-canonical-const>)` returning `None`
32970        // far from the derive-attr drift's commit. Peer with the
32971        // sibling
32972        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
32973        // (ca463a4) and
32974        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
32975        // pins on the M3 collection-slot atom axes — same discipline
32976        // both collection-slot lifts established, extended here to the
32977        // singleton `:entrada` mesh-slot atom axis, the last M3
32978        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
32979        // axis on the Aplicacao surface without a lifted serde-key
32980        // peer.
32981        let e = Entrada {
32982            host: "checkout.quero.cloud".into(),
32983            para: "cart".into(),
32984            paths: vec!["/cart".into()],
32985            port: 8080,
32986        };
32987        let json = serde_json::to_string(&e).unwrap();
32988        for key in [
32989            crate::ENTRADA_KEY_HOST,
32990            crate::ENTRADA_KEY_PARA,
32991            crate::ENTRADA_KEY_PATHS,
32992            crate::ENTRADA_KEY_PORT,
32993        ] {
32994            let quoted = format!("\"{key}\"");
32995            assert!(
32996                json.contains(&quoted),
32997                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
32998                 byte-sequence {quoted} verbatim in the JSON emission \
32999                 (got: {json})",
33000            );
33001        }
33002    }
33003
33004    #[test]
33005    fn entrada_key_consts_are_pairwise_distinct() {
33006        // Cross-axis drift-detection pin: a future collapse of the four
33007        // canonical [`Entrada`] singleton byte-strings onto the same
33008        // value (e.g. an accidental copy-paste flip of
33009        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
33010        // silently reroute every downstream probe on one axis onto the
33011        // sibling axis's overlay entry and pass every propagation-probe
33012        // test that expected only the stale axis's value — the
33013        // Gateway/HTTPRoute emitter would read the hostname string
33014        // where the destination-Servico name was expected (or vice
33015        // versa), the admission-webhook cross-check would compare the
33016        // wrong pair of values, and the resulting Gateway resource
33017        // would either be admitted with garbage or rejected at the
33018        // controller far from the rebrand commit's source. Peer of the
33019        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
33020        // tetrad (40cc4e5), the two-way distinct pin on the
33021        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
33022        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
33023        // triad (ca463a4).
33024        let all = [
33025            crate::ENTRADA_KEY_HOST,
33026            crate::ENTRADA_KEY_PARA,
33027            crate::ENTRADA_KEY_PATHS,
33028            crate::ENTRADA_KEY_PORT,
33029        ];
33030        for (i, a) in all.iter().enumerate() {
33031            for b in all.iter().skip(i + 1) {
33032                assert_ne!(
33033                    a, b,
33034                    "ENTRADA_KEY_* consts must be pairwise-distinct \
33035                     canonical byte-sequences — got `{a}` == `{b}`",
33036                );
33037            }
33038        }
33039    }
33040
33041    #[test]
33042    fn entrada_key_consts_are_lower_camel_case_shape() {
33043        // Shape-pin: every `ENTRADA_KEY_*` const must be a
33044        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
33045        // `kebab-case` hyphens, no leading colon, no `PascalCase`
33046        // leading capital, no whitespace / dots) — the canonical shape
33047        // the `#[serde(rename_all = "camelCase")]` derive produces on
33048        // [`Entrada`]. A future flip to a non-camelCase attribute at
33049        // the derive surfaces both here (this test fails on the
33050        // stale-constant shape) and at
33051        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
33052        // test fails on the mismatch between const and derive). Peer
33053        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
33054        // and `contrato_key_consts_are_lower_camel_case_shape`
33055        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
33056        // entry axes.
33057        for key in [
33058            crate::ENTRADA_KEY_HOST,
33059            crate::ENTRADA_KEY_PARA,
33060            crate::ENTRADA_KEY_PATHS,
33061            crate::ENTRADA_KEY_PORT,
33062        ] {
33063            assert!(
33064                !key.is_empty(),
33065                "ENTRADA_KEY_* must be non-empty (got {key:?})"
33066            );
33067            let first = key.chars().next().unwrap();
33068            assert!(
33069                first.is_ascii_lowercase(),
33070                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
33071                 (got {key:?}, leads with {first:?})",
33072            );
33073            assert!(
33074                key.chars().all(|c| c.is_ascii_alphanumeric()),
33075                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
33076                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
33077            );
33078        }
33079    }
33080
33081    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
33082
33083    #[test]
33084    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
33085        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
33086        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
33087        // [`crate::POLITICAS_KEY_RETRIES`] /
33088        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
33089        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
33090        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
33091        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
33092        // on [`MeshPolicy`] emits. Three of the five axes
33093        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
33094        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
33095        // camelCase transforms — the derive-attribute is load-bearing
33096        // on those, unlike the sibling `Entrada` / `Membro` /
33097        // `WitContract` structs whose fields are all lowercase-single-
33098        // word and where the derive is a no-op on every axis.
33099        // Serialize a fully-populated [`MeshPolicy`] (every axis
33100        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
33101        // on none of the five slots) and pin that each canonical
33102        // byte-sequence appears verbatim in the JSON — a future
33103        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
33104        // verbatim-field-name flip at the derive attribute (any of
33105        // which would silently break every downstream JSON consumer
33106        // that reaches for one of the five consts via
33107        // `Value::get(...)` — the future M4 per-edge `:politicas`
33108        // overlay projection onto Cilium `L7Rules` and Gateway API
33109        // `HTTPRoute` backend timeouts, the future
33110        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
33111        // admission-time mesh-policy cross-check, the future
33112        // `feira lint` per-`:politicas` bound-check gate) surfaces here
33113        // as a build-time test failure at `aplicacao.rs`, not as an
33114        // apply-time `.get(<stale-canonical-const>)` returning `None`
33115        // far from the derive-attr drift's commit. Peer with the
33116        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
33117        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
33118        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
33119        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
33120        // atom axes — same discipline every M3 sibling lift
33121        // established, extended here to the singleton `:politicas`
33122        // mesh-slot atom axis, closing the last M3 typed-struct
33123        // top-level `#[serde(rename_all = "camelCase")]` axis on the
33124        // Aplicacao surface without a lifted serde-key peer.
33125        let p = MeshPolicy {
33126            timeout: Some(Duration::from_secs(30)),
33127            retries: Some(3),
33128            circuit_breaker: Some(CircuitBreaker {
33129                max_failures: 5,
33130                window: Duration::from_secs(60),
33131            }),
33132            mtls_required: Some(true),
33133            rate_limit: Some(RateLimit {
33134                rate: 100,
33135                window: Duration::from_secs(1),
33136            }),
33137        };
33138        let json = serde_json::to_string(&p).unwrap();
33139        for key in [
33140            crate::POLITICAS_KEY_TIMEOUT,
33141            crate::POLITICAS_KEY_RETRIES,
33142            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
33143            crate::POLITICAS_KEY_MTLS_REQUIRED,
33144            crate::POLITICAS_KEY_RATE_LIMIT,
33145        ] {
33146            let quoted = format!("\"{key}\"");
33147            assert!(
33148                json.contains(&quoted),
33149                "serialized MeshPolicy must carry the lifted \
33150                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
33151                 JSON emission (got: {json})",
33152            );
33153        }
33154    }
33155
33156    #[test]
33157    fn politicas_key_consts_are_pairwise_distinct() {
33158        // Cross-axis drift-detection pin: a future collapse of the five
33159        // canonical [`MeshPolicy`] singleton byte-strings onto the same
33160        // value (e.g. an accidental copy-paste flip of
33161        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
33162        // would silently reroute every downstream probe on one axis
33163        // onto the sibling axis's overlay entry and pass every
33164        // propagation-probe test that expected only the stale axis's
33165        // value — the M4 per-edge `:politicas` overlay projection would
33166        // read the retry-count string where the timeout duration was
33167        // expected (or vice versa), the CR materializer's admission
33168        // cross-check would compare the wrong pair of values, and the
33169        // resulting mesh reconciler would either bind the wrong axis
33170        // or reject the resource at reconcile far from the rebrand
33171        // commit's source. Peer of the sibling four-way distinct pin
33172        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
33173        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
33174        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
33175        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
33176        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
33177        let all = [
33178            crate::POLITICAS_KEY_TIMEOUT,
33179            crate::POLITICAS_KEY_RETRIES,
33180            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
33181            crate::POLITICAS_KEY_MTLS_REQUIRED,
33182            crate::POLITICAS_KEY_RATE_LIMIT,
33183        ];
33184        for (i, a) in all.iter().enumerate() {
33185            for b in all.iter().skip(i + 1) {
33186                assert_ne!(
33187                    a, b,
33188                    "POLITICAS_KEY_* consts must be pairwise-distinct \
33189                     canonical byte-sequences — got `{a}` == `{b}`",
33190                );
33191            }
33192        }
33193    }
33194
33195    #[test]
33196    fn politicas_key_consts_are_lower_camel_case_shape() {
33197        // Shape-pin: every `POLITICAS_KEY_*` const must be a
33198        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
33199        // `kebab-case` hyphens, no leading colon, no `PascalCase`
33200        // leading capital, no whitespace / dots) — the canonical shape
33201        // the `#[serde(rename_all = "camelCase")]` derive produces on
33202        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
33203        // at the derive surfaces both here (this test fails on the
33204        // stale-constant shape) and at
33205        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
33206        // (that test fails on the mismatch between const and derive).
33207        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
33208        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
33209        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
33210        // (ca463a4) on the sibling M3 typed-struct axes.
33211        for key in [
33212            crate::POLITICAS_KEY_TIMEOUT,
33213            crate::POLITICAS_KEY_RETRIES,
33214            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
33215            crate::POLITICAS_KEY_MTLS_REQUIRED,
33216            crate::POLITICAS_KEY_RATE_LIMIT,
33217        ] {
33218            assert!(
33219                !key.is_empty(),
33220                "POLITICAS_KEY_* must be non-empty (got {key:?})"
33221            );
33222            let first = key.chars().next().unwrap();
33223            assert!(
33224                first.is_ascii_lowercase(),
33225                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
33226                 byte (got {key:?}, leads with {first:?})",
33227            );
33228            assert!(
33229                key.chars().all(|c| c.is_ascii_alphanumeric()),
33230                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
33231                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
33232            );
33233        }
33234    }
33235
33236    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
33237
33238    #[test]
33239    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
33240        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
33241        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
33242        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
33243        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
33244        // [`CircuitBreaker`] emits inside the
33245        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
33246        // two axes (`max_failures` → `maxFailures`) is a non-trivial
33247        // camelCase transform — the derive-attribute is load-bearing on
33248        // that axis, unlike the sibling `window` field where the derive
33249        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
33250        // pin that each canonical byte-sequence appears verbatim in the
33251        // JSON — a future accidental `rename_all = "snake_case"` /
33252        // `"kebab-case"` / verbatim-field-name flip at the derive
33253        // attribute (any of which would silently break every downstream
33254        // JSON consumer that reaches for one of the two consts via
33255        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
33256        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
33257        // per-edge `:politicas` overlay projection onto the mesh's
33258        // per-backend consecutive-failure-counter tripping threshold, the
33259        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
33260        // admission-time breaker cross-check, the future `feira lint`
33261        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
33262        // here as a build-time test failure at `aplicacao.rs`, not as an
33263        // apply-time `.get(<stale-canonical-const>)` returning `None`
33264        // far from the derive-attr drift's commit. Peer with the sibling
33265        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
33266        // (b55cca7) parent-axis pin — that test pins the outer
33267        // sub-block key the derive on [`MeshPolicy`] emits, this test
33268        // pins the inner keys the derive on the payload type emits, so
33269        // the two together lock the whole [`MeshPolicy`] breaker-tuning
33270        // shape end-to-end at build time.
33271        let cb = CircuitBreaker {
33272            max_failures: 5,
33273            window: Duration::from_secs(60),
33274        };
33275        let json = serde_json::to_string(&cb).unwrap();
33276        for key in [
33277            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
33278            crate::CIRCUIT_BREAKER_KEY_WINDOW,
33279        ] {
33280            let quoted = format!("\"{key}\"");
33281            assert!(
33282                json.contains(&quoted),
33283                "serialized CircuitBreaker must carry the lifted \
33284                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
33285                 in the JSON emission (got: {json})",
33286            );
33287        }
33288    }
33289
33290    #[test]
33291    fn circuit_breaker_key_consts_are_pairwise_distinct() {
33292        // Cross-axis drift-detection pin: a future collapse of the two
33293        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
33294        // same value (e.g. an accidental copy-paste flip of
33295        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
33296        // `"maxFailures"`) would silently reroute every downstream
33297        // probe on one axis onto the sibling axis's overlay entry and
33298        // pass every propagation-probe test that expected only the
33299        // stale axis's value — the M4 per-edge `:politicas` overlay
33300        // projection would read the failure-count where the window
33301        // duration was expected (or vice versa), the CR materializer's
33302        // admission cross-check would compare the wrong pair of values,
33303        // and the resulting mesh reconciler would either bind the wrong
33304        // axis or reject the resource at reconcile far from the rebrand
33305        // commit's source. Peer of the sibling five-way distinct pin on
33306        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
33307        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
33308        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
33309        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
33310        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
33311        let all = [
33312            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
33313            crate::CIRCUIT_BREAKER_KEY_WINDOW,
33314        ];
33315        for (i, a) in all.iter().enumerate() {
33316            for b in all.iter().skip(i + 1) {
33317                assert_ne!(
33318                    a, b,
33319                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
33320                     canonical byte-sequences — got `{a}` == `{b}`",
33321                );
33322            }
33323        }
33324    }
33325
33326    #[test]
33327    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
33328        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
33329        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
33330        // `kebab-case` hyphens, no leading colon, no `PascalCase`
33331        // leading capital, no whitespace / dots) — the canonical shape
33332        // the `#[serde(rename_all = "camelCase")]` derive produces on
33333        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
33334        // at the derive surfaces both here (this test fails on the
33335        // stale-constant shape) and at
33336        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
33337        // (that test fails on the mismatch between const and derive).
33338        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
33339        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
33340        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
33341        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
33342        // (ca463a4) on the sibling M3 typed-struct axes.
33343        for key in [
33344            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
33345            crate::CIRCUIT_BREAKER_KEY_WINDOW,
33346        ] {
33347            assert!(
33348                !key.is_empty(),
33349                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
33350            );
33351            let first = key.chars().next().unwrap();
33352            assert!(
33353                first.is_ascii_lowercase(),
33354                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
33355                 byte (got {key:?}, leads with {first:?})",
33356            );
33357            assert!(
33358                key.chars().all(|c| c.is_ascii_alphanumeric()),
33359                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
33360                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
33361            );
33362        }
33363    }
33364
33365    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
33366
33367    #[test]
33368    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
33369        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
33370        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
33371        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
33372        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
33373        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
33374        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
33375        // [`Placement`] emits. One of the four axes (`shard_key` →
33376        // `shardKey`) is a non-trivial camelCase transform — the
33377        // derive-attribute is load-bearing on that axis, unlike the
33378        // sibling `estrategia` / `clusters` / `affinity` axes whose
33379        // source-side field names carry no `_` and where the derive is a
33380        // no-op. Serialize a fully-populated [`Placement`] (both
33381        // `Option`-carrying axes `Some(_)` so
33382        // `skip_serializing_if = "Option::is_none"` fires on neither of
33383        // the two optional slots) and pin that each canonical
33384        // byte-sequence appears verbatim in the JSON — a future
33385        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
33386        // verbatim-field-name flip at the derive attribute (any of which
33387        // would silently break every downstream consumer that reaches
33388        // for one of the four consts via
33389        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
33390        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
33391        // aggregator's per-cluster fanout filter keying off
33392        // `placement.clusters`, the M3 shard-pool dispatch materializer
33393        // keying off `placement.shardKey`, the M3 Adaptive compression
33394        // pass weighting off `placement.affinity`, every downstream
33395        // dispatcher branching on `placement.estrategia`, the future
33396        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
33397        // admission-time placement cross-check, the future `feira lint`
33398        // per-`:placement` bound-check gate) surfaces here as a
33399        // build-time test failure at `aplicacao.rs`, not as an
33400        // apply-time `.get(<stale-canonical-const>)` returning `None`
33401        // far from the derive-attr drift's commit. Peer with the sibling
33402        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
33403        // (b55cca7),
33404        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
33405        // (468e959),
33406        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
33407        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
33408        // (ca463a4), and
33409        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
33410        // pins on the M3 collection-slot / singleton-slot atom axes —
33411        // closes the last M3 typed-struct top-level
33412        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
33413        // surface without a drift-detection pin.
33414        let p = Placement {
33415            estrategia: PlacementStrategy::Sharded,
33416            clusters: vec!["rio".into(), "mar".into()],
33417            affinity: Some("data-locality".into()),
33418            shard_key: Some("$tenantId".into()),
33419        };
33420        let json = serde_json::to_string(&p).unwrap();
33421        for key in [
33422            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
33423            crate::M3_PLACEMENT_KEY_CLUSTERS,
33424            crate::M3_PLACEMENT_KEY_AFFINITY,
33425            crate::M3_PLACEMENT_KEY_SHARD_KEY,
33426        ] {
33427            let quoted = format!("\"{key}\"");
33428            assert!(
33429                json.contains(&quoted),
33430                "serialized Placement must carry the lifted \
33431                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
33432                 the JSON emission (got: {json})",
33433            );
33434        }
33435    }
33436
33437    #[test]
33438    fn m3_placement_key_consts_are_pairwise_distinct() {
33439        // Cross-axis drift-detection pin: a future collapse of the four
33440        // canonical [`Placement`] sub-block byte-strings onto the same
33441        // value (e.g. an accidental copy-paste flip of
33442        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
33443        // `"affinity"`) would silently reroute every downstream probe on
33444        // one axis onto the sibling axis's overlay entry and pass every
33445        // propagation-probe test that expected only the stale axis's
33446        // value — the M3 shard-pool dispatch materializer would read the
33447        // affinity placement-hint where the shard-selection template was
33448        // expected (or vice versa), the M3 Adaptive compression pass's
33449        // cross-check would compare the wrong pair of values, and the
33450        // resulting placement engine would either bind the wrong axis or
33451        // reject the resource at reconcile far from the rebrand commit's
33452        // source. Peer of the sibling two-way distinct pin on the
33453        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
33454        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
33455        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
33456        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
33457        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
33458        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
33459        let all = [
33460            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
33461            crate::M3_PLACEMENT_KEY_CLUSTERS,
33462            crate::M3_PLACEMENT_KEY_AFFINITY,
33463            crate::M3_PLACEMENT_KEY_SHARD_KEY,
33464        ];
33465        for (i, a) in all.iter().enumerate() {
33466            for b in all.iter().skip(i + 1) {
33467                assert_ne!(
33468                    a, b,
33469                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
33470                     canonical byte-sequences — got `{a}` == `{b}`",
33471                );
33472            }
33473        }
33474    }
33475
33476    #[test]
33477    fn m3_placement_key_consts_are_lower_camel_case_shape() {
33478        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
33479        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
33480        // `kebab-case` hyphens, no leading colon, no `PascalCase`
33481        // leading capital, no whitespace / dots) — the canonical shape
33482        // the `#[serde(rename_all = "camelCase")]` derive produces on
33483        // [`Placement`]. A future flip to a non-camelCase attribute at
33484        // the derive surfaces both here (this test fails on the stale-
33485        // constant shape) and at
33486        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
33487        // (that test fails on the mismatch between const and derive).
33488        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
33489        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
33490        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
33491        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
33492        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
33493        // (ca463a4) on the sibling M3 typed-struct axes.
33494        for key in [
33495            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
33496            crate::M3_PLACEMENT_KEY_CLUSTERS,
33497            crate::M3_PLACEMENT_KEY_AFFINITY,
33498            crate::M3_PLACEMENT_KEY_SHARD_KEY,
33499        ] {
33500            assert!(
33501                !key.is_empty(),
33502                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
33503            );
33504            let first = key.chars().next().unwrap();
33505            assert!(
33506                first.is_ascii_lowercase(),
33507                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
33508                 byte (got {key:?}, leads with {first:?})",
33509            );
33510            assert!(
33511                key.chars().all(|c| c.is_ascii_alphanumeric()),
33512                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
33513                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
33514            );
33515        }
33516    }
33517
33518    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
33519    //    destination-facing L4 port resolver every per-Aplicacao renderer
33520    //    reaching for a per-destination Servico TCP port axis routes
33521    //    through. The four pin tests below fix the four-way accept-set
33522    //    the resolver must always honor: (:entrada-para-matches,
33523    //    :entrada-para-mismatches, :entrada-none-so-fallback,
33524    //    :entrada-port-non-default-honored) — drift on any arm surfaces
33525    //    at caixa-core build time rather than at cluster-apply time.
33526
33527    #[test]
33528    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
33529        // The typed `:entrada` block's `:para "cart"` matches the
33530        // queried destination, so the resolver returns the author-
33531        // declared `:port` scalar verbatim — the canonical "the
33532        // destination Servico IS the ingress apex, honor the typed
33533        // listener port" arm of the port-resolution dispatch.
33534        let mut spec = three_member_spec();
33535        if let Some(e) = spec.entrada.as_mut() {
33536            e.para = "cart".into();
33537            e.port = 9090;
33538        }
33539        assert_eq!(
33540            spec.port_for_destination("cart"),
33541            9090,
33542            "port_for_destination(entrada.para) must return entrada.port \
33543             verbatim, not the DEFAULT_SERVICO_PORT fallback"
33544        );
33545    }
33546
33547    #[test]
33548    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
33549        // The typed `:entrada` block names `:para "cart"`, but the
33550        // queried destination is `"payment"` — a Servico that
33551        // participates in the mesh graph but is not the ingress apex.
33552        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
33553        // canonical port floor, closing the "non-apex destination reads
33554        // the substrate default" arm. Same fixture the peer
33555        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
33556        // pin at caixa-mesh exercises through the CNP emit-side path;
33557        // this pin exercises the shared underlying resolver directly.
33558        let spec = three_member_spec();
33559        assert_eq!(
33560            spec.port_for_destination("payment"),
33561            DEFAULT_SERVICO_PORT,
33562            "port_for_destination(non-apex-destination) must route \
33563             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
33564        );
33565    }
33566
33567    #[test]
33568    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
33569        // Internal-only Aplicacao — no `:entrada` block declared. Every
33570        // per-destination port query falls back to the lifted
33571        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
33572        // the Aplicacao surface admits `:entrada None` (internal mesh
33573        // with no external gateway); every downstream renderer's per-
33574        // destination port axis must still resolve to a well-defined
33575        // scalar even without an ingress apex.
33576        let mut spec = three_member_spec();
33577        spec.entrada = None;
33578        assert_eq!(
33579            spec.port_for_destination("cart"),
33580            DEFAULT_SERVICO_PORT,
33581            "port_for_destination on an internal-only Aplicacao must \
33582             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
33583             every destination"
33584        );
33585        assert_eq!(
33586            spec.port_for_destination("payment"),
33587            DEFAULT_SERVICO_PORT,
33588            "port_for_destination on an internal-only Aplicacao must \
33589             fall back uniformly across every destination — the fallback \
33590             is not entrada-shape-conditional"
33591        );
33592    }
33593
33594    #[test]
33595    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
33596        // Structural pin against a hypothetical future refactor that
33597        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
33598        // the resolver (a "normalize to the default when the author's
33599        // port matches the substrate default" collapse) — that would
33600        // break renderer sites that carry meaning on the emitted port
33601        // value beyond bare equality (a future per-cluster listener-
33602        // audit that keys off the author-declared port, not the
33603        // resolved-with-fallback port). Pin that a non-default
33604        // entrada.port is returned verbatim so drift here surfaces at
33605        // caixa-core build time.
33606        let mut spec = three_member_spec();
33607        if let Some(e) = spec.entrada.as_mut() {
33608            e.para = "cart".into();
33609            e.port = 8443;
33610        }
33611        assert_ne!(
33612            8443, DEFAULT_SERVICO_PORT,
33613            "test fixture must probe a port distinct from \
33614             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
33615        );
33616        assert_eq!(
33617            spec.port_for_destination("cart"),
33618            8443,
33619            "port_for_destination(entrada.para) must return entrada.port \
33620             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
33621        );
33622    }
33623
33624    #[test]
33625    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
33626        // Apex-identity pair-invariant pin composing both substrate-
33627        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
33628        // and [`Entrada::destination`] — at the emit-side call shape
33629        // every per-Aplicacao renderer's ingress-apex L4 port reader
33630        // now takes. The invariant:
33631        //
33632        //   spec.port_for_destination(entrada.destination()) == entrada.port
33633        //
33634        // holds by construction under today's single-destination
33635        // `:entrada` slot (`destination()` returns `entrada.para`, and
33636        // the resolver's apex arm matches `para == destination` and
33637        // returns `entrada.port`), and every downstream consumer that
33638        // composes the two accessors at the ingress apex — the
33639        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
33640        // `backendRefs[0].port` emit-site path, the peer future M4 CR
33641        // materializer's admission-webhook that promotes the scalar to
33642        // a per-CR override overlay, every future per-Aplicacao snapshot
33643        // renderer's apex-facing L4 port reader — reaches through the
33644        // same composition. Pin the identity across four permutations
33645        // (`:para` × `:port` including a non-default port to exercise
33646        // the honor-verbatim arm and a non-cart `:para` to exercise
33647        // destination-agnostic identity) so a future refactor that
33648        // silently split either accessor's apex behavior surfaces at
33649        // caixa-core build time — a subtle `destination()` renaming
33650        // that returned `entrada.host.as_str()` instead of
33651        // `entrada.para.as_str()` would blow this pin loudly, closing
33652        // the last quiet failure mode the two lifts admit in composition.
33653        //
33654        // Peer discipline with the sibling caixa-mesh cross-crate pin
33655        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
33656        // on the two-renderer pair-invariant axis; this pin encodes the
33657        // same two-consumer coherence rule at the substrate-primitive
33658        // level so the invariant survives even if every renderer is
33659        // deleted.
33660        for (para, port) in [
33661            ("cart", DEFAULT_SERVICO_PORT),
33662            ("cart", 8443u16),
33663            ("payment", 9090u16),
33664            ("catalog", 443u16),
33665        ] {
33666            let mut spec = three_member_spec();
33667            if let Some(e) = spec.entrada.as_mut() {
33668                e.para = para.into();
33669                e.port = port;
33670            }
33671            let expected_port = spec
33672                .entrada()
33673                .expect("three_member_spec carries a typed `:entrada` block")
33674                .port();
33675            let composed_port = {
33676                let entrada = spec.entrada().expect("entrada present");
33677                spec.port_for_destination(entrada.destination())
33678            };
33679            assert_eq!(
33680                composed_port, expected_port,
33681                "`spec.port_for_destination(entrada.destination())` must \
33682                 equal `entrada.port` under today's single-destination \
33683                 `:entrada` slot — this is the apex-identity contract \
33684                 every downstream ingress-apex L4 port reader relies on. \
33685                 Input :entrada :para: {para:?}, :entrada :port: {port}"
33686            );
33687        }
33688    }
33689
33690    #[test]
33691    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
33692        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
33693        // per-`:entrada` apex-arm membership probe must key off
33694        // [`Entrada::destination`], not the raw `.para` field access.
33695        // Structurally: setting ONLY the `:entrada :para` field to a
33696        // fresh non-cart destination on an otherwise-well-formed
33697        // Aplicacao must (1) leave `e.destination()` byte-equal to
33698        // `e.para.as_str()` (the accessor is byte-projective by
33699        // definition), and (2) cause the resolver's apex arm to fire
33700        // and return `entrada.port` at exactly that new destination
33701        // while every other destination string falls through to
33702        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
33703        // membership check. Pins against a future silent detour that
33704        // (a) re-derived the apex-arm membership probe off
33705        // `e.para == destination` in `port_for_destination` instead of
33706        // `e.destination() == destination`, silently disagreeing with
33707        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
33708        // consumers (`entrada.destination()` at
33709        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
33710        // caixa-mesh/src/lib.rs:2739) that already reach through the
33711        // accessor, (b) accessor-side introduced a per-tenant alias
33712        // arm the caller was unaware of, silently rewriting an
33713        // author-declared `:para "cart"` value to a canary-aliased
33714        // form — the raw-field-access resolver would fall through to
33715        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
33716        // while the peer emit-site consumers landed on the aliased
33717        // destination, splitting the ingress-apex L4 port at
33718        // cluster-apply time.
33719        //
33720        // Peer of the sibling
33721        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
33722        // (d0de220) composition pin on the per-`:membros` refusal-arm
33723        // axis — same "the shape-gate predicate must route through the
33724        // substrate-primitive typed dispatch" discipline extended onto
33725        // the per-`:entrada` apex-arm membership-probe axis. Closes
33726        // the last unlifted `.para` production-code read site on
33727        // `Entrada` in `caixa-core` — after this converge every
33728        // `caixa-core` `.para` field access outside the accessor's own
33729        // body and outside the `WitContract` per-`:contratos` sibling
33730        // axis is either a test-side field-setter or a doc-comment
33731        // reference.
33732        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
33733            let mut spec = three_member_spec();
33734            if let Some(e) = spec.entrada.as_mut() {
33735                e.para = para.into();
33736                e.port = port;
33737            }
33738            let e = spec
33739                .entrada
33740                .as_ref()
33741                .expect("three_member_spec carries a typed `:entrada` block");
33742            assert_eq!(
33743                e.destination(),
33744                e.para.as_str(),
33745                "Entrada::destination must byte-equal the .para field \
33746                 access — an accessor-side detour that no longer \
33747                 projects the raw field would silently split this \
33748                 drift-detection test from the port_for_destination \
33749                 apex-arm membership probe",
33750            );
33751            assert_eq!(
33752                spec.port_for_destination(para),
33753                port,
33754                "port_for_destination must key off the accessor-projected \
33755                 destination and return `entrada.port` on the apex arm — \
33756                 input :entrada :para: {para:?}, :entrada :port: {port}",
33757            );
33758            assert_eq!(
33759                spec.port_for_destination("ghost-destination-never-a-member"),
33760                DEFAULT_SERVICO_PORT,
33761                "port_for_destination must fall through to \
33762                 DEFAULT_SERVICO_PORT on a non-matching destination \
33763                 under the accessor-projected membership check — input \
33764                 :entrada :para: {para:?}, :entrada :port: {port}",
33765            );
33766        }
33767    }
33768
33769    #[test]
33770    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
33771        // The canonical per-`:politicas :rate-limit` `:rate`
33772        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
33773        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
33774        // typed `u32` verbatim, byte-equal to the raw field access
33775        // across every representative value in the accept-set — `1` (the
33776        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
33777        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
33778        // carves out on the sibling `PolicyRateLimitZero` refusal),
33779        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
33780        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
33781        // `0` (a past-the-guard sentinel that pins the accessor doesn't
33782        // perform a silent bounds-collapse into `1` on the zero arm —
33783        // validate rejects zero but the accessor must ship the raw slot
33784        // verbatim so a validate-time gate regression surfaces at the
33785        // emit boundary rather than being silently absorbed), `u32::MAX`
33786        // (a past-the-guard sentinel that pins the accessor doesn't
33787        // perform a silent bounds-collapse through
33788        // `POLICY_RATE_LIMIT_MAX` at the return path).
33789        //
33790        // First sub-struct required-scalar accessor pin on the
33791        // `RateLimit` axis — sibling in shape to the peer
33792        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
33793        // required-`u32` accessor pin on the peer per-sub-struct
33794        // required-axis. Pins against a future silent detour that
33795        // re-derived the token capacity from a peer axis (an accidental
33796        // `self.window.as_secs() as u32` collapse that read the
33797        // rate-limit window duration as a token count), a `0 → 1`
33798        // cluster-default projection (which would silently absorb the
33799        // `PolicyRateLimitZero` refusal case at the accessor boundary),
33800        // or a bounds-collapsing accessor that clamped the return
33801        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
33802        // gate owns the bounds; the accessor must ship the raw slot
33803        // verbatim).
33804        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
33805            let rl = RateLimit {
33806                rate,
33807                window: Duration::from_secs(1),
33808            };
33809            assert_eq!(
33810                rl.rate(),
33811                rate,
33812                "RateLimit::rate must return :politicas :rate-limit :rate \
33813                 verbatim (got {}, expected {rate})",
33814                rl.rate(),
33815            );
33816            assert_eq!(
33817                rl.rate(),
33818                rl.rate,
33819                "RateLimit::rate must byte-equal the raw .rate field \
33820                 access across every value in the u32 accept-set",
33821            );
33822        }
33823    }
33824
33825    #[test]
33826    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
33827        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
33828        // `:rate-limit :rate` zero-floor arm must key off
33829        // [`RateLimit::rate`], not the raw `.rate` field access.
33830        // Structurally: a `RateLimit { rate: 0, window:
33831        // Duration::from_secs(1) }` embedded in a `:politicas
33832        // :rate-limit` slot must surface the `PolicyRateLimitZero`
33833        // refusal exactly, and a `RateLimit { rate: 1, window:
33834        // Duration::from_secs(1) }` (the lower boundary of the
33835        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
33836        // The pair jointly pins the accessor + validate-gate composition:
33837        // any future silent detour that had the accessor return a fresh
33838        // `1` on the zero arm (a `.rate().max(1)` collapse) would
33839        // silently absorb the `PolicyRateLimitZero` refusal at the
33840        // accessor boundary and the validate gate would accept a
33841        // struct-literal `RateLimit { rate: 0, .. }` — the composition
33842        // pin catches that at caixa-core build time.
33843        //
33844        // Peer of the sibling per-`CircuitBreaker`
33845        // [`CircuitBreaker::max_failures`] (3a74062) /
33846        // [`CircuitBreaker::window`] (373957f) accessor-composition
33847        // pins on the peer required-scalar axes — same "the validate /
33848        // shape-gate predicate must route through the substrate-primitive
33849        // typed dispatch" discipline extended onto the peer
33850        // per-`RateLimit` required-`u32` composition axis.
33851        let mut spec = three_member_spec();
33852        spec.politicas = MeshPolicy {
33853            rate_limit: Some(RateLimit {
33854                rate: 0,
33855                window: Duration::from_secs(1),
33856            }),
33857            ..MeshPolicy::default()
33858        };
33859        assert!(
33860            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
33861            "validate_politicas must reject rate == 0 with \
33862             PolicyRateLimitZero — the accessor and the validate gate \
33863             must route through the same substrate-primitive typed \
33864             dispatch on the :rate zero-floor arm",
33865        );
33866        spec.politicas = MeshPolicy {
33867            rate_limit: Some(RateLimit {
33868                rate: 1,
33869                window: Duration::from_secs(1),
33870            }),
33871            ..MeshPolicy::default()
33872        };
33873        assert!(
33874            spec.validate().is_ok(),
33875            "validate_politicas must accept rate == 1 (the lower \
33876             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
33877        );
33878    }
33879
33880    #[test]
33881    fn rate_limit_rate_projects_u32_by_copy() {
33882        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
33883        // `u32` is `Copy` and the accessor must return by value, not by
33884        // reference. Peer of the sibling per-`CircuitBreaker`
33885        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
33886        // peer required-scalar `:max-failures` axis, extended onto the
33887        // peer per-`RateLimit` required-`u32` copy-invariant shape —
33888        // the accessor's returned `u32` must outlive `&self` (multiple
33889        // calls must return equal values from a dropped-`&self` copy,
33890        // since the returned scalar carries no borrow), and calling the
33891        // accessor twice on the same RateLimit must yield the same
33892        // `u32` verbatim (idempotent, no side effects on `&self`).
33893        //
33894        // Pins against a future silent detour that returned `&u32`
33895        // (which would type-check but silently break every downstream
33896        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
33897        // first parameter is `u32`, and `&u32` would fold to a detached
33898        // copy at the call site with a `*` deref the sibling accessors
33899        // don't need), an accidental `.rate.wrapping_add(0)` detour that
33900        // returned a fresh copy through an arithmetic no-op (breaking a
33901        // future `const fn` regression), or a one-arm-only accessor
33902        // that returned a saturating value on some sentinel input
33903        // (breaking the pass-through invariant the sibling required-
33904        // scalar accessors carry).
33905        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
33906            let rl = RateLimit {
33907                rate,
33908                window: Duration::from_secs(1),
33909            };
33910            let first = rl.rate();
33911            let second = rl.rate();
33912            assert_eq!(
33913                first, second,
33914                "RateLimit::rate must be idempotent — two successive \
33915                 calls on the same &self must return the same u32",
33916            );
33917            assert_eq!(
33918                first, rate,
33919                "RateLimit::rate must return :politicas :rate-limit :rate \
33920                 verbatim by copy — got {first}, expected {rate}",
33921            );
33922        }
33923    }
33924
33925    #[test]
33926    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
33927        // The canonical per-`:politicas :rate-limit` `:window`
33928        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
33929        // pin: [`RateLimit::window`] must return the
33930        // `:politicas :rate-limit :window` typed `Duration` verbatim,
33931        // byte-equal to the raw field access across every
33932        // representative value in the accept-set — `Duration::from_secs(1)`
33933        // (the `"s"` canonical window, the lower row of
33934        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
33935        // [`AplicacaoSpec::validate_politicas`] gate accepts via
33936        // [`is_canonical_rate_limit_window`]),
33937        // `Duration::from_secs(60)` (the `"m"` canonical window, the
33938        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
33939        // window, the upper row), `Duration::ZERO` (a past-the-guard
33940        // sentinel that pins the accessor doesn't perform a silent
33941        // bounds-collapse into `Duration::from_secs(1)` on the zero
33942        // arm — validate rejects an off-set window through
33943        // `PolicyRateLimitWindowNotCanonical` but the accessor must
33944        // ship the raw slot verbatim so a validate-time gate
33945        // regression surfaces at the emit boundary rather than being
33946        // silently absorbed), `Duration::from_millis(500)` (a
33947        // sub-canonical past-the-guard sentinel that pins the accessor
33948        // doesn't silently normalize a non-canonical fractional
33949        // magnitude onto the nearest canonical row).
33950        //
33951        // Second sub-struct required-scalar accessor pin on the
33952        // `RateLimit` axis — sibling in shape to the just-landed
33953        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
33954        // accessor pin on the peer per-sub-struct required-axis,
33955        // extended onto the per-`RateLimit` required-`Duration` axis.
33956        // Pins against a future silent detour that re-derived the
33957        // refill period from a peer axis (an accidental
33958        // `Duration::from_secs(self.rate as u64)` collapse that read
33959        // the rate-limit token capacity as a refill-interval
33960        // duration), a `Duration::ZERO → Duration::from_secs(1)`
33961        // canonical-default projection (which would silently absorb
33962        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
33963        // accessor boundary), or a canonical-set-collapsing accessor
33964        // that clamped the return through [`rate_limit_window_unit`]
33965        // (the `AplicacaoSpec::validate` gate owns the canonical-set
33966        // membership; the accessor must ship the raw slot verbatim).
33967        for window in [
33968            Duration::from_secs(1),
33969            Duration::from_secs(60),
33970            Duration::from_secs(3600),
33971            Duration::ZERO,
33972            Duration::from_millis(500),
33973        ] {
33974            let rl = RateLimit { rate: 100, window };
33975            assert_eq!(
33976                rl.window(),
33977                window,
33978                "RateLimit::window must return :politicas :rate-limit :window \
33979                 verbatim (got {:?}, expected {window:?})",
33980                rl.window(),
33981            );
33982            assert_eq!(
33983                rl.window(),
33984                rl.window,
33985                "RateLimit::window must byte-equal the raw .window field \
33986                 access across every value in the Duration accept-set",
33987            );
33988        }
33989    }
33990
33991    #[test]
33992    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
33993        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
33994        // `:rate-limit :window` canonical-set arm must key off
33995        // [`RateLimit::window`], not the raw `.window` field access.
33996        // Structurally: a `RateLimit { window: Duration::from_millis(500),
33997        // .. }` embedded in a `:politicas :rate-limit` slot must
33998        // surface the `PolicyRateLimitWindowNotCanonical` refusal
33999        // exactly (with the sub-canonical `Duration::from_millis(500)`
34000        // magnitude carried through verbatim), and a `RateLimit
34001        // { window: Duration::from_secs(1), .. }` (the lower row of
34002        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
34003        // The pair jointly pins the accessor + validate-gate
34004        // composition: any future silent detour that had the accessor
34005        // normalize the off-set window to the nearest canonical row
34006        // (a `.window().max(Duration::from_secs(1))` collapse, or a
34007        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
34008        // collapse) would silently absorb the
34009        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
34010        // boundary — including a drift in the error's `window` payload
34011        // (the emit-side diagnostic reader keys off the offending
34012        // magnitude verbatim, so a normalization at the accessor
34013        // boundary would silently pin the wrong magnitude in the
34014        // refusal). The composition pin catches that at caixa-core
34015        // build time.
34016        //
34017        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
34018        // (7f81a60) accessor-composition pin on the peer required-
34019        // scalar `:rate` axis — same "the validate / shape-gate
34020        // predicate must route through the substrate-primitive typed
34021        // dispatch, and the error payload must project through the
34022        // same accessor" discipline extended onto the peer
34023        // per-`RateLimit` required-`Duration` composition axis.
34024        let mut spec = three_member_spec();
34025        spec.politicas = MeshPolicy {
34026            rate_limit: Some(RateLimit {
34027                rate: 100,
34028                window: Duration::from_millis(500),
34029            }),
34030            ..MeshPolicy::default()
34031        };
34032        match spec.validate() {
34033            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
34034                assert_eq!(
34035                    window,
34036                    Duration::from_millis(500),
34037                    "PolicyRateLimitWindowNotCanonical must carry the \
34038                     offending :window magnitude verbatim through the \
34039                     accessor — got {window:?}, expected 500ms",
34040                );
34041            }
34042            other => panic!(
34043                "validate_politicas must reject non-canonical :window \
34044                 with PolicyRateLimitWindowNotCanonical — the accessor \
34045                 and the validate gate must route through the same \
34046                 substrate-primitive typed dispatch on the :window \
34047                 canonical-set arm; got {other:?}",
34048            ),
34049        }
34050        spec.politicas = MeshPolicy {
34051            rate_limit: Some(RateLimit {
34052                rate: 100,
34053                window: Duration::from_secs(1),
34054            }),
34055            ..MeshPolicy::default()
34056        };
34057        assert!(
34058            spec.validate().is_ok(),
34059            "validate_politicas must accept window == Duration::from_secs(1) \
34060             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
34061        );
34062    }
34063
34064    #[test]
34065    fn rate_limit_window_projects_duration_by_copy() {
34066        // The by-copy pin: [`RateLimit::window`] returns `Duration`
34067        // by copy — `Duration` is `Copy` and the accessor must return
34068        // by value, not by reference. Peer of the sibling per-`RateLimit`
34069        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
34070        // required-scalar `:rate` axis, extended onto the peer
34071        // per-`RateLimit` required-`Duration` copy-invariant shape —
34072        // the accessor's returned `Duration` must outlive `&self`
34073        // (multiple calls must return equal values from a
34074        // dropped-`&self` copy, since the returned scalar carries no
34075        // borrow), and calling the accessor twice on the same
34076        // RateLimit must yield the same `Duration` verbatim
34077        // (idempotent, no side effects on `&self`).
34078        //
34079        // Pins against a future silent detour that returned
34080        // `&Duration` (which would type-check but silently break every
34081        // downstream `Duration`-by-value consumer —
34082        // [`is_canonical_rate_limit_window`]'s first parameter is
34083        // `Duration`, and `&Duration` would fold to a detached copy at
34084        // the call site with a `*` deref the sibling accessors don't
34085        // need), an accidental `.window + Duration::ZERO` detour that
34086        // returned a fresh copy through an arithmetic no-op (breaking
34087        // a future `const fn` regression), or a one-arm-only accessor
34088        // that returned a canonical fallback on some sentinel input
34089        // (breaking the pass-through invariant the sibling required-
34090        // scalar accessors carry).
34091        for window in [
34092            Duration::from_secs(1),
34093            Duration::from_secs(60),
34094            Duration::from_secs(3600),
34095            Duration::ZERO,
34096            Duration::from_millis(500),
34097        ] {
34098            let rl = RateLimit { rate: 100, window };
34099            let first = rl.window();
34100            let second = rl.window();
34101            assert_eq!(
34102                first, second,
34103                "RateLimit::window must be idempotent — two successive \
34104                 calls on the same &self must return the same Duration",
34105            );
34106            assert_eq!(
34107                first, window,
34108                "RateLimit::window must return :politicas :rate-limit :window \
34109                 verbatim by copy — got {first:?}, expected {window:?}",
34110            );
34111        }
34112    }
34113
34114    #[test]
34115    fn placement_estrategia_default_pins_m3_canonical_value() {
34116        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
34117        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
34118        // active-active-across-every-named-cluster arm, the closest
34119        // canonical M3 production reference the substrate carries and
34120        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
34121        // for every un-`:placement`-declared Aplicacao. Pinning the arm
34122        // here surfaces a future rebrand of the M3-canonical
34123        // distribution default (a widening to `Sharded` once the
34124        // substrate discovers hash-keyed distribution as the more
34125        // common production shape, a tightening to `SingleNode` for
34126        // stateful Erlang/OTP distributed-app-takeover semantics
34127        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
34128        // operator pins through a future `:placement-overrides` slot)
34129        // as a deliberate test edit, not a silent contract migration.
34130        // Peer of the sibling M2 per-supervisor value pins
34131        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
34132        // /
34133        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
34134        // extended onto the M3 mesh-primitive-defining `:placement
34135        // :estrategia` axis.
34136        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
34137    }
34138
34139    #[test]
34140    fn placement_strategy_default_routes_through_lifted_default() {
34141        // Composition pin: the [`Default for PlacementStrategy`] impl's
34142        // return arm must route through the substrate-canonical
34143        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
34144        // a raw `Self::Replicated` arm. Prior to the lift the impl
34145        // carried an inline `Self::Replicated` arm with no compile-time
34146        // link back to the shared M3-canonical `Replicated` arm the
34147        // paired [`Default for Placement`] impl's struct-literal
34148        // `estrategia` field, the serde-side `#[serde(default)]` on
34149        // [`Placement::estrategia`] that resolves an author-omitted
34150        // wire-form `:placement :estrategia` scalar through the impl,
34151        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
34152        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
34153        // routes through [`Placement::default`] which routes through the
34154        // strategy default) all key off — so a future rebrand of the
34155        // M3-canonical distribution default would have had to be threaded
34156        // through the `Default` impl and the three peer routes in
34157        // lockstep or the four consumers would silently split. Byte-
34158        // parity against the lifted constant closes the split. Peer of
34159        // the sibling
34160        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
34161        // /
34162        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
34163        // composition pins on the M2 per-supervisor axes.
34164        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
34165    }
34166
34167    #[test]
34168    fn placement_default_estrategia_routes_through_lifted_default() {
34169        // Composition pin: the [`Default for Placement`] impl's
34170        // struct-literal `estrategia` field must route through the
34171        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
34172        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
34173        // impl that the sibling
34174        // `placement_strategy_default_routes_through_lifted_default` pin
34175        // already routes onto the constant). Structurally: every
34176        // `Placement::default()` call must yield an `estrategia` field
34177        // byte-equal to the lifted constant so the two paired defaults —
34178        // the [`Default for PlacementStrategy`] impl arm and the
34179        // struct-literal default arm here — cannot silently split on any
34180        // future M3-canonical distribution-default rebrand. Peer of the
34181        // sibling M2
34182        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
34183        // byte-parity pin on the [`Default for SupervisorSpec`]
34184        // struct-literal `estrategia` field extended onto the M3
34185        // mesh-primitive-defining slot family.
34186        assert_eq!(
34187            Placement::default().estrategia,
34188            PLACEMENT_ESTRATEGIA_DEFAULT,
34189        );
34190    }
34191
34192    #[test]
34193    fn placement_serde_default_estrategia_routes_through_lifted_default() {
34194        // Composition pin: the serde-side `#[serde(default)]` on
34195        // [`Placement::estrategia`] — the wire-format author-omitted
34196        // `:placement :estrategia` arm — must resolve onto the substrate-
34197        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
34198        // (via the [`Default for PlacementStrategy`] impl the sibling
34199        // `placement_strategy_default_routes_through_lifted_default` pin
34200        // already routes onto the constant). Structurally: a `Placement`
34201        // deserialized from a payload that omits the `estrategia` key
34202        // must yield an `estrategia` field byte-equal to the lifted
34203        // constant, so the wire-format author-omitted arm and the
34204        // [`PlacementStrategy::default`] impl arm cannot silently split
34205        // on any future M3-canonical distribution-default rebrand. Peer
34206        // of the sibling M2
34207        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
34208        // byte-parity pin on the wire-format author-omitted `:children
34209        // :restart` scalar extended onto the M3 mesh-primitive-defining
34210        // slot family.
34211        let omitted: Placement = serde_json::from_str("{}")
34212            .expect("Placement must deserialize with the estrategia key omitted");
34213        assert_eq!(
34214            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
34215            "an author-omitted :placement :estrategia slot must degrade onto \
34216             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
34217             {:?}, expected {:?})",
34218            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
34219        );
34220    }
34221
34222    // ── contrato_target_ctors! fold pins ────────────────────────────────
34223    //
34224    // Fixture edge triple + payload-field-name label pair for every
34225    // `contrato_target_ctors!`-generated ctor pin below. Kept as
34226    // non-default `("cart", "catalog", "wasi:http/proxy")` +
34227    // `WitTarget::HTTP_FIELD_NAME` so a byte-equality mistake against
34228    // the fixture default doesn't silently pass. Peer of the sibling
34229    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` /
34230    // `<slot>_violation_ctor_matches_struct_literal_wrap` /
34231    // `<slot>_slots_on_non_<owner>_ctor_matches_struct_literal_wrap` /
34232    // `missing_entry_ctor_matches_struct_literal_wrap` /
34233    // `<slot>_ctor_matches_tuple_literal_wrap` equivalence pins on the
34234    // four `LayoutError` constructor families each closed on their
34235    // sibling envelopes.
34236    fn contrato_target_ctor_fixture() -> (String, String, String, &'static str) {
34237        (
34238            "cart".to_string(),
34239            "catalog".to_string(),
34240            "wasi:http/proxy".to_string(),
34241            WitTarget::HTTP_FIELD_NAME,
34242        )
34243    }
34244
34245    #[test]
34246    fn contrato_wrong_target_ctor_matches_struct_literal_wrap() {
34247        // Equivalence pin: the ctor produces byte-equal
34248        // `AplicacaoError::ContratoWrongTarget` to the pre-lift open-
34249        // coded struct-literal on the same edge fixture, so the fold
34250        // cannot silently drift on any future field-addition /
34251        // reordering / string-conversion tweak on the variant. Peer of
34252        // the sibling `entrada_host_invalid_ctor_matches_struct_literal_wrap`
34253        // (17dd504) / the four `LayoutError` family equivalence pins.
34254        let (de, para, wit, expected) = contrato_target_ctor_fixture();
34255        let lifted = AplicacaoError::contrato_wrong_target(
34256            (de.clone(), para.clone(), wit.clone()),
34257            expected,
34258        );
34259        let struct_literal = AplicacaoError::ContratoWrongTarget {
34260            de,
34261            para,
34262            wit,
34263            expected,
34264        };
34265        assert_eq!(lifted, struct_literal);
34266    }
34267
34268    #[test]
34269    fn contrato_missing_target_ctor_matches_struct_literal_wrap() {
34270        // Equivalence pin peer of the sibling
34271        // `contrato_wrong_target_ctor_matches_struct_literal_wrap` above
34272        // on the paired `ContratoMissingTarget` variant of the same
34273        // four-slot envelope shape the `contrato_target_ctors!` macro
34274        // closes.
34275        let (de, para, wit, expected) = contrato_target_ctor_fixture();
34276        let lifted = AplicacaoError::contrato_missing_target(
34277            (de.clone(), para.clone(), wit.clone()),
34278            expected,
34279        );
34280        let struct_literal = AplicacaoError::ContratoMissingTarget {
34281            de,
34282            para,
34283            wit,
34284            expected,
34285        };
34286        assert_eq!(lifted, struct_literal);
34287    }
34288
34289    #[test]
34290    fn contrato_target_ctors_route_edge_triple_through_verbatim() {
34291        // Routing pin: the `(de, para, wit)` triple threads verbatim
34292        // onto same-named fields on both generated ctors, no wrapper-
34293        // side lowercase / trim / re-order. Sweeps a non-default triple
34294        // (`"cart-svc" → "catalog-v2"`, `"nats:pub-sub"`) so any
34295        // wrapper-side transformation surfaces here rather than at a
34296        // downstream diagnostic-shape drift. Sibling of
34297        // `entrada_host_invalid_ctor_routes_host_through_to_string`
34298        // (17dd504) on the paired triple-carrying envelope.
34299        let edge = (
34300            "cart-svc".to_string(),
34301            "catalog-v2".to_string(),
34302            "nats:pub-sub".to_string(),
34303        );
34304        let wrong =
34305            AplicacaoError::contrato_wrong_target(edge.clone(), WitTarget::PUBSUB_FIELD_NAME);
34306        let missing = AplicacaoError::contrato_missing_target(edge, WitTarget::PUBSUB_FIELD_NAME);
34307        let AplicacaoError::ContratoWrongTarget {
34308            de: wde,
34309            para: wpara,
34310            wit: wwit,
34311            ..
34312        } = wrong
34313        else {
34314            panic!("contrato_wrong_target must construct the ContratoWrongTarget variant");
34315        };
34316        let AplicacaoError::ContratoMissingTarget {
34317            de: mde,
34318            para: mpara,
34319            wit: mwit,
34320            ..
34321        } = missing
34322        else {
34323            panic!("contrato_missing_target must construct the ContratoMissingTarget variant");
34324        };
34325        assert_eq!(wde, "cart-svc");
34326        assert_eq!(wpara, "catalog-v2");
34327        assert_eq!(wwit, "nats:pub-sub");
34328        assert_eq!(mde, "cart-svc");
34329        assert_eq!(mpara, "catalog-v2");
34330        assert_eq!(mwit, "nats:pub-sub");
34331    }
34332
34333    #[test]
34334    fn contrato_target_ctors_route_expected_through_verbatim() {
34335        // Routing pin: the `expected: &'static str` label threads
34336        // verbatim (identity, not copy-and-transform) onto the
34337        // `expected` field of both variants, so the four canonical
34338        // labels [`WitTarget::HTTP_FIELD_NAME`] /
34339        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
34340        // / [`WitTarget::CAPABILITY_EXPECTED`] survive the fold as
34341        // pointer-equal (not merely value-equal) references — a wrapper-
34342        // side `.to_string()` / `Cow::Owned` promotion would break the
34343        // `&'static str` contract downstream consumers depend on.
34344        for label in [
34345            WitTarget::HTTP_FIELD_NAME,
34346            WitTarget::PUBSUB_FIELD_NAME,
34347            WitTarget::STORE_FIELD_NAME,
34348            WitTarget::CAPABILITY_EXPECTED,
34349        ] {
34350            let (de, para, wit, _) = contrato_target_ctor_fixture();
34351            let wrong = AplicacaoError::contrato_wrong_target(
34352                (de.clone(), para.clone(), wit.clone()),
34353                label,
34354            );
34355            let missing = AplicacaoError::contrato_missing_target((de, para, wit), label);
34356            match wrong {
34357                AplicacaoError::ContratoWrongTarget { expected, .. } => {
34358                    assert!(
34359                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
34360                            && expected.len() == label.len(),
34361                        "contrato_wrong_target must thread the &'static str \
34362                         label pointer-equal onto the `expected` field \
34363                         (label = {label:?})",
34364                    );
34365                }
34366                other => panic!("expected ContratoWrongTarget, got {other:?}"),
34367            }
34368            match missing {
34369                AplicacaoError::ContratoMissingTarget { expected, .. } => {
34370                    assert!(
34371                        std::ptr::eq(expected.as_ptr(), label.as_ptr())
34372                            && expected.len() == label.len(),
34373                        "contrato_missing_target must thread the &'static \
34374                         str label pointer-equal onto the `expected` field \
34375                         (label = {label:?})",
34376                    );
34377                }
34378                other => panic!("expected ContratoMissingTarget, got {other:?}"),
34379            }
34380        }
34381    }
34382
34383    // ── contrato_empty_pair_ctors! fold pins ────────────────────────────
34384    //
34385    // Fixture edge pair for every `contrato_empty_pair_ctors!`-generated
34386    // ctor pin below. Kept as non-default `("cart", "catalog")` so a
34387    // byte-equality mistake against the fixture default doesn't silently
34388    // pass. Peer of the sibling `contrato_target_ctor_fixture` (14b81d5,
34389    // triple + expected-label envelope on
34390    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
34391    // struct_literal_wrap` (17dd504, host + reason envelope on
34392    // `entrada_host_invalid`) / the four `LayoutError` family
34393    // equivalence pins.
34394    fn contrato_empty_pair_ctor_fixture() -> (String, String) {
34395        ("cart".to_string(), "catalog".to_string())
34396    }
34397
34398    #[test]
34399    fn empty_wit_ctor_matches_struct_literal_wrap() {
34400        // Equivalence pin: the ctor produces byte-equal
34401        // `AplicacaoError::EmptyWit` to the pre-lift open-coded
34402        // struct-literal on the same edge pair, so the fold cannot
34403        // silently drift on any future field-addition / reordering /
34404        // string-conversion tweak on the variant. Peer of the sibling
34405        // `contrato_wrong_target_ctor_matches_struct_literal_wrap`
34406        // (14b81d5) / `entrada_host_invalid_ctor_matches_struct_literal_wrap`
34407        // (17dd504) / the four `LayoutError` family equivalence pins.
34408        let (de, para) = contrato_empty_pair_ctor_fixture();
34409        let lifted = AplicacaoError::empty_wit((de.clone(), para.clone()));
34410        let struct_literal = AplicacaoError::EmptyWit { de, para };
34411        assert_eq!(lifted, struct_literal);
34412    }
34413
34414    #[test]
34415    fn contrato_endpoint_empty_ctor_matches_struct_literal_wrap() {
34416        // Equivalence pin peer of the sibling
34417        // `empty_wit_ctor_matches_struct_literal_wrap` above on the
34418        // paired `ContratoEndpointEmpty` variant of the same two-slot
34419        // envelope shape the `contrato_empty_pair_ctors!` macro closes.
34420        let (de, para) = contrato_empty_pair_ctor_fixture();
34421        let lifted = AplicacaoError::contrato_endpoint_empty((de.clone(), para.clone()));
34422        let struct_literal = AplicacaoError::ContratoEndpointEmpty { de, para };
34423        assert_eq!(lifted, struct_literal);
34424    }
34425
34426    #[test]
34427    fn contrato_subject_empty_ctor_matches_struct_literal_wrap() {
34428        // Equivalence pin peer of the sibling
34429        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
34430        // above on the paired `ContratoSubjectEmpty` variant of the
34431        // same two-slot envelope shape.
34432        let (de, para) = contrato_empty_pair_ctor_fixture();
34433        let lifted = AplicacaoError::contrato_subject_empty((de.clone(), para.clone()));
34434        let struct_literal = AplicacaoError::ContratoSubjectEmpty { de, para };
34435        assert_eq!(lifted, struct_literal);
34436    }
34437
34438    #[test]
34439    fn contrato_slot_empty_ctor_matches_struct_literal_wrap() {
34440        // Equivalence pin peer of the sibling
34441        // `contrato_subject_empty_ctor_matches_struct_literal_wrap`
34442        // above on the paired `ContratoSlotEmpty` variant of the same
34443        // two-slot envelope shape.
34444        let (de, para) = contrato_empty_pair_ctor_fixture();
34445        let lifted = AplicacaoError::contrato_slot_empty((de.clone(), para.clone()));
34446        let struct_literal = AplicacaoError::ContratoSlotEmpty { de, para };
34447        assert_eq!(lifted, struct_literal);
34448    }
34449
34450    #[test]
34451    fn contrato_empty_pair_ctors_route_edge_pair_through_verbatim() {
34452        // Routing pin: the `(de, para)` pair threads verbatim onto
34453        // same-named fields on all four generated ctors, no wrapper-
34454        // side lowercase / trim / re-order. Sweeps a non-default pair
34455        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
34456        // transformation surfaces here rather than at a downstream
34457        // diagnostic-shape drift. Sibling of
34458        // `contrato_target_ctors_route_edge_triple_through_verbatim`
34459        // (14b81d5) on the paired triple-carrying envelope and of
34460        // `entrada_host_invalid_ctor_routes_host_through_to_string`
34461        // (17dd504) on the sibling `{ host, reason }` envelope.
34462        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
34463        let variants: [(AplicacaoError, &'static str); 4] = [
34464            (AplicacaoError::empty_wit(edge.clone()), "EmptyWit"),
34465            (
34466                AplicacaoError::contrato_endpoint_empty(edge.clone()),
34467                "ContratoEndpointEmpty",
34468            ),
34469            (
34470                AplicacaoError::contrato_subject_empty(edge.clone()),
34471                "ContratoSubjectEmpty",
34472            ),
34473            (
34474                AplicacaoError::contrato_slot_empty(edge.clone()),
34475                "ContratoSlotEmpty",
34476            ),
34477        ];
34478        for (built, label) in variants {
34479            let (de, para) = match built {
34480                AplicacaoError::EmptyWit { de, para }
34481                | AplicacaoError::ContratoEndpointEmpty { de, para }
34482                | AplicacaoError::ContratoSubjectEmpty { de, para }
34483                | AplicacaoError::ContratoSlotEmpty { de, para } => (de, para),
34484                other => panic!("expected {label} pair variant, got {other:?}"),
34485            };
34486            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
34487            assert_eq!(
34488                para, "catalog-v2",
34489                "para field on {label} must thread verbatim",
34490            );
34491        }
34492    }
34493
34494    // ── contrato_pair_value_reason_ctors! fold pins ─────────────────────
34495    //
34496    // Fixture edge pair + value + reason for every
34497    // `contrato_pair_value_reason_ctors!`-generated ctor pin below. Kept
34498    // as non-default `("cart", "catalog")` on the `(de, para)` pair and
34499    // fixed per-axis `<val>` / reason so a byte-equality mistake against
34500    // the fixture default doesn't silently pass. Peer of the sibling
34501    // `contrato_empty_pair_ctor_fixture` (8580068, pair-only envelope on
34502    // `contrato_empty_pair_ctors!`) / `contrato_target_ctor_fixture`
34503    // (14b81d5, triple + expected-label envelope on
34504    // `contrato_target_ctors!`) / `entrada_host_invalid_ctor_matches_
34505    // struct_literal_wrap` (17dd504, host + reason envelope on
34506    // `entrada_host_invalid`).
34507    fn contrato_pair_value_reason_ctor_fixture() -> (String, String) {
34508        ("cart".to_string(), "catalog".to_string())
34509    }
34510
34511    #[test]
34512    fn contrato_endpoint_invalid_ctor_matches_struct_literal_wrap() {
34513        // Equivalence pin: the ctor produces byte-equal
34514        // `AplicacaoError::ContratoEndpointInvalid` to the pre-lift
34515        // open-coded struct-literal on the same
34516        // `(edge_pair, endpoint, reason)` triple, so the fold cannot
34517        // silently drift on any future field-addition / reordering /
34518        // string-conversion tweak on the variant. Peer of the sibling
34519        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
34520        // (8580068) on the paired two-slot envelope of the same
34521        // `{ de, para, ... }` prefix, and of
34522        // `entrada_host_invalid_ctor_matches_struct_literal_wrap`
34523        // (17dd504) on the sibling `{ <field>: String, reason: String }`
34524        // two-slot envelope.
34525        let (de, para) = contrato_pair_value_reason_ctor_fixture();
34526        let endpoint = "/charge";
34527        let reason = "sample reason text";
34528        let lifted =
34529            AplicacaoError::contrato_endpoint_invalid((de.clone(), para.clone()), endpoint, reason);
34530        let struct_literal = AplicacaoError::ContratoEndpointInvalid {
34531            de,
34532            para,
34533            endpoint: endpoint.to_string(),
34534            reason: reason.to_string(),
34535        };
34536        assert_eq!(lifted, struct_literal);
34537    }
34538
34539    #[test]
34540    fn contrato_subject_invalid_ctor_matches_struct_literal_wrap() {
34541        // Equivalence pin peer of the sibling
34542        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
34543        // above on the paired `ContratoSubjectInvalid` variant of the
34544        // same four-slot envelope shape the
34545        // `contrato_pair_value_reason_ctors!` macro closes.
34546        let (de, para) = contrato_pair_value_reason_ctor_fixture();
34547        let subject = "checkout.events.charge.failed";
34548        let reason = "sample reason text";
34549        let lifted =
34550            AplicacaoError::contrato_subject_invalid((de.clone(), para.clone()), subject, reason);
34551        let struct_literal = AplicacaoError::ContratoSubjectInvalid {
34552            de,
34553            para,
34554            subject: subject.to_string(),
34555            reason: reason.to_string(),
34556        };
34557        assert_eq!(lifted, struct_literal);
34558    }
34559
34560    #[test]
34561    fn contrato_slot_invalid_ctor_matches_struct_literal_wrap() {
34562        // Equivalence pin peer of the sibling
34563        // `contrato_subject_invalid_ctor_matches_struct_literal_wrap`
34564        // above on the paired `ContratoSlotInvalid` variant of the same
34565        // four-slot envelope shape.
34566        let (de, para) = contrato_pair_value_reason_ctor_fixture();
34567        let slot = "checkout/$orderId";
34568        let reason = "sample reason text";
34569        let lifted =
34570            AplicacaoError::contrato_slot_invalid((de.clone(), para.clone()), slot, reason);
34571        let struct_literal = AplicacaoError::ContratoSlotInvalid {
34572            de,
34573            para,
34574            slot: slot.to_string(),
34575            reason: reason.to_string(),
34576        };
34577        assert_eq!(lifted, struct_literal);
34578    }
34579
34580    #[test]
34581    fn contrato_wit_invalid_ctor_matches_struct_literal_wrap() {
34582        // Equivalence pin peer of the sibling
34583        // `contrato_slot_invalid_ctor_matches_struct_literal_wrap` above
34584        // on the paired `ContratoWitInvalid` variant of the same four-
34585        // slot envelope shape the `contrato_pair_value_reason_ctors!`
34586        // macro closes. Fold pinned this test lands with the last
34587        // `{ de, para, <field>: String, reason: String }` open-coded
34588        // struct-literal inside [`WitContract::target`] rewritten to
34589        // route through the macro-generated
34590        // [`AplicacaoError::contrato_wit_invalid`] ctor — a byte-mismatch
34591        // between the ctor and the pre-lift struct-literal trips this
34592        // pin ahead of any downstream diagnostic-shape drift on the
34593        // `:contratos :wit` axis.
34594        let (de, para) = contrato_pair_value_reason_ctor_fixture();
34595        let wit = "wasi-http/proxy";
34596        let reason = "sample reason text";
34597        let lifted = AplicacaoError::contrato_wit_invalid((de.clone(), para.clone()), wit, reason);
34598        let struct_literal = AplicacaoError::ContratoWitInvalid {
34599            de,
34600            para,
34601            wit: wit.to_string(),
34602            reason: reason.to_string(),
34603        };
34604        assert_eq!(lifted, struct_literal);
34605    }
34606
34607    #[test]
34608    fn contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim() {
34609        // Routing pin: the `(de, para)` pair threads verbatim onto
34610        // same-named fields on all four generated ctors, no wrapper-
34611        // side lowercase / trim / re-order. Sweeps a non-default pair
34612        // (`"cart-svc" → "catalog-v2"`) so any wrapper-side
34613        // transformation surfaces here rather than at a downstream
34614        // diagnostic-shape drift. Sibling of
34615        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
34616        // (8580068) on the paired two-slot envelope and of
34617        // `contrato_target_ctors_route_edge_triple_through_verbatim`
34618        // (14b81d5) on the paired triple-carrying envelope.
34619        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
34620        let variants: [(AplicacaoError, &'static str); 4] = [
34621            (
34622                AplicacaoError::contrato_endpoint_invalid(edge.clone(), "/x", "r"),
34623                "ContratoEndpointInvalid",
34624            ),
34625            (
34626                AplicacaoError::contrato_subject_invalid(edge.clone(), "x.y", "r"),
34627                "ContratoSubjectInvalid",
34628            ),
34629            (
34630                AplicacaoError::contrato_slot_invalid(edge.clone(), "x/y", "r"),
34631                "ContratoSlotInvalid",
34632            ),
34633            (
34634                AplicacaoError::contrato_wit_invalid(edge.clone(), "wasi:http/proxy", "r"),
34635                "ContratoWitInvalid",
34636            ),
34637        ];
34638        for (built, label) in variants {
34639            let (de, para) = match built {
34640                AplicacaoError::ContratoEndpointInvalid { de, para, .. }
34641                | AplicacaoError::ContratoSubjectInvalid { de, para, .. }
34642                | AplicacaoError::ContratoSlotInvalid { de, para, .. }
34643                | AplicacaoError::ContratoWitInvalid { de, para, .. } => (de, para),
34644                other => panic!("expected {label} pair variant, got {other:?}"),
34645            };
34646            assert_eq!(de, "cart-svc", "de field on {label} must thread verbatim");
34647            assert_eq!(
34648                para, "catalog-v2",
34649                "para field on {label} must thread verbatim",
34650            );
34651        }
34652    }
34653
34654    #[test]
34655    fn contrato_pair_value_reason_ctors_route_reason_through_into_uniformly() {
34656        // Cross-arm invariance pin — the four ctors all route
34657        // `reason: impl Into<String>` verbatim onto their respective
34658        // typed variants through the shared
34659        // [`contrato_pair_value_reason_ctors!`] macro. Sweeps a fixture
34660        // pair (`&str` literal, `format!` output) against every ctor to
34661        // pin that no per-arm wrapper transformation drifted in against
34662        // the uniform macro-generated body. Peer of
34663        // `aplicacao_field_reason_ctors_route_reason_through_into_uniformly`
34664        // (981060b) on the sibling two-slot envelope's cross-arm sweep.
34665        let edge = || ("cart".to_string(), "catalog".to_string());
34666        let via_literal = "literal reason text";
34667        let via_format = format!("{} reason text", "literal");
34668        assert_eq!(
34669            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_literal),
34670            AplicacaoError::contrato_endpoint_invalid(edge(), "/e", via_format.clone()),
34671        );
34672        assert_eq!(
34673            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_literal),
34674            AplicacaoError::contrato_subject_invalid(edge(), "s.t", via_format.clone()),
34675        );
34676        assert_eq!(
34677            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_literal),
34678            AplicacaoError::contrato_slot_invalid(edge(), "k/v", via_format.clone()),
34679        );
34680        assert_eq!(
34681            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_literal),
34682            AplicacaoError::contrato_wit_invalid(edge(), "wasi:http/proxy", via_format),
34683        );
34684    }
34685
34686    // ── contrato_endpoint_not_absolute standalone ctor pins ─────────────
34687    //
34688    // Fail-before-pass-after pins for the standalone
34689    // [`AplicacaoError::contrato_endpoint_not_absolute`] inherent ctor
34690    // (see the paired doc-block above the ctor definition) — the fold of
34691    // the last open-coded three-slot `{ de, para, endpoint: <val>
34692    // .to_string() }` struct-literal inside [`WitContract::target`]'s
34693    // HTTP-arm leading-slash gate onto one substrate primitive on the
34694    // envelope. A byte-mismatched ctor body would trip the equivalence
34695    // pin first, ahead of any downstream diagnostic-shape drift.
34696    //
34697    // Peer of the sibling standalone-ctor equivalence pins on the peer
34698    // one-off variants across caixa-core:
34699    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
34700    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` above
34701    // on the paired two-slot and four-slot per-`:contratos :endpoint`
34702    // envelopes; `child_caixa_invalid_ctor_matches_struct_literal_wrap`
34703    // and `child_versao_invalid_ctor_matches_struct_literal_wrap`
34704    // (d2ef2ec) on the sibling `SupervisorError` `{ caixa, [versao,]
34705    // reason }` two- and three-slot envelopes; the
34706    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
34707    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
34708    fn contrato_endpoint_not_absolute_ctor_fixture() -> (String, String) {
34709        ("cart".to_string(), "catalog".to_string())
34710    }
34711
34712    #[test]
34713    fn contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap() {
34714        // Equivalence pin: the ctor produces byte-equal
34715        // `AplicacaoError::ContratoEndpointNotAbsolute` to the pre-lift
34716        // open-coded struct-literal on the same `(edge_pair, endpoint)`
34717        // pair, so the fold cannot silently drift on any future
34718        // field-addition / reordering / string-conversion tweak on the
34719        // variant. Same equivalence-pin shape as the sibling
34720        // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap`
34721        // (8580068) on the paired two-slot envelope and
34722        // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap`
34723        // (14e13f1) on the paired four-slot envelope of the same
34724        // `{ de, para, ... }`-prefix `:endpoint` axis.
34725        let (de, para) = contrato_endpoint_not_absolute_ctor_fixture();
34726        let endpoint = "charge";
34727        let lifted =
34728            AplicacaoError::contrato_endpoint_not_absolute((de.clone(), para.clone()), endpoint);
34729        let struct_literal = AplicacaoError::ContratoEndpointNotAbsolute {
34730            de,
34731            para,
34732            endpoint: endpoint.to_string(),
34733        };
34734        assert_eq!(lifted, struct_literal);
34735    }
34736
34737    #[test]
34738    fn contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim() {
34739        // Routing pin on the `(de, para)` axis: sweep a non-default
34740        // pair (`"cart-svc" → "catalog-v2"`) so any wrapper-side
34741        // lowercase / trim / re-order surfaces here rather than at a
34742        // downstream diagnostic-shape drift. Peer of
34743        // `contrato_empty_pair_ctors_route_edge_pair_through_verbatim`
34744        // (8580068) on the paired two-slot envelope and
34745        // `contrato_pair_value_reason_ctors_route_edge_pair_through_verbatim`
34746        // (14e13f1) on the paired four-slot envelope of the same
34747        // `{ de, para, ... }`-prefix `:contratos` axis.
34748        let edge = ("cart-svc".to_string(), "catalog-v2".to_string());
34749        let built = AplicacaoError::contrato_endpoint_not_absolute(edge, "charge");
34750        match built {
34751            AplicacaoError::ContratoEndpointNotAbsolute { de, para, .. } => {
34752                assert_eq!(de, "cart-svc", "de field must thread verbatim");
34753                assert_eq!(para, "catalog-v2", "para field must thread verbatim");
34754            }
34755            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
34756        }
34757    }
34758
34759    #[test]
34760    fn contrato_endpoint_not_absolute_ctor_routes_endpoint_through_to_string() {
34761        // Routing pin on the `endpoint: &str` axis: sweep a non-default
34762        // value (`"charge"` — no leading `/`, the exact shape the
34763        // [`WitContract::target`] HTTP-arm leading-slash gate rejects)
34764        // through the sole payload-carrier constructor axis so any
34765        // wrapper-side transformation on the `endpoint.to_string()`
34766        // one-field construction surfaces here rather than at a
34767        // downstream diagnostic-shape mismatch. Sibling of
34768        // `contrato_pair_value_reason_ctors_route_reason_through_into_uniformly`
34769        // (14e13f1) on the sibling four-slot envelope's payload-carrier
34770        // routing pin.
34771        let edge = || ("cart".to_string(), "catalog".to_string());
34772        let via_literal = "charge";
34773        let via_string = String::from("charge");
34774        assert_eq!(
34775            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_literal),
34776            AplicacaoError::contrato_endpoint_not_absolute(edge(), via_string.as_str()),
34777        );
34778    }
34779
34780    // ── contrato_self_loop standalone ctor pins ─────────────────────────
34781    //
34782    // Fail-before-pass-after pins for the standalone
34783    // [`AplicacaoError::contrato_self_loop`] inherent ctor (see the paired
34784    // doc-block above the ctor definition) — the fold of the last
34785    // open-coded two-slot `{ caixa: <ct>.source().to_string(), wit:
34786    // <ct>.world_ref().to_string() }` struct-literal inside
34787    // [`AplicacaoSpec::validate_contratos`]'s per-`:contratos` self-edge
34788    // arm onto one substrate primitive on the [`AplicacaoError`]
34789    // envelope, projecting through the paired [`WitContract::source`] /
34790    // [`WitContract::world_ref`] scalar accessors on the substrate
34791    // primitive. A byte-mismatched ctor body would trip the equivalence
34792    // pin first, ahead of any downstream diagnostic-shape drift.
34793    //
34794    // Peer of the sibling standalone-ctor equivalence pins on the peer
34795    // one-off variants across caixa-core:
34796    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
34797    // (cdf1a2c) above on the paired three-slot `{ de, para, endpoint }`
34798    // envelope, the sibling
34799    // `contrato_endpoint_empty_ctor_matches_struct_literal_wrap` +
34800    // `contrato_endpoint_invalid_ctor_matches_struct_literal_wrap` on
34801    // the paired two-slot and four-slot per-`:contratos :endpoint`
34802    // envelopes, and the sibling
34803    // `entrada_host_invalid_ctor_matches_struct_literal_wrap` (17dd504)
34804    // pin on the sibling standalone `{ host, reason }` two-slot ctor.
34805    fn contrato_self_loop_ctor_fixture() -> WitContract {
34806        WitContract {
34807            de: "cart".to_string(),
34808            para: "cart".to_string(),
34809            wit: "wasi:http/proxy".to_string(),
34810            endpoint: Some("/self".to_string()),
34811            subject: None,
34812            slot: None,
34813        }
34814    }
34815
34816    #[test]
34817    fn contrato_self_loop_ctor_matches_struct_literal_wrap() {
34818        // Equivalence pin: the ctor produces byte-equal
34819        // `AplicacaoError::ContratoSelfLoop` to the pre-lift open-coded
34820        // struct-literal that read the same two fields through
34821        // [`WitContract::source`] and [`WitContract::world_ref`]. Guards
34822        // any future field-addition / reordering / string-conversion
34823        // tweak on the variant. Same equivalence-pin shape as the
34824        // sibling `contrato_endpoint_not_absolute_ctor_matches_
34825        // struct_literal_wrap` (cdf1a2c) on the paired three-slot
34826        // per-`:contratos :endpoint` envelope.
34827        let contract = contrato_self_loop_ctor_fixture();
34828        let lifted = AplicacaoError::contrato_self_loop(&contract);
34829        let struct_literal = AplicacaoError::ContratoSelfLoop {
34830            caixa: contract.source().to_string(),
34831            wit: contract.world_ref().to_string(),
34832        };
34833        assert_eq!(lifted, struct_literal);
34834    }
34835
34836    #[test]
34837    fn contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim() {
34838        // Routing pin sweeping non-default `caixa` and `:wit` values
34839        // (`"catalog-v2"` / `"nats:pub-sub"`) through the paired
34840        // [`WitContract::source`] / [`WitContract::world_ref`] accessor
34841        // axes so any wrapper-side lowercase / trim / re-order surfaces
34842        // here rather than at a downstream diagnostic-shape drift.
34843        // Peer of the sibling
34844        // `contrato_endpoint_not_absolute_ctor_routes_edge_pair_through_verbatim`
34845        // (cdf1a2c) routing pin on the sibling three-slot envelope.
34846        let contract = WitContract {
34847            de: "catalog-v2".to_string(),
34848            para: "catalog-v2".to_string(),
34849            wit: "nats:pub-sub".to_string(),
34850            endpoint: None,
34851            subject: Some("orders.>".to_string()),
34852            slot: None,
34853        };
34854        let built = AplicacaoError::contrato_self_loop(&contract);
34855        match built {
34856            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
34857                assert_eq!(
34858                    caixa, "catalog-v2",
34859                    "caixa slot must thread WitContract::source() verbatim"
34860                );
34861                assert_eq!(
34862                    wit, "nats:pub-sub",
34863                    "wit slot must thread WitContract::world_ref() verbatim"
34864                );
34865            }
34866            other => panic!("expected ContratoSelfLoop, got {other:?}"),
34867        }
34868    }
34869
34870    #[test]
34871    fn contrato_self_loop_ctor_projects_source_field_not_destination() {
34872        // Accessor-fidelity pin: the ctor's `caixa` slot keys off the
34873        // [`WitContract::source`] accessor (matching the pre-lift open-
34874        // coded body's field selection), not [`WitContract::destination`].
34875        // Under today's `WitContract::is_self_loop()`-gated call site
34876        // the two are equal by that predicate's own contract, but a
34877        // future consumer that constructs the ctor against a not-yet-
34878        // gated candidate contract — an M4
34879        // `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook re-
34880        // checking a per-`(:de, :para)`-patched candidate before the
34881        // self-loop gate re-fires, a per-tenant per-Aplicacao overlay
34882        // resolver rejecting a self-edge introduced by a cluster-local
34883        // `:contratos` override — needs the pre-lift field selection
34884        // pinned so a silent `.destination()` swap at the ctor body
34885        // surfaces here rather than at a downstream diagnostic mis-
34886        // attribution far from the self-loop diagnostic's owner
34887        // (the `caller` side per MESH-COMPOSITION §III.1's typed edge
34888        // direction).
34889        //
34890        // Deliberately constructs a non-self-loop pair (`"cart" →
34891        // "catalog"`) so the two accessors yield distinct bytes on the
34892        // fixture — a `.destination()` swap at the ctor body would land
34893        // `"catalog"` in the `caixa` slot instead of `"cart"` and trip
34894        // the assertion here.
34895        let contract = WitContract {
34896            de: "cart".to_string(),
34897            para: "catalog".to_string(),
34898            wit: "wasi:http/proxy".to_string(),
34899            endpoint: Some("/charge".to_string()),
34900            subject: None,
34901            slot: None,
34902        };
34903        let built = AplicacaoError::contrato_self_loop(&contract);
34904        match built {
34905            AplicacaoError::ContratoSelfLoop { caixa, .. } => {
34906                assert_eq!(
34907                    caixa, "cart",
34908                    "caixa slot must project WitContract::source() (not destination)"
34909                );
34910            }
34911            other => panic!("expected ContratoSelfLoop, got {other:?}"),
34912        }
34913    }
34914
34915    // Pin the four-slot `{ de, para, wit, target }` per-`:contratos`
34916    // whole-edge-dedup sibling of the two-slot per-`:contratos` envelope
34917    // family — the sole per-axis ctor projecting through both
34918    // [`WitContract::edge_triple`] (on the leading `de` / `para` / `wit`
34919    // triple) and [`WitTarget::label`] (on the trailing `target` slot).
34920    // Equivalence pin locks the ctor body to the pre-lift struct-literal
34921    // shape under `PartialEq`, so any accessor-side field-selection drift
34922    // or per-arm wrapper transformation surfaces here as a build-time
34923    // test failure rather than at a downstream diagnostic-shape mismatch
34924    // far from the substrate primitive. Peer of the sibling
34925    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe)
34926    // equivalence pin on the paired two-slot `{ caixa, wit }` per-self-
34927    // edge envelope's `WitContract`-projection ctor.
34928    #[test]
34929    fn contrato_duplicate_ctor_matches_struct_literal_wrap() {
34930        let contract = contrato_self_loop_ctor_fixture();
34931        let target = contract.target_projected();
34932        let lifted = AplicacaoError::contrato_duplicate(&contract, &target);
34933        let (de, para, wit) = contract.edge_triple();
34934        let struct_literal = AplicacaoError::ContratoDuplicate {
34935            de,
34936            para,
34937            wit,
34938            target: target.label(),
34939        };
34940        assert_eq!(lifted, struct_literal);
34941    }
34942
34943    // Routing pin sweeping a non-self-loop pair (`"cart" → "catalog"`) so
34944    // the paired [`WitContract::edge_triple`] projection's three axes
34945    // (`de`, `para`, `wit`) and the [`WitTarget::label`] projection on
34946    // the `target` axis all yield distinct bytes on the fixture — any
34947    // wrapper-side re-order / accessor-swap on the four axes surfaces
34948    // here rather than at a downstream diagnostic-shape drift. Peer of
34949    // the sibling
34950    // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
34951    // (b30edfe) routing pin on the paired two-slot envelope.
34952    #[test]
34953    fn contrato_duplicate_ctor_routes_edge_triple_and_target_label_verbatim() {
34954        let contract = WitContract {
34955            de: "cart".to_string(),
34956            para: "catalog".to_string(),
34957            wit: "wasi:http/proxy".to_string(),
34958            endpoint: Some("/charge".to_string()),
34959            subject: None,
34960            slot: None,
34961        };
34962        let target = contract.target_projected();
34963        let built = AplicacaoError::contrato_duplicate(&contract, &target);
34964        match built {
34965            AplicacaoError::ContratoDuplicate {
34966                de,
34967                para,
34968                wit,
34969                target,
34970            } => {
34971                assert_eq!(
34972                    de, "cart",
34973                    "de slot must thread WitContract::edge_triple().0 verbatim"
34974                );
34975                assert_eq!(
34976                    para, "catalog",
34977                    "para slot must thread WitContract::edge_triple().1 verbatim"
34978                );
34979                assert_eq!(
34980                    wit, "wasi:http/proxy",
34981                    "wit slot must thread WitContract::edge_triple().2 verbatim"
34982                );
34983                assert!(
34984                    target.contains("/charge"),
34985                    "target slot must project through WitTarget::label() \
34986                     (got target = {target:?})"
34987                );
34988            }
34989            other => panic!("expected ContratoDuplicate, got {other:?}"),
34990        }
34991    }
34992
34993    // Per-variant equivalence pins for the [`aplicacao_caixa_only_ctors!`]
34994    // macro definition (see the paired doc-block above the macro definition)
34995    // — every generated `<ctor>(caixa: &str) -> Self` constructor folds the
34996    // uniform `Self::<Variant> { caixa: caixa.to_string() }` one-field
34997    // struct-literal onto one substrate primitive. The four per-variant
34998    // equivalence pins below (fail-before-pass-after by construction — a
34999    // byte-mismatched macro arm would trip its equivalence pin first) lock
35000    // each generated constructor to its struct-literal peer under
35001    // `PartialEq`, so every wire-up in [`WitContract::require_endpoints_in`],
35002    // [`AplicacaoSpec::validate_membros`], and
35003    // [`validate_no_self_membership`] on that variant produces a byte-equal
35004    // `AplicacaoError` to the pre-lift open-coded struct-literal. The
35005    // cross-axis pin that follows (non-default caixa name) routes the sole
35006    // constructor input axis through `.to_string()`, so the fold does not
35007    // silently collapse onto a fixed name.
35008    //
35009    // Peer of the sibling per-variant `<ctor>_matches_struct_literal_wrap`
35010    // and cross-axis `<macro>_route_caixa_through_to_string` pins on the
35011    // sibling `SupervisorError` `{ caixa: String }` envelope (db09650,
35012    // `supervisor_caixa_only_ctors!`), sibling of the peer per-variant +
35013    // cross-axis pins on the peer three `AplicacaoError` sub-family folds
35014    // (14b81d5 / 8580068 / 981060b / 14e13f1), sibling of the peer four
35015    // `LayoutError` families (131ca0d / 0419438 / 1b09f9d / 3fe3dd7), sibling
35016    // of the peer M2 `:behavior` envelope fold (67c31ec,
35017    // `behavior_slot_path_ctors!` `{ slot, path }`), sibling of the peer M2
35018    // `:upgrade-from` envelope folds (8e67041 / 7468ca9), and sibling of the
35019    // peer `DepError` envelope folds (792aa92 / f85f145 / 0e35793).
35020
35021    #[test]
35022    fn contrato_member_missing_ctor_matches_struct_literal_wrap() {
35023        assert_eq!(
35024            AplicacaoError::contrato_member_missing("cart"),
35025            AplicacaoError::ContratoMemberMissing {
35026                caixa: "cart".to_string(),
35027            },
35028            "generated contrato_member_missing ctor must produce byte-equal \
35029             AplicacaoError to the open-coded struct-literal wrap on the \
35030             same &str fixture",
35031        );
35032    }
35033
35034    #[test]
35035    fn membro_versao_empty_ctor_matches_struct_literal_wrap() {
35036        assert_eq!(
35037            AplicacaoError::membro_versao_empty("cart"),
35038            AplicacaoError::MembroVersaoEmpty {
35039                caixa: "cart".to_string(),
35040            },
35041            "generated membro_versao_empty ctor must produce byte-equal \
35042             AplicacaoError to the open-coded struct-literal wrap on the \
35043             same &str fixture",
35044        );
35045    }
35046
35047    #[test]
35048    fn membro_duplicate_ctor_matches_struct_literal_wrap() {
35049        assert_eq!(
35050            AplicacaoError::membro_duplicate("cart"),
35051            AplicacaoError::MembroDuplicate {
35052                caixa: "cart".to_string(),
35053            },
35054            "generated membro_duplicate ctor must produce byte-equal \
35055             AplicacaoError to the open-coded struct-literal wrap on the \
35056             same &str fixture",
35057        );
35058    }
35059
35060    #[test]
35061    fn membro_is_self_aplicacao_ctor_matches_struct_literal_wrap() {
35062        assert_eq!(
35063            AplicacaoError::membro_is_self_aplicacao("checkout"),
35064            AplicacaoError::MembroIsSelfAplicacao {
35065                caixa: "checkout".to_string(),
35066            },
35067            "generated membro_is_self_aplicacao ctor must produce byte-equal \
35068             AplicacaoError to the open-coded struct-literal wrap on the \
35069             same &str fixture",
35070        );
35071    }
35072
35073    #[test]
35074    fn aplicacao_caixa_only_ctors_route_caixa_through_to_string() {
35075        // Cross-axis pin: sweep the sole constructor input axis (`caixa:
35076        // &str`) through a non-default fixture name against every generated
35077        // arm in the [`aplicacao_caixa_only_ctors!`] macro, so any
35078        // wrapper-side lowercase / trim / truncate / re-order on the
35079        // `caixa.to_string()` sole-field construction surfaces here rather
35080        // than at a downstream diagnostic-shape mismatch. Peer of the
35081        // sibling `supervisor_caixa_only_ctors_route_caixa_through_to_string`
35082        // cross-axis pin on the sibling `SupervisorError` `{ caixa: String }`
35083        // envelope (db09650), extended here onto the peer `AplicacaoError`
35084        // `{ caixa: String }` envelope so every substrate-primitive ctor
35085        // family in caixa-core carrying a single-slot `{ caixa: String }`
35086        // shape guarantees the sole-field construction routes the caller's
35087        // `&str` through `.to_string()` verbatim.
35088        let name = "cache-v2";
35089        assert_eq!(
35090            AplicacaoError::contrato_member_missing(name),
35091            AplicacaoError::ContratoMemberMissing {
35092                caixa: name.to_string(),
35093            },
35094        );
35095        assert_eq!(
35096            AplicacaoError::membro_versao_empty(name),
35097            AplicacaoError::MembroVersaoEmpty {
35098                caixa: name.to_string(),
35099            },
35100        );
35101        assert_eq!(
35102            AplicacaoError::membro_duplicate(name),
35103            AplicacaoError::MembroDuplicate {
35104                caixa: name.to_string(),
35105            },
35106        );
35107        assert_eq!(
35108            AplicacaoError::membro_is_self_aplicacao(name),
35109            AplicacaoError::MembroIsSelfAplicacao {
35110                caixa: name.to_string(),
35111            },
35112        );
35113    }
35114
35115    #[test]
35116    fn entrada_path_not_absolute_ctor_matches_struct_literal_wrap() {
35117        assert_eq!(
35118            AplicacaoError::entrada_path_not_absolute("api/cart"),
35119            AplicacaoError::EntradaPathNotAbsolute {
35120                path: "api/cart".to_string(),
35121            },
35122            "generated entrada_path_not_absolute ctor must produce byte-equal \
35123             AplicacaoError to the open-coded struct-literal wrap on the \
35124             same &str fixture",
35125        );
35126    }
35127
35128    #[test]
35129    fn entrada_path_duplicate_ctor_matches_struct_literal_wrap() {
35130        assert_eq!(
35131            AplicacaoError::entrada_path_duplicate("/api/cart"),
35132            AplicacaoError::EntradaPathDuplicate {
35133                path: "/api/cart".to_string(),
35134            },
35135            "generated entrada_path_duplicate ctor must produce byte-equal \
35136             AplicacaoError to the open-coded struct-literal wrap on the \
35137             same &str fixture",
35138        );
35139    }
35140
35141    // ── membro_versao_invalid ctor pins ────────────────────────────────
35142    //
35143    // Per-variant byte-equality + cross-axis routing pins guaranteeing the
35144    // lifted [`AplicacaoError::membro_versao_invalid`] inherent constructor
35145    // produces an `AplicacaoError` structurally identical to the pre-lift
35146    // `Self::MembroVersaoInvalid { caixa: caixa.to_string(), versao:
35147    // versao.to_string(), reason: reason.into() }` open-coded three-slot
35148    // struct-literal on the same `(&str, &str, reason)` fixture. Peer of
35149    // the sibling `child_versao_invalid_ctor_matches_struct_literal_wrap` +
35150    // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
35151    // pins on the peer `SupervisorError` `{ caixa: String, versao: String,
35152    // reason: String }` envelope's per-`:children :versao` axis (d2ef2ec),
35153    // extended here onto the paired per-`:membros :versao` axis on the
35154    // sibling `AplicacaoError` envelope so both three-slot `{ caixa,
35155    // versao, reason }` per-caixa-versao-invalidation ctors on caixa-core's
35156    // typed-error surface guarantee the shared three-field construction
35157    // routes through one substrate primitive per envelope.
35158
35159    #[test]
35160    fn membro_versao_invalid_ctor_matches_struct_literal_wrap() {
35161        let caixa = "cart";
35162        let versao = "not-a-req";
35163        let reason = "sample reason text";
35164        assert_eq!(
35165            AplicacaoError::membro_versao_invalid(caixa, versao, reason),
35166            AplicacaoError::MembroVersaoInvalid {
35167                caixa: caixa.to_string(),
35168                versao: versao.to_string(),
35169                reason: reason.to_string(),
35170            },
35171            "lifted membro_versao_invalid ctor must produce byte-equal \
35172             AplicacaoError to the open-coded struct-literal wrap on the \
35173             same (&str, &str, reason) fixture",
35174        );
35175    }
35176
35177    #[test]
35178    fn membro_versao_invalid_ctor_routes_caixa_and_versao_through_to_string() {
35179        // Cross-axis pin: sweep the two `&str`-shaped constructor input
35180        // axes (`caixa`, `versao`) through non-default fixtures so any
35181        // wrapper-side lowercase / trim / truncate / re-order on either
35182        // `.to_string()` field construction surfaces here rather than at
35183        // a downstream diagnostic-shape mismatch. Peer of the sibling
35184        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
35185        // routing pin on the peer `SupervisorError` envelope.
35186        let caixa = "Cart-V2";
35187        let versao = "0.1.0-alpha+build.42";
35188        let reason = "constructed reason";
35189        let err = AplicacaoError::membro_versao_invalid(caixa, versao, reason);
35190        let AplicacaoError::MembroVersaoInvalid {
35191            caixa: got_caixa,
35192            versao: got_versao,
35193            reason: got_reason,
35194        } = err
35195        else {
35196            panic!("membro_versao_invalid must construct MembroVersaoInvalid variant");
35197        };
35198        assert_eq!(got_caixa, caixa.to_string());
35199        assert_eq!(got_versao, versao.to_string());
35200        assert_eq!(got_reason, reason.to_string());
35201    }
35202
35203    #[test]
35204    fn membro_versao_invalid_ctor_routes_reason_through_into() {
35205        // Route pin: the `reason: impl Into<String>` bound accepts both
35206        // `&str` literals and `format!(…)` / `String` outputs verbatim,
35207        // matching the sibling
35208        // `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
35209        // routing pin on the peer `SupervisorError::child_versao_invalid`.
35210        // Pins the sole `AplicacaoSpec::validate_membros` wire-up's
35211        // `require_valid_versao_requirement`-delivered `reason` closure
35212        // parameter (typed `String`) picks the ctor up without a per-arm
35213        // wrapper transformation, and every future consumer that
35214        // constructs the variant from a `format!(…)` reason surfaces
35215        // byte-equal to the `&str`-literal path.
35216        let caixa = "cart";
35217        let versao = "not-a-req";
35218        let from_literal = AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason");
35219        let from_format =
35220            AplicacaoError::membro_versao_invalid(caixa, versao, format!("{} reason", "literal"));
35221        let from_string =
35222            AplicacaoError::membro_versao_invalid(caixa, versao, "literal reason".to_string());
35223        assert_eq!(from_literal, from_format);
35224        assert_eq!(from_literal, from_string);
35225    }
35226
35227    #[test]
35228    fn aplicacao_path_only_ctors_route_path_through_to_string() {
35229        // Cross-axis pin: sweep the sole constructor input axis (`path:
35230        // &str`) through a non-default fixture path against every generated
35231        // arm in the [`aplicacao_path_only_ctors!`] macro, so any
35232        // wrapper-side lowercase / trim / truncate / re-order on the
35233        // `path.to_string()` sole-field construction surfaces here rather
35234        // than at a downstream diagnostic-shape mismatch. Peer of the
35235        // sibling `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
35236        // cross-axis pin on the peer `AplicacaoError` `{ caixa: String }`
35237        // envelope (d9f6867), extended here onto the sibling
35238        // `AplicacaoError` `{ path: String }` envelope so every substrate-
35239        // primitive ctor family in caixa-core carrying a single-slot
35240        // `{ <slot>: String }` shape guarantees the sole-field construction
35241        // routes the caller's `&str` through `.to_string()` verbatim.
35242        let path = "/api/v2/checkout";
35243        assert_eq!(
35244            AplicacaoError::entrada_path_not_absolute(path),
35245            AplicacaoError::EntradaPathNotAbsolute {
35246                path: path.to_string(),
35247            },
35248        );
35249        assert_eq!(
35250            AplicacaoError::entrada_path_duplicate(path),
35251            AplicacaoError::EntradaPathDuplicate {
35252                path: path.to_string(),
35253            },
35254        );
35255    }
35256
35257    // ── aplicacao_policy_scalar_ctors! per-variant + cross-axis pins ────────
35258    //
35259    // Per-variant byte-equality pins guaranteeing every generated ctor arm in
35260    // the [`aplicacao_policy_scalar_ctors!`] macro produces an `AplicacaoError`
35261    // structurally identical to the pre-lift `Self::<variant> { <field>: <val> }`
35262    // one-line struct-literal on the same `Copy`-`Duration | u32` fixture, plus
35263    // one cross-axis sweep that routes each per-variant `<field>: <ty>` scalar
35264    // through the sole `$field:ident: $ty:ty` axis the macro exposes so any
35265    // wrapper-side truncation / re-order / silent `.into()` / silent constant-
35266    // substitution on any one variant surfaces here rather than at a downstream
35267    // per-`:politicas` diagnostic-shape drift. Peer of the sibling per-variant
35268    // pins on `aplicacao_field_reason_ctors!` (981060b),
35269    // `aplicacao_caixa_only_ctors!` (d9f6867), `aplicacao_path_only_ctors!`
35270    // (3ba8de6), `contrato_pair_value_reason_ctors!` (14e13f1),
35271    // `contrato_empty_pair_ctors!` (8580068), `contrato_target_ctors!`
35272    // (14b81d5), plus the sibling `DepError` / `SupervisorError` /
35273    // `LayoutError` / `LimitsError` / `BehaviorError` / `UpgradeError`
35274    // per-envelope ctor-macro pins.
35275
35276    #[test]
35277    fn policy_timeout_not_canonical_ctor_matches_struct_literal_wrap() {
35278        let timeout = Duration::from_micros(1_500);
35279        assert_eq!(
35280            AplicacaoError::policy_timeout_not_canonical(timeout),
35281            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
35282            "generated policy_timeout_not_canonical ctor must produce byte-equal \
35283             `AplicacaoError::PolicyTimeoutNotCanonical` to the pre-lift \
35284             struct-literal wrap on the same `Copy`-`Duration` fixture",
35285        );
35286    }
35287
35288    #[test]
35289    fn policy_timeout_exceeds_cap_ctor_matches_struct_literal_wrap() {
35290        let timeout = Duration::from_secs(3_601);
35291        assert_eq!(
35292            AplicacaoError::policy_timeout_exceeds_cap(timeout),
35293            AplicacaoError::PolicyTimeoutExceedsCap { timeout },
35294            "generated policy_timeout_exceeds_cap ctor must produce byte-equal \
35295             `AplicacaoError::PolicyTimeoutExceedsCap` to the pre-lift \
35296             struct-literal wrap on the same `Copy`-`Duration` fixture",
35297        );
35298    }
35299
35300    #[test]
35301    fn policy_retries_exceeds_cap_ctor_matches_struct_literal_wrap() {
35302        let retries = 47_u32;
35303        assert_eq!(
35304            AplicacaoError::policy_retries_exceeds_cap(retries),
35305            AplicacaoError::PolicyRetriesExceedsCap { retries },
35306            "generated policy_retries_exceeds_cap ctor must produce byte-equal \
35307             `AplicacaoError::PolicyRetriesExceedsCap` to the pre-lift \
35308             struct-literal wrap on the same `Copy`-`u32` fixture",
35309        );
35310    }
35311
35312    #[test]
35313    fn policy_breaker_max_failures_exceeds_cap_ctor_matches_struct_literal_wrap() {
35314        let max_failures = 1_337_u32;
35315        assert_eq!(
35316            AplicacaoError::policy_breaker_max_failures_exceeds_cap(max_failures),
35317            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
35318            "generated policy_breaker_max_failures_exceeds_cap ctor must produce \
35319             byte-equal `AplicacaoError::PolicyBreakerMaxFailuresExceedsCap` to \
35320             the pre-lift struct-literal wrap on the same `Copy`-`u32` fixture",
35321        );
35322    }
35323
35324    #[test]
35325    fn policy_breaker_window_not_canonical_ctor_matches_struct_literal_wrap() {
35326        let window = Duration::from_micros(500);
35327        assert_eq!(
35328            AplicacaoError::policy_breaker_window_not_canonical(window),
35329            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
35330            "generated policy_breaker_window_not_canonical ctor must produce \
35331             byte-equal `AplicacaoError::PolicyBreakerWindowNotCanonical` to the \
35332             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
35333        );
35334    }
35335
35336    #[test]
35337    fn policy_breaker_window_exceeds_cap_ctor_matches_struct_literal_wrap() {
35338        let window = Duration::from_secs(3_700);
35339        assert_eq!(
35340            AplicacaoError::policy_breaker_window_exceeds_cap(window),
35341            AplicacaoError::PolicyBreakerWindowExceedsCap { window },
35342            "generated policy_breaker_window_exceeds_cap ctor must produce \
35343             byte-equal `AplicacaoError::PolicyBreakerWindowExceedsCap` to the \
35344             pre-lift struct-literal wrap on the same `Copy`-`Duration` fixture",
35345        );
35346    }
35347
35348    #[test]
35349    fn policy_rate_limit_exceeds_cap_ctor_matches_struct_literal_wrap() {
35350        let rate = 1_000_001_u32;
35351        assert_eq!(
35352            AplicacaoError::policy_rate_limit_exceeds_cap(rate),
35353            AplicacaoError::PolicyRateLimitExceedsCap { rate },
35354            "generated policy_rate_limit_exceeds_cap ctor must produce byte-equal \
35355             `AplicacaoError::PolicyRateLimitExceedsCap` to the pre-lift \
35356             struct-literal wrap on the same `Copy`-`u32` fixture",
35357        );
35358    }
35359
35360    #[test]
35361    fn policy_rate_limit_window_not_canonical_ctor_matches_struct_literal_wrap() {
35362        let window = Duration::from_secs(15);
35363        assert_eq!(
35364            AplicacaoError::policy_rate_limit_window_not_canonical(window),
35365            AplicacaoError::PolicyRateLimitWindowNotCanonical { window },
35366            "generated policy_rate_limit_window_not_canonical ctor must produce \
35367             byte-equal `AplicacaoError::PolicyRateLimitWindowNotCanonical` to \
35368             the pre-lift struct-literal wrap on the same `Copy`-`Duration` \
35369             fixture",
35370        );
35371    }
35372
35373    #[test]
35374    fn aplicacao_policy_scalar_ctors_route_field_through_copy_uniformly() {
35375        // Cross-axis routing pin: sweep each generated `<field>: <ty>`
35376        // constructor input axis through a non-default `Copy` fixture against
35377        // every arm in the [`aplicacao_policy_scalar_ctors!`] macro, so any
35378        // wrapper-side silent `.into()` / silent constant-substitution / silent
35379        // field re-name away from the canonical `timeout | retries |
35380        // max_failures | window | rate` axes on any one variant, or a
35381        // `Duration | u32` axis silently rerouted through some other `Copy`
35382        // coercion, surfaces here rather than at a downstream per-`:politicas`
35383        // diagnostic-shape drift. Peer of the sibling
35384        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
35385        // (d9f6867), `aplicacao_path_only_ctors_route_path_through_to_string`
35386        // (3ba8de6), `dep_nome_list_ctors_route_nome_and_list_through_uniformly`
35387        // (6f5e0cd), and `supervisor_child_reason_ctors_route_reason_through_into_uniformly`
35388        // (d2ef2ec) cross-axis routing pins on the peer per-envelope ctor
35389        // families, extended here onto the last M3 per-`:politicas` per-axis
35390        // `AplicacaoError` variant family folded onto a substrate primitive.
35391        //
35392        // Fixtures picked out of each variant's accept-set boundary rather
35393        // than the default value so a silent constant-substitution to `0` /
35394        // `Duration::ZERO` / any per-variant sentinel surfaces here on the
35395        // structural-equality assertion. The two `Duration` fixtures pick the
35396        // sub-millisecond and above-cap ends respectively; the three `u32`
35397        // fixtures pick above-cap magnitudes for `retries` / `max_failures` /
35398        // `rate` respectively (each variant's cap sits well below the fixture
35399        // so the pre-lift struct-literal wrap the fixture is compared against
35400        // is the same shape the pre-lift wire-up produced).
35401        let sub_ms = Duration::from_micros(1_500);
35402        let above_hour = Duration::from_secs(3_700);
35403        let non_canonical_rl_window = Duration::from_secs(15);
35404        assert_eq!(
35405            AplicacaoError::policy_timeout_not_canonical(sub_ms),
35406            AplicacaoError::PolicyTimeoutNotCanonical { timeout: sub_ms },
35407        );
35408        assert_eq!(
35409            AplicacaoError::policy_timeout_exceeds_cap(above_hour),
35410            AplicacaoError::PolicyTimeoutExceedsCap {
35411                timeout: above_hour,
35412            },
35413        );
35414        assert_eq!(
35415            AplicacaoError::policy_retries_exceeds_cap(47),
35416            AplicacaoError::PolicyRetriesExceedsCap { retries: 47 },
35417        );
35418        assert_eq!(
35419            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_337),
35420            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
35421                max_failures: 1_337,
35422            },
35423        );
35424        assert_eq!(
35425            AplicacaoError::policy_breaker_window_not_canonical(sub_ms),
35426            AplicacaoError::PolicyBreakerWindowNotCanonical { window: sub_ms },
35427        );
35428        assert_eq!(
35429            AplicacaoError::policy_breaker_window_exceeds_cap(above_hour),
35430            AplicacaoError::PolicyBreakerWindowExceedsCap { window: above_hour },
35431        );
35432        assert_eq!(
35433            AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001),
35434            AplicacaoError::PolicyRateLimitExceedsCap { rate: 1_000_001 },
35435        );
35436        assert_eq!(
35437            AplicacaoError::policy_rate_limit_window_not_canonical(non_canonical_rl_window),
35438            AplicacaoError::PolicyRateLimitWindowNotCanonical {
35439                window: non_canonical_rl_window,
35440            },
35441        );
35442    }
35443
35444    #[test]
35445    fn aplicacao_policy_scalar_ctors_are_const_zero_runtime_work() {
35446        // Const-eval pin: the [`aplicacao_policy_scalar_ctors!`] macro spells
35447        // every generated ctor `const fn` so a caller can pin an
35448        // `AplicacaoError` at compile time — the same zero-runtime-work
35449        // property the pre-lift `|<slot>| AplicacaoError::<Variant> { <slot> }`
35450        // closure carried on its `Copy`-pass-through construction path (no
35451        // `.to_string()` / `.into()` allocation, no branching). If any future
35452        // edit silently drops the `const` qualifier from the macro body the
35453        // per-arm `const` bindings below fail to compile, which surfaces the
35454        // regression at the substrate-primitive definition rather than at
35455        // some downstream consumer that had come to rely on the `const`-
35456        // constructibility. Peer of the sibling per-variant
35457        // `_ctor_matches_struct_literal_wrap` pins above on the runtime-
35458        // equality axis; this pin closes the compile-time-const axis on the
35459        // same generated family.
35460        const TIMEOUT_NC: AplicacaoError =
35461            AplicacaoError::policy_timeout_not_canonical(Duration::from_micros(1));
35462        const TIMEOUT_CAP: AplicacaoError =
35463            AplicacaoError::policy_timeout_exceeds_cap(Duration::from_secs(3_601));
35464        const RETRIES_CAP: AplicacaoError = AplicacaoError::policy_retries_exceeds_cap(11);
35465        const MAX_FAIL_CAP: AplicacaoError =
35466            AplicacaoError::policy_breaker_max_failures_exceeds_cap(1_001);
35467        const CB_WIN_NC: AplicacaoError =
35468            AplicacaoError::policy_breaker_window_not_canonical(Duration::from_micros(1));
35469        const CB_WIN_CAP: AplicacaoError =
35470            AplicacaoError::policy_breaker_window_exceeds_cap(Duration::from_secs(3_601));
35471        const RATE_CAP: AplicacaoError = AplicacaoError::policy_rate_limit_exceeds_cap(1_000_001);
35472        const RL_WIN_NC: AplicacaoError =
35473            AplicacaoError::policy_rate_limit_window_not_canonical(Duration::from_secs(15));
35474        assert!(matches!(
35475            TIMEOUT_NC,
35476            AplicacaoError::PolicyTimeoutNotCanonical { .. }
35477        ));
35478        assert!(matches!(
35479            TIMEOUT_CAP,
35480            AplicacaoError::PolicyTimeoutExceedsCap { .. }
35481        ));
35482        assert!(matches!(
35483            RETRIES_CAP,
35484            AplicacaoError::PolicyRetriesExceedsCap { .. }
35485        ));
35486        assert!(matches!(
35487            MAX_FAIL_CAP,
35488            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { .. }
35489        ));
35490        assert!(matches!(
35491            CB_WIN_NC,
35492            AplicacaoError::PolicyBreakerWindowNotCanonical { .. }
35493        ));
35494        assert!(matches!(
35495            CB_WIN_CAP,
35496            AplicacaoError::PolicyBreakerWindowExceedsCap { .. }
35497        ));
35498        assert!(matches!(
35499            RATE_CAP,
35500            AplicacaoError::PolicyRateLimitExceedsCap { .. }
35501        ));
35502        assert!(matches!(
35503            RL_WIN_NC,
35504            AplicacaoError::PolicyRateLimitWindowNotCanonical { .. }
35505        ));
35506    }
35507
35508    // Per-variant equivalence + routing pins for the
35509    // [`AplicacaoError::placement_cluster_duplicate`] standalone ctor
35510    // (see the paired doc-block above the ctor definition) — the
35511    // generated `pub fn placement_cluster_duplicate(cluster: &str) ->
35512    // Self` inherent constructor folds the uniform
35513    // `Self::PlacementClusterDuplicate { cluster: cluster.to_string() }`
35514    // one-field struct-literal onto one substrate primitive. Same
35515    // shape as the sibling
35516    // `contrato_self_loop_ctor_matches_struct_literal_wrap` (b30edfe) /
35517    // `contrato_endpoint_not_absolute_ctor_matches_struct_literal_wrap`
35518    // (cdf1a2c) equivalence pins on the paired standalone `AplicacaoError`
35519    // ctors — extended here onto the single-slot per-`:placement
35520    // :clusters` dedup-envelope.
35521
35522    #[test]
35523    fn placement_cluster_duplicate_ctor_matches_struct_literal_wrap() {
35524        // Equivalence pin: the ctor produces byte-equal
35525        // `AplicacaoError::PlacementClusterDuplicate` to the pre-lift
35526        // open-coded struct-literal that read the same field through
35527        // `c.clone()` at the caller site inside
35528        // [`AplicacaoSpec::validate_placement_shape`]. Guards any future
35529        // field-addition / reordering / string-conversion tweak on the
35530        // variant.
35531        let cluster = "rio";
35532        let lifted = AplicacaoError::placement_cluster_duplicate(cluster);
35533        let struct_literal = AplicacaoError::PlacementClusterDuplicate {
35534            cluster: cluster.to_string(),
35535        };
35536        assert_eq!(lifted, struct_literal);
35537    }
35538
35539    #[test]
35540    fn placement_cluster_duplicate_ctor_routes_cluster_through_to_string() {
35541        // Routing pin: sweep the sole constructor input axis
35542        // (`cluster: &str`) through a non-default fixture name so any
35543        // wrapper-side lowercase / trim / truncate / re-order on the
35544        // `cluster.to_string()` sole-field construction surfaces here
35545        // rather than at a downstream diagnostic-shape mismatch. Peer of
35546        // the sibling
35547        // `aplicacao_caixa_only_ctors_route_caixa_through_to_string`
35548        // (d9f6867) cross-axis pin on the sibling one-slot
35549        // `{ caixa: String }` envelope — extended here onto the sibling
35550        // `{ cluster: String }` envelope so the sole `String`-slot
35551        // construction routes the caller's `&str` through `.to_string()`
35552        // verbatim.
35553        let cluster = "sao-paulo-2";
35554        let built = AplicacaoError::placement_cluster_duplicate(cluster);
35555        match built {
35556            AplicacaoError::PlacementClusterDuplicate { cluster: c } => {
35557                assert_eq!(
35558                    c, cluster,
35559                    "cluster slot must thread the caller's `&str` verbatim through .to_string()"
35560                );
35561            }
35562            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
35563        }
35564    }
35565
35566    // Per-variant equivalence + routing pins for the
35567    // [`AplicacaoError::placement_without_clusters`] standalone ctor
35568    // (see the paired doc-block above the ctor definition) — the
35569    // generated `pub const fn placement_without_clusters(placement:
35570    // &Placement) -> Self` inherent constructor folds the uniform
35571    // `Self::PlacementWithoutClusters { estrategia: placement.estrategia()
35572    // }` one-field `Copy`-pass-through struct-literal onto one substrate
35573    // primitive. Same shape as the sibling
35574    // `placement_cluster_duplicate_ctor_matches_struct_literal_wrap`
35575    // (92b1c92) / `contrato_self_loop_ctor_matches_struct_literal_wrap`
35576    // (b30edfe) equivalence pins on the paired standalone `AplicacaoError`
35577    // ctors — extended here onto the one-slot per-`:placement`
35578    // empty-clusters envelope.
35579
35580    #[test]
35581    fn placement_without_clusters_ctor_matches_struct_literal_wrap() {
35582        // Equivalence pin: the ctor produces byte-equal
35583        // `AplicacaoError::PlacementWithoutClusters` to the pre-lift
35584        // open-coded struct-literal that read the same field through
35585        // `p.estrategia()` at the caller site inside
35586        // [`AplicacaoSpec::validate_placement`]. Guards any future
35587        // field-addition / reordering / accessor-return tweak on the
35588        // variant.
35589        let placement = Placement {
35590            estrategia: PlacementStrategy::Replicated,
35591            clusters: vec![],
35592            affinity: None,
35593            shard_key: None,
35594        };
35595        let lifted = AplicacaoError::placement_without_clusters(&placement);
35596        let struct_literal = AplicacaoError::PlacementWithoutClusters {
35597            estrategia: placement.estrategia(),
35598        };
35599        assert_eq!(lifted, struct_literal);
35600    }
35601
35602    #[test]
35603    fn placement_without_clusters_ctor_routes_estrategia_through_accessor() {
35604        // Routing pin: sweep the sole constructor input axis
35605        // (`placement: &Placement`) through every variant in the closed
35606        // [`PlacementStrategy::ALL`] accept-set so any wrapper-side
35607        // re-derivation / off-by-one arm-swap / stale-field read on the
35608        // `placement.estrategia()` sole-field projection surfaces here
35609        // rather than at a downstream diagnostic-shape mismatch. Peer of
35610        // the sibling
35611        // `validate_placement_reads_through_lifted_estrategia_accessor`
35612        // three-consumer coherence pin — extended here onto the ctor
35613        // itself so the accessor-projection posture is byte-witnessed at
35614        // the substrate primitive rather than only at the caller-site
35615        // fan-out. Sweeps all three [`PlacementStrategy`] variants so any
35616        // future addition to the closed accept-set surfaces as an
35617        // exhaustiveness gap on this iteration list.
35618        for estrategia in [
35619            PlacementStrategy::SingleNode,
35620            PlacementStrategy::Replicated,
35621            PlacementStrategy::Sharded,
35622        ] {
35623            let placement = Placement {
35624                estrategia,
35625                clusters: vec![],
35626                affinity: None,
35627                shard_key: None,
35628            };
35629            let built = AplicacaoError::placement_without_clusters(&placement);
35630            match built {
35631                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
35632                    assert_eq!(
35633                        e,
35634                        placement.estrategia(),
35635                        "estrategia slot must thread the caller's `Placement` verbatim \
35636                         through Placement::estrategia() — the ctor reads through the \
35637                         lifted accessor",
35638                    );
35639                    assert_eq!(
35640                        e, estrategia,
35641                        "estrategia slot must byte-equal the fixture-declared variant",
35642                    );
35643                }
35644                other => panic!("expected PlacementWithoutClusters, got {other:?}"),
35645            }
35646        }
35647    }
35648
35649    #[test]
35650    fn placement_without_clusters_ctor_is_const_fn() {
35651        // Fail-before-pass-after pin on
35652        // [`AplicacaoError::placement_without_clusters`]'s `const`-eval-
35653        // surface posture. The ctor threads the paired
35654        // [`Placement::estrategia`] `const fn` `Copy`-scalar accessor's
35655        // return through one `const fn` construction — any future
35656        // accidental downgrade to non-`const` (a `.clone()` on the
35657        // `Copy`-scalar `estrategia:` field expression, an owned-`String`
35658        // materialization on the sibling non-`estrategia:` axis) fails
35659        // `placement_without_clusters_via_const_fn` at caixa-core build
35660        // time with E0015 (`cannot call non-const method`), strictly
35661        // stronger than a runtime `assert!`. Sibling of the peer
35662        // [`aplicacao_policy_scalar_ctors!`] (7ef425e) family's `const fn`
35663        // posture on the sibling per-`:politicas` cap-scalar envelopes
35664        // and the peer [`Placement::estrategia`] const-fn accessor pin at
35665        // [`placement_estrategia_accessor_is_const_fn`] on the paired
35666        // substrate primitive.
35667        const fn placement_without_clusters_via_const_fn(p: &Placement) -> AplicacaoError {
35668            AplicacaoError::placement_without_clusters(p)
35669        }
35670        let placement = Placement {
35671            estrategia: PlacementStrategy::Sharded,
35672            clusters: vec![],
35673            affinity: None,
35674            shard_key: Some("tenantId".into()),
35675        };
35676        assert_eq!(
35677            placement_without_clusters_via_const_fn(&placement),
35678            AplicacaoError::placement_without_clusters(&placement),
35679        );
35680    }
35681
35682    #[test]
35683    fn entrada_member_missing_ctor_matches_struct_literal_wrap() {
35684        // Equivalence pin: the ctor produces byte-equal
35685        // `AplicacaoError::EntradaMemberMissing` to the pre-lift
35686        // open-coded struct-literal that read the same `:para` value
35687        // through `e.destination().to_string()` at the caller site
35688        // inside [`AplicacaoSpec::validate_entrada`]. Guards any future
35689        // field-addition / reordering / accessor-return tweak on the
35690        // variant. Sibling of the peer
35691        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
35692        // and `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
35693        // pins on the sibling per-`:placement` envelope, and sibling of
35694        // the peer `contrato_member_missing_ctor_matches_struct_literal_wrap`
35695        // pin on the sibling per-`:membros :caixa` envelope.
35696        let entrada = Entrada {
35697            host: "checkout.quero.cloud".into(),
35698            para: "phantom-shim".into(),
35699            paths: vec!["/api".into()],
35700            port: 8080,
35701        };
35702        let via_ctor = AplicacaoError::entrada_member_missing(&entrada);
35703        let via_literal = AplicacaoError::EntradaMemberMissing {
35704            para: entrada.destination().to_string(),
35705        };
35706        assert_eq!(
35707            via_ctor, via_literal,
35708            "entrada_member_missing(&entrada) must byte-equal the open-coded \
35709             EntradaMemberMissing struct-literal on the same &Entrada fixture"
35710        );
35711        assert_eq!(
35712            via_ctor.to_string(),
35713            via_literal.to_string(),
35714            "Display byte-string must byte-equal the open-coded struct-literal"
35715        );
35716    }
35717
35718    #[test]
35719    fn entrada_member_missing_ctor_routes_para_through_entrada_accessor() {
35720        // Boundary-sweep pin on the ctor's substrate-primitive
35721        // projection: the `para` slot is stored verbatim from
35722        // [`Entrada::destination`] across a representative set of
35723        // `:entrada :para` byte-strings, so any wrapper-side silent
35724        // normalization, `.into()` divergence, accidental field
35725        // rebrand, or per-arm ctor divergence on the sole-field
35726        // projection surfaces at caixa-core build time rather than at
35727        // a downstream diagnostic consumer that reads `err.para` back
35728        // and gets a different value than the one it stored. Peer of
35729        // the sibling
35730        // `shard_key_on_non_sharded_routes_estrategia_through_placement_accessor`
35731        // boundary-sweep pin on the sibling per-`:placement :shard-key`
35732        // envelope and the peer `placement_without_clusters_ctor_routes_estrategia_through_accessor`
35733        // sweep on the sibling per-`:placement` empty-clusters envelope
35734        // — extended here onto the [`Entrada`]-borrow-projected sole
35735        // `para` slot on the sibling per-`:entrada :para` envelope. The
35736        // sweep list carries a mixed set (well-shaped phantom, hyphen-
35737        // digit tail, single-character floor, and the digit-start form
35738        // the peer `accepts_canonical_entrada_para_forms` positive-
35739        // control test also sweeps) so a future silent per-input
35740        // normalization surfaces on the arm that diverges.
35741        for para in [
35742            "phantom-shim",
35743            "cart-v2",
35744            "a",
35745            "c0",
35746            "3rd-party-shim",
35747            "x-1-2-3-4",
35748        ] {
35749            let entrada = Entrada {
35750                host: "checkout.quero.cloud".into(),
35751                para: para.into(),
35752                paths: vec!["/api".into()],
35753                port: 8080,
35754            };
35755            let err = AplicacaoError::entrada_member_missing(&entrada);
35756            let AplicacaoError::EntradaMemberMissing { para: stored_para } = err else {
35757                panic!("entrada_member_missing must construct EntradaMemberMissing for {para:?}");
35758            };
35759            assert_eq!(
35760                stored_para,
35761                entrada.destination(),
35762                "para slot must round-trip verbatim through Entrada::destination() \
35763                 for {para:?}"
35764            );
35765            assert_eq!(
35766                stored_para, para,
35767                "para slot must byte-equal the fixture-declared value for {para:?}"
35768            );
35769        }
35770    }
35771
35772    #[test]
35773    fn validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor() {
35774        // End-to-end pin: the sole in-crate wire-up site
35775        // (`AplicacaoSpec::validate_entrada`'s membership-lookup arm)
35776        // routes through [`AplicacaoError::entrada_member_missing`] and
35777        // the observed `Err` byte-equals the ctor's output on the same
35778        // well-shaped-phantom `:para` fixture. A future silent de-lift
35779        // of the wire-up back to the open-coded struct-literal trips
35780        // this test at caixa-core build time rather than at a
35781        // downstream diagnostic consumer far from the wire-up commit.
35782        // Sibling of the peer
35783        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
35784        // end-to-end pin on the sibling per-`:placement :shard-key`
35785        // envelope, and sibling of the peer
35786        // `entrada_para_well_shaped_phantom_still_raises_member_missing`
35787        // pattern-match pin on the same wire-up — extended here from a
35788        // `matches!` shape check to a byte-identity + Display parity
35789        // route through the ctor.
35790        let mut s = three_member_spec();
35791        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
35792        let observed = s.validate().unwrap_err();
35793        let expected = AplicacaoError::entrada_member_missing(s.entrada.as_ref().unwrap());
35794        assert_eq!(
35795            observed, expected,
35796            "validate_entrada's phantom-reference-arm Err must byte-equal \
35797             entrada_member_missing(&entrada)"
35798        );
35799        assert_eq!(
35800            observed.to_string(),
35801            expected.to_string(),
35802            "Display byte-string parity"
35803        );
35804    }
35805
35806    #[test]
35807    fn contrato_cycle_ctor_matches_struct_literal_wrap() {
35808        // Equivalence pin: the ctor produces byte-equal
35809        // `AplicacaoError::ContratoCycle` to the pre-lift open-coded
35810        // struct-literal that stored the caller-side reconstructed
35811        // cycle path verbatim at the gray-arm cycle-close return inside
35812        // [`AplicacaoSpec::detect_sync_cycles`]. Guards any future
35813        // field-addition / reordering / re-collect divergence on the
35814        // variant. Sibling of the peer
35815        // `entrada_member_missing_ctor_matches_struct_literal_wrap`
35816        // (deeae5c) pin on the sibling per-`:entrada :para`
35817        // phantom-reference envelope, and sibling of the peer
35818        // `placement_without_clusters_ctor_matches_struct_literal_wrap`
35819        // pin on the sibling per-`:placement` empty-clusters envelope.
35820        let cycle = vec![
35821            "cart".to_string(),
35822            "catalog".to_string(),
35823            "cart".to_string(),
35824        ];
35825        let via_ctor = AplicacaoError::contrato_cycle(cycle.clone());
35826        let via_literal = AplicacaoError::ContratoCycle {
35827            cycle: cycle.clone(),
35828        };
35829        assert_eq!(
35830            via_ctor, via_literal,
35831            "contrato_cycle(cycle) must byte-equal the open-coded \
35832             ContratoCycle struct-literal on the same Vec<String> fixture"
35833        );
35834        assert_eq!(
35835            via_ctor.to_string(),
35836            via_literal.to_string(),
35837            "Display byte-string must byte-equal the open-coded struct-literal"
35838        );
35839    }
35840
35841    #[test]
35842    fn contrato_cycle_ctor_routes_path_verbatim() {
35843        // Boundary-sweep pin on the ctor's substrate-primitive
35844        // pass-through: the `cycle` slot is stored verbatim across a
35845        // representative set of reconstructed cycle paths (two-node
35846        // closed loop; three-node loop; long chain with repeated
35847        // interior nodes; a fixture whose first/last coincide by the
35848        // gray-arm's own append-target-once-more discipline), so any
35849        // wrapper-side silent normalization, dedup, sort, `.into()`
35850        // divergence, accidental field rebrand, or re-collect on the
35851        // sole-field pass-through surfaces at caixa-core build time
35852        // rather than at a downstream diagnostic consumer that reads
35853        // `err.cycle` back and gets a different value than the one it
35854        // stored. Peer of the sibling
35855        // `entrada_member_missing_ctor_routes_para_through_entrada_accessor`
35856        // (deeae5c) boundary-sweep pin on the sibling per-`:entrada
35857        // :para` envelope — extended here onto the owned-[`Vec<String>`]
35858        // pass-through on the sibling per-`:contratos` cycle envelope.
35859        for cycle in [
35860            vec![
35861                "cart".to_string(),
35862                "catalog".to_string(),
35863                "cart".to_string(),
35864            ],
35865            vec![
35866                "cart".to_string(),
35867                "catalog".to_string(),
35868                "payment".to_string(),
35869                "cart".to_string(),
35870            ],
35871            vec![
35872                "a".to_string(),
35873                "b".to_string(),
35874                "c".to_string(),
35875                "d".to_string(),
35876                "b".to_string(),
35877            ],
35878            vec!["only".to_string(), "only".to_string()],
35879        ] {
35880            let err = AplicacaoError::contrato_cycle(cycle.clone());
35881            let AplicacaoError::ContratoCycle { cycle: stored } = err else {
35882                panic!("contrato_cycle must construct ContratoCycle for {cycle:?}");
35883            };
35884            assert_eq!(
35885                stored, cycle,
35886                "cycle slot must round-trip the caller-side Vec<String> verbatim \
35887                 for {cycle:?}"
35888            );
35889        }
35890    }
35891
35892    #[test]
35893    fn detect_sync_cycles_arm_routes_through_contrato_cycle_ctor() {
35894        // End-to-end pin: the sole in-crate wire-up site
35895        // (`AplicacaoSpec::detect_sync_cycles`'s gray-arm cycle-close
35896        // return) routes through [`AplicacaoError::contrato_cycle`] and
35897        // the observed `Err` byte-equals the ctor's output on the same
35898        // reconstructed cycle path. A future silent de-lift of the
35899        // wire-up back to the open-coded `AplicacaoError::ContratoCycle
35900        // { cycle }` struct-literal trips this test at caixa-core build
35901        // time rather than at a downstream diagnostic consumer far from
35902        // the wire-up commit. Sibling of the peer
35903        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
35904        // (deeae5c) end-to-end pin on the sibling per-`:entrada :para`
35905        // envelope, and sibling of the peer
35906        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
35907        // (14bafca) end-to-end pin on the sibling per-`:placement
35908        // :shard-key` envelope — extended here from a bare
35909        // `matches!(err, AplicacaoError::ContratoCycle { .. })` shape
35910        // check to a byte-identity route through the ctor.
35911        let mut s = three_member_spec();
35912        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
35913        s.contratos = vec![
35914            contract_http("catalog", "cart", "/x"),
35915            contract_http("cart", "payment", "/y"),
35916            contract_http("payment", "catalog", "/z"),
35917        ];
35918        let observed = s.validate().unwrap_err();
35919        let AplicacaoError::ContratoCycle { ref cycle } = observed else {
35920            panic!("expected ContratoCycle from the sync-cycle detector, got {observed:?}");
35921        };
35922        let expected = AplicacaoError::contrato_cycle(cycle.clone());
35923        assert_eq!(
35924            observed, expected,
35925            "detect_sync_cycles's gray-arm Err must byte-equal \
35926             contrato_cycle(cycle) on the reconstructed cycle path"
35927        );
35928        assert_eq!(
35929            observed.to_string(),
35930            expected.to_string(),
35931            "Display byte-string parity"
35932        );
35933    }
35934
35935    // ── policy_breaker_window_below_timeout standalone ctor pins ────────
35936    //
35937    // Fail-before-pass-after pins for the standalone
35938    // [`AplicacaoError::policy_breaker_window_below_timeout`] inherent
35939    // ctor (see the paired doc-block above the ctor definition) — the
35940    // fold of the last open-coded two-slot `{ window: cb.window(),
35941    // timeout: t }` struct-literal inside
35942    // [`MeshPolicy::first_cross_axis_violation`]'s window-below-timeout
35943    // arm onto one substrate primitive on the [`AplicacaoError`]
35944    // envelope, projecting through the [`CircuitBreaker::window`] scalar
35945    // accessor on the substrate primitive. A byte-mismatched ctor body
35946    // would trip the equivalence pin first, ahead of any downstream
35947    // diagnostic-shape drift.
35948    //
35949    // Peer of the sibling standalone-ctor equivalence pins on the peer
35950    // per-envelope substrate-primitive-projection ctors across
35951    // caixa-core: `contrato_self_loop_ctor_matches_struct_literal_wrap`
35952    // (b30edfe) on the sibling `{ caixa: String, wit: String }` two-slot
35953    // per-`:contratos` self-edge envelope,
35954    // `entrada_member_missing_ctor_matches_struct_literal_wrap` (deeae5c)
35955    // on the sibling `{ para: String }` one-slot per-`:entrada :para`
35956    // phantom-reference envelope, and
35957    // `shard_key_on_non_sharded_ctor_matches_struct_literal_wrap`
35958    // (14bafca) on the sibling `{ estrategia, shard_key }` two-slot
35959    // per-`:placement :shard-key` envelope.
35960
35961    #[test]
35962    fn policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap() {
35963        // Equivalence pin: the ctor produces byte-equal
35964        // `AplicacaoError::PolicyBreakerWindowBelowTimeout` to the pre-
35965        // lift open-coded struct-literal that read the same two fields
35966        // through [`CircuitBreaker::window`] and the paired
35967        // `:politicas :timeout` destructure. Guards any future
35968        // field-addition / reordering / accessor-swap tweak on the
35969        // variant. Same equivalence-pin shape as the sibling
35970        // `contrato_self_loop_ctor_matches_struct_literal_wrap`
35971        // (b30edfe) on the sibling per-`:contratos` self-edge envelope.
35972        let cb = CircuitBreaker {
35973            max_failures: 5,
35974            window: Duration::from_secs(10),
35975        };
35976        let timeout = Duration::from_secs(30);
35977        let via_ctor = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
35978        let via_literal = AplicacaoError::PolicyBreakerWindowBelowTimeout {
35979            window: cb.window(),
35980            timeout,
35981        };
35982        assert_eq!(
35983            via_ctor, via_literal,
35984            "policy_breaker_window_below_timeout(&cb, t) must byte-equal \
35985             the open-coded PolicyBreakerWindowBelowTimeout struct-literal \
35986             on the same Copy-Duration fixture"
35987        );
35988        assert_eq!(
35989            via_ctor.to_string(),
35990            via_literal.to_string(),
35991            "Display byte-string must byte-equal the open-coded struct-literal"
35992        );
35993    }
35994
35995    #[test]
35996    fn policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim() {
35997        // Routing pin sweeping non-default `:circuit-breaker :window`
35998        // and `:timeout` pairs (below-boundary window / above-boundary
35999        // window; sub-second window / multi-minute timeout;
36000        // millisecond-precision fixture) through the paired
36001        // [`CircuitBreaker::window`] accessor and the direct `timeout`
36002        // parameter, so any wrapper-side silent normalization,
36003        // rounding, argument re-order, or accidental slot rebrand on
36004        // the two-slot pass-through surfaces at caixa-core build time
36005        // rather than at a downstream diagnostic consumer that reads
36006        // the two [`Duration`]s back and gets different values than
36007        // the ones it stored.
36008        //
36009        // Deliberately routes through a fixture whose `cb.window` and
36010        // `timeout` are distinct — a silent accessor swap
36011        // (`cb.max_failures` casting to `Duration` would fail to
36012        // compile; a hypothetical field-rename swap swapping the two
36013        // slots at the ctor body would land `timeout` in the `window`
36014        // slot instead of `cb.window()` and vice-versa, tripping the
36015        // per-field assertion here). Peer of the sibling
36016        // `contrato_self_loop_ctor_routes_source_and_world_ref_through_verbatim`
36017        // (b30edfe) routing pin on the sibling two-slot per-`:contratos`
36018        // envelope.
36019        for (max_failures, window, timeout) in [
36020            (5_u32, Duration::from_secs(10), Duration::from_secs(30)),
36021            (
36022                1_u32,
36023                Duration::from_millis(29_999),
36024                Duration::from_secs(30),
36025            ),
36026            (42_u32, Duration::from_millis(500), Duration::from_secs(120)),
36027            (7_u32, Duration::from_secs(1), Duration::from_secs(60)),
36028        ] {
36029            let cb = CircuitBreaker {
36030                max_failures,
36031                window,
36032            };
36033            let built = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
36034            let AplicacaoError::PolicyBreakerWindowBelowTimeout {
36035                window: stored_window,
36036                timeout: stored_timeout,
36037            } = built
36038            else {
36039                panic!(
36040                    "policy_breaker_window_below_timeout must construct \
36041                     PolicyBreakerWindowBelowTimeout for cb={cb:?}/timeout={timeout:?}"
36042                );
36043            };
36044            assert_eq!(
36045                stored_window, window,
36046                "window slot must thread CircuitBreaker::window() verbatim \
36047                 for cb={cb:?}/timeout={timeout:?}"
36048            );
36049            assert_eq!(
36050                stored_timeout, timeout,
36051                "timeout slot must thread the caller-side :timeout scalar verbatim \
36052                 for cb={cb:?}/timeout={timeout:?}"
36053            );
36054        }
36055    }
36056
36057    #[test]
36058    fn first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor() {
36059        // End-to-end pin: the sole in-crate wire-up site
36060        // ([`MeshPolicy::first_cross_axis_violation`]'s
36061        // window-below-timeout arm) routes through
36062        // [`AplicacaoError::policy_breaker_window_below_timeout`] and
36063        // the observed `Err` byte-equals the ctor's output on the same
36064        // sub-boundary `(:window, :timeout)` fixture. A future silent
36065        // de-lift of the wire-up back to the open-coded
36066        // `AplicacaoError::PolicyBreakerWindowBelowTimeout { window,
36067        // timeout }` struct-literal trips this test at caixa-core build
36068        // time rather than at a downstream diagnostic consumer far from
36069        // the wire-up commit. Sibling of the peer
36070        // `detect_sync_cycles_arm_routes_through_contrato_cycle_ctor`
36071        // (5cfcab8) end-to-end pin on the sibling per-`:contratos`
36072        // cross-edge cycle envelope,
36073        // `validate_entrada_phantom_arm_routes_through_entrada_member_missing_ctor`
36074        // (deeae5c) on the sibling per-`:entrada :para` phantom-
36075        // reference envelope, and
36076        // `validate_placement_non_sharded_arm_routes_through_shard_key_on_non_sharded_ctor`
36077        // (14bafca) on the sibling per-`:placement :shard-key`
36078        // envelope — extended here from a bare `matches!(err,
36079        // AplicacaoError::PolicyBreakerWindowBelowTimeout { .. })`
36080        // shape check to a byte-identity route through the ctor.
36081        let mut s = three_member_spec();
36082        s.politicas.timeout = Some(Duration::from_secs(30));
36083        s.politicas.circuit_breaker = Some(CircuitBreaker {
36084            max_failures: 5,
36085            window: Duration::from_secs(10),
36086        });
36087        let observed = s.validate().unwrap_err();
36088        let cb = s.politicas.circuit_breaker.unwrap();
36089        let timeout = s.politicas.timeout.unwrap();
36090        let expected = AplicacaoError::policy_breaker_window_below_timeout(&cb, timeout);
36091        assert_eq!(
36092            observed, expected,
36093            "MeshPolicy::first_cross_axis_violation's window-below-timeout \
36094             arm's Err must byte-equal policy_breaker_window_below_timeout(&cb, t)"
36095        );
36096        assert_eq!(
36097            observed.to_string(),
36098            expected.to_string(),
36099            "Display byte-string parity"
36100        );
36101    }
36102
36103    #[test]
36104    fn policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap() {
36105        // Equivalence pin: the ctor produces byte-equal
36106        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit` to the
36107        // pre-lift open-coded struct-literal that read the same four fields
36108        // through [`RateLimit::rate`], [`RateLimit::window`],
36109        // [`CircuitBreaker::max_failures`], and [`CircuitBreaker::window`].
36110        // Guards any future field-addition / reordering / accessor-swap
36111        // tweak on the variant. Same equivalence-pin shape as the sibling
36112        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
36113        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
36114        // cross-axis envelope.
36115        let rl = RateLimit {
36116            rate: 1,
36117            window: Duration::from_secs(3600),
36118        };
36119        let cb = CircuitBreaker {
36120            max_failures: 5,
36121            window: Duration::from_secs(10),
36122        };
36123        let via_ctor = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
36124        let via_literal = AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
36125            rate: rl.rate(),
36126            rl_window: rl.window(),
36127            max_failures: cb.max_failures(),
36128            cb_window: cb.window(),
36129        };
36130        assert_eq!(
36131            via_ctor, via_literal,
36132            "policy_breaker_cannot_trip_under_rate_limit(&rl, &cb) must \
36133             byte-equal the open-coded PolicyBreakerCannotTripUnderRateLimit \
36134             struct-literal on the same Copy-(u32|Duration) fixture"
36135        );
36136        assert_eq!(
36137            via_ctor.to_string(),
36138            via_literal.to_string(),
36139            "Display byte-string must byte-equal the open-coded struct-literal"
36140        );
36141    }
36142
36143    #[test]
36144    fn policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim() {
36145        // Routing pin sweeping non-default `(:rate, :rate-limit :window,
36146        // :max-failures, :circuit-breaker :window)` tuples across the
36147        // production-playbook starve band — Envoy 5-in-10s vs 1/hour,
36148        // sub-second breaker window, multi-minute rate-limit window,
36149        // multi-tenant per-cluster ratio — through the paired
36150        // [`RateLimit::rate`] / [`RateLimit::window`] /
36151        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
36152        // accessors, so any wrapper-side silent normalization, rounding,
36153        // argument re-order, or accidental slot rebrand on the four-slot
36154        // pass-through surfaces at caixa-core build time rather than at a
36155        // downstream diagnostic consumer that reads the four scalars back
36156        // and gets different values than the ones it stored.
36157        //
36158        // Deliberately routes through fixtures whose four scalars are
36159        // pairwise distinct (`rate ≠ max_failures`, `rl_window ≠
36160        // cb_window`) — a hypothetical field-rename swap swapping any
36161        // two adjacent slots at the ctor body would land the value from
36162        // the wrong axis, tripping the per-field assertion here. Peer of
36163        // the sibling
36164        // `policy_breaker_window_below_timeout_ctor_routes_cb_window_and_timeout_verbatim`
36165        // (9b30c07) routing pin on the sibling two-slot per-`(:timeout,
36166        // :circuit-breaker)` cross-axis envelope.
36167        for (rate, rl_window, max_failures, cb_window) in [
36168            (
36169                1_u32,
36170                Duration::from_secs(3600),
36171                5_u32,
36172                Duration::from_secs(10),
36173            ),
36174            (4_u32, Duration::from_secs(1), 5_u32, Duration::from_secs(1)),
36175            (
36176                2_u32,
36177                Duration::from_millis(500),
36178                10_u32,
36179                Duration::from_secs(300),
36180            ),
36181            (
36182                7_u32,
36183                Duration::from_secs(120),
36184                42_u32,
36185                Duration::from_millis(750),
36186            ),
36187        ] {
36188            let rl = RateLimit {
36189                rate,
36190                window: rl_window,
36191            };
36192            let cb = CircuitBreaker {
36193                max_failures,
36194                window: cb_window,
36195            };
36196            let built = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
36197            let AplicacaoError::PolicyBreakerCannotTripUnderRateLimit {
36198                rate: stored_rate,
36199                rl_window: stored_rl_window,
36200                max_failures: stored_max_failures,
36201                cb_window: stored_cb_window,
36202            } = built
36203            else {
36204                panic!(
36205                    "policy_breaker_cannot_trip_under_rate_limit must \
36206                     construct PolicyBreakerCannotTripUnderRateLimit for \
36207                     rl={rl:?}/cb={cb:?}"
36208                );
36209            };
36210            assert_eq!(
36211                stored_rate, rate,
36212                "rate slot must thread RateLimit::rate() verbatim for \
36213                 rl={rl:?}/cb={cb:?}"
36214            );
36215            assert_eq!(
36216                stored_rl_window, rl_window,
36217                "rl_window slot must thread RateLimit::window() verbatim \
36218                 for rl={rl:?}/cb={cb:?}"
36219            );
36220            assert_eq!(
36221                stored_max_failures, max_failures,
36222                "max_failures slot must thread CircuitBreaker::max_failures() \
36223                 verbatim for rl={rl:?}/cb={cb:?}"
36224            );
36225            assert_eq!(
36226                stored_cb_window, cb_window,
36227                "cb_window slot must thread CircuitBreaker::window() verbatim \
36228                 for rl={rl:?}/cb={cb:?}"
36229            );
36230        }
36231    }
36232
36233    #[test]
36234    fn first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor()
36235     {
36236        // End-to-end pin: the sole in-crate wire-up site
36237        // ([`MeshPolicy::first_cross_axis_violation`]'s
36238        // starve-under-rate-limit arm) routes through
36239        // [`AplicacaoError::policy_breaker_cannot_trip_under_rate_limit`]
36240        // and the observed `Err` byte-equals the ctor's output on the same
36241        // token-bucket-starves-breaker fixture. A future silent de-lift of
36242        // the wire-up back to the open-coded
36243        // `AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { rate,
36244        // rl_window, max_failures, cb_window }` struct-literal trips this
36245        // test at caixa-core build time rather than at a downstream
36246        // diagnostic consumer far from the wire-up commit. Sibling of the
36247        // peer
36248        // `first_cross_axis_violation_arm_routes_through_policy_breaker_window_below_timeout_ctor`
36249        // (9b30c07) end-to-end pin on the sibling per-`(:timeout,
36250        // :circuit-breaker)` cross-axis envelope — extended here from a
36251        // bare `matches!(err,
36252        // AplicacaoError::PolicyBreakerCannotTripUnderRateLimit { .. })`
36253        // shape check to a byte-identity route through the ctor. Clears
36254        // `:timeout` so the sibling window-below-timeout arm does not
36255        // fire first on the ordering-precedent it holds over this arm.
36256        let mut s = three_member_spec();
36257        s.politicas.timeout = None;
36258        s.politicas.circuit_breaker = Some(CircuitBreaker {
36259            max_failures: 5,
36260            window: Duration::from_secs(10),
36261        });
36262        s.politicas.rate_limit = Some(RateLimit {
36263            rate: 1,
36264            window: Duration::from_secs(3600),
36265        });
36266        let observed = s.validate().unwrap_err();
36267        let rl = s.politicas.rate_limit.unwrap();
36268        let cb = s.politicas.circuit_breaker.unwrap();
36269        let expected = AplicacaoError::policy_breaker_cannot_trip_under_rate_limit(&rl, &cb);
36270        assert_eq!(
36271            observed, expected,
36272            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit \
36273             arm's Err must byte-equal \
36274             policy_breaker_cannot_trip_under_rate_limit(&rl, &cb)"
36275        );
36276        assert_eq!(
36277            observed.to_string(),
36278            expected.to_string(),
36279            "Display byte-string parity"
36280        );
36281    }
36282
36283    #[test]
36284    fn policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap() {
36285        // Equivalence pin: the ctor produces byte-equal
36286        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted` to the
36287        // pre-lift open-coded struct-literal that read the same two fields
36288        // through the bare `retries` destructure and
36289        // [`CircuitBreaker::max_failures`]. Guards any future field-addition
36290        // / reordering / accessor-swap tweak on the variant. Same
36291        // equivalence-pin shape as the sibling
36292        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
36293        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
36294        // second cross-axis envelope and
36295        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
36296        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)` first
36297        // cross-axis envelope.
36298        let retries = 5_u32;
36299        let cb = CircuitBreaker {
36300            max_failures: 3,
36301            window: Duration::from_secs(60),
36302        };
36303        let via_ctor = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
36304        let via_literal = AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
36305            retries,
36306            max_failures: cb.max_failures(),
36307        };
36308        assert_eq!(
36309            via_ctor, via_literal,
36310            "policy_breaker_trips_before_retries_exhausted(retries, &cb) must \
36311             byte-equal the open-coded PolicyBreakerTripsBeforeRetriesExhausted \
36312             struct-literal on the same Copy-u32 fixture"
36313        );
36314        assert_eq!(
36315            via_ctor.to_string(),
36316            via_literal.to_string(),
36317            "Display byte-string must byte-equal the open-coded struct-literal"
36318        );
36319    }
36320
36321    #[test]
36322    fn policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim() {
36323        // Routing pin sweeping non-default `(retries, max_failures)` tuples
36324        // across the production-playbook retries-saturate band — Envoy 5
36325        // retries vs 3 max-failures, boundary retries==max_failures pair (a
36326        // rejecting arm on the strict-inequality invariant), multi-tenant
36327        // high-retries-vs-low-trip ratio, sub-cap high-max-failures ceiling —
36328        // through the paired bare-`retries` destructure and
36329        // [`CircuitBreaker::max_failures`] accessor, so any wrapper-side
36330        // silent normalization, rounding, argument re-order, or accidental
36331        // slot rebrand on the two-slot pass-through surfaces at caixa-core
36332        // build time rather than at a downstream diagnostic consumer that
36333        // reads the two scalars back and gets different values than the ones
36334        // it stored.
36335        //
36336        // Deliberately routes through fixtures whose two scalars are
36337        // pairwise distinct (`retries ≠ max_failures` on every non-boundary
36338        // arm) — a hypothetical field-rename swap swapping the two slots at
36339        // the ctor body would land the value from the wrong axis, tripping
36340        // the per-field assertion here. Peer of the sibling
36341        // `policy_breaker_cannot_trip_under_rate_limit_ctor_routes_rl_and_cb_verbatim`
36342        // (6bb4e46) routing pin on the sibling four-slot per-`(:rate-limit,
36343        // :circuit-breaker)` second cross-axis envelope.
36344        for (retries, max_failures) in [
36345            (5_u32, 3_u32),
36346            (3_u32, 3_u32),
36347            (100_u32, 1_u32),
36348            (7_u32, 42_u32),
36349        ] {
36350            let cb = CircuitBreaker {
36351                max_failures,
36352                window: Duration::from_secs(60),
36353            };
36354            let built = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
36355            let AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted {
36356                retries: stored_retries,
36357                max_failures: stored_max_failures,
36358            } = built
36359            else {
36360                panic!(
36361                    "policy_breaker_trips_before_retries_exhausted must \
36362                     construct PolicyBreakerTripsBeforeRetriesExhausted for \
36363                     retries={retries}/cb={cb:?}"
36364                );
36365            };
36366            assert_eq!(
36367                stored_retries, retries,
36368                "retries slot must thread the bare-`retries` destructure \
36369                 verbatim for retries={retries}/cb={cb:?}"
36370            );
36371            assert_eq!(
36372                stored_max_failures, max_failures,
36373                "max_failures slot must thread CircuitBreaker::max_failures() \
36374                 verbatim for retries={retries}/cb={cb:?}"
36375            );
36376        }
36377    }
36378
36379    #[test]
36380    fn first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor()
36381     {
36382        // End-to-end pin: the sole in-crate wire-up site
36383        // ([`MeshPolicy::first_cross_axis_violation`]'s retries-saturate
36384        // arm) routes through
36385        // [`AplicacaoError::policy_breaker_trips_before_retries_exhausted`]
36386        // and the observed `Err` byte-equals the ctor's output on the same
36387        // retries-saturate fixture. A future silent de-lift of the wire-up
36388        // back to the open-coded
36389        // `AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { retries,
36390        // max_failures }` struct-literal trips this test at caixa-core build
36391        // time rather than at a downstream diagnostic consumer far from the
36392        // wire-up commit. Sibling of the peer
36393        // `first_cross_axis_violation_arm_routes_through_policy_breaker_cannot_trip_under_rate_limit_ctor`
36394        // (6bb4e46) end-to-end pin on the sibling per-`(:rate-limit,
36395        // :circuit-breaker)` second cross-axis envelope — extended here from
36396        // a bare `matches!(err,
36397        // AplicacaoError::PolicyBreakerTripsBeforeRetriesExhausted { .. })`
36398        // shape check to a byte-identity route through the ctor. Clears
36399        // `:timeout` and `:rate-limit` so the sibling window-below-timeout
36400        // and starve-under-rate-limit arms do not fire first on the
36401        // ordering-precedent they hold over this arm.
36402        let mut s = three_member_spec();
36403        s.politicas.timeout = None;
36404        s.politicas.rate_limit = None;
36405        s.politicas.retries = Some(5);
36406        s.politicas.circuit_breaker = Some(CircuitBreaker {
36407            max_failures: 3,
36408            window: Duration::from_secs(60),
36409        });
36410        let observed = s.validate().unwrap_err();
36411        let retries = s.politicas.retries.unwrap();
36412        let cb = s.politicas.circuit_breaker.unwrap();
36413        let expected = AplicacaoError::policy_breaker_trips_before_retries_exhausted(retries, &cb);
36414        assert_eq!(
36415            observed, expected,
36416            "MeshPolicy::first_cross_axis_violation's retries-saturate arm's \
36417             Err must byte-equal \
36418             policy_breaker_trips_before_retries_exhausted(retries, &cb)"
36419        );
36420        assert_eq!(
36421            observed.to_string(),
36422            expected.to_string(),
36423            "Display byte-string parity"
36424        );
36425    }
36426
36427    #[test]
36428    fn policy_rate_limit_cannot_admit_retry_burst_ctor_matches_struct_literal_wrap() {
36429        // Equivalence pin: the ctor produces byte-equal
36430        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst` to the
36431        // pre-lift open-coded struct-literal that read the same two fields
36432        // through the bare `retries` destructure and [`RateLimit::rate`].
36433        // Guards any future field-addition / reordering / accessor-swap
36434        // tweak on the variant. Same equivalence-pin shape as the sibling
36435        // `policy_breaker_trips_before_retries_exhausted_ctor_matches_struct_literal_wrap`
36436        // (f54c539) on the sibling per-`(:retries, :circuit-breaker)`
36437        // third cross-axis envelope,
36438        // `policy_breaker_cannot_trip_under_rate_limit_ctor_matches_struct_literal_wrap`
36439        // (6bb4e46) on the sibling per-`(:rate-limit, :circuit-breaker)`
36440        // second cross-axis envelope, and
36441        // `policy_breaker_window_below_timeout_ctor_matches_struct_literal_wrap`
36442        // (9b30c07) on the sibling per-`(:timeout, :circuit-breaker)`
36443        // first cross-axis envelope.
36444        let retries = 3_u32;
36445        let rl = RateLimit {
36446            rate: 3,
36447            window: Duration::from_secs(1),
36448        };
36449        let via_ctor = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
36450        let via_literal = AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
36451            retries,
36452            rate: rl.rate(),
36453        };
36454        assert_eq!(
36455            via_ctor, via_literal,
36456            "policy_rate_limit_cannot_admit_retry_burst(retries, &rl) must \
36457             byte-equal the open-coded PolicyRateLimitCannotAdmitRetryBurst \
36458             struct-literal on the same Copy-u32 fixture"
36459        );
36460        assert_eq!(
36461            via_ctor.to_string(),
36462            via_literal.to_string(),
36463            "Display byte-string must byte-equal the open-coded struct-literal"
36464        );
36465    }
36466
36467    #[test]
36468    fn policy_rate_limit_cannot_admit_retry_burst_ctor_routes_retries_and_rl_verbatim() {
36469        // Routing pin sweeping non-default `(retries, rate)` tuples across
36470        // the production-playbook rate-limit-starve band — boundary
36471        // `retries==rate` (a rejecting arm on the `>=` invariant stated as
36472        // `rate >= retries + 1`), one-below-boundary pair, multi-tenant
36473        // high-retries-vs-low-rate ratio, and sub-cap high-rate ceiling —
36474        // through the paired bare-`retries` destructure and
36475        // [`RateLimit::rate`] accessor, so any wrapper-side silent
36476        // normalization, rounding, argument re-order, or accidental slot
36477        // rebrand on the two-slot pass-through surfaces at caixa-core
36478        // build time rather than at a downstream diagnostic consumer that
36479        // reads the two scalars back and gets different values than the
36480        // ones it stored.
36481        //
36482        // Deliberately routes through fixtures whose two scalars are
36483        // pairwise distinct on every non-boundary arm — a hypothetical
36484        // field-rename swap swapping the two slots at the ctor body would
36485        // land the value from the wrong axis, tripping the per-field
36486        // assertion here. Peer of the sibling
36487        // `policy_breaker_trips_before_retries_exhausted_ctor_routes_retries_and_cb_verbatim`
36488        // (f54c539) routing pin on the sibling two-slot per-`(:retries,
36489        // :circuit-breaker)` third cross-axis envelope.
36490        for (retries, rate) in [
36491            (3_u32, 3_u32),
36492            (5_u32, 4_u32),
36493            (100_u32, 50_u32),
36494            (2_u32, POLICY_RATE_LIMIT_MAX),
36495        ] {
36496            let rl = RateLimit {
36497                rate,
36498                window: Duration::from_secs(1),
36499            };
36500            let built = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
36501            let AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst {
36502                retries: stored_retries,
36503                rate: stored_rate,
36504            } = built
36505            else {
36506                panic!(
36507                    "policy_rate_limit_cannot_admit_retry_burst must \
36508                     construct PolicyRateLimitCannotAdmitRetryBurst for \
36509                     retries={retries}/rl={rl:?}"
36510                );
36511            };
36512            assert_eq!(
36513                stored_retries, retries,
36514                "retries slot must thread the bare-`retries` destructure \
36515                 verbatim for retries={retries}/rl={rl:?}"
36516            );
36517            assert_eq!(
36518                stored_rate, rate,
36519                "rate slot must thread RateLimit::rate() verbatim for \
36520                 retries={retries}/rl={rl:?}"
36521            );
36522        }
36523    }
36524
36525    #[test]
36526    fn first_cross_axis_violation_arm_routes_through_policy_rate_limit_cannot_admit_retry_burst_ctor()
36527     {
36528        // End-to-end pin: the sole in-crate wire-up site
36529        // ([`MeshPolicy::first_cross_axis_violation`]'s starve-under-rate-
36530        // limit arm) routes through
36531        // [`AplicacaoError::policy_rate_limit_cannot_admit_retry_burst`]
36532        // and the observed `Err` byte-equals the ctor's output on the same
36533        // rate-limit-starve fixture. A future silent de-lift of the
36534        // wire-up back to the open-coded
36535        // `AplicacaoError::PolicyRateLimitCannotAdmitRetryBurst { retries,
36536        // rate }` struct-literal trips this test at caixa-core build time
36537        // rather than at a downstream diagnostic consumer far from the
36538        // wire-up commit. Sibling of the peer
36539        // `first_cross_axis_violation_arm_routes_through_policy_breaker_trips_before_retries_exhausted_ctor`
36540        // (f54c539) end-to-end pin on the sibling per-`(:retries,
36541        // :circuit-breaker)` third cross-axis envelope. Clears `:timeout`
36542        // and `:circuit-breaker` so the sibling window-below-timeout /
36543        // starve-under-rate-limit / trips-before-retries-exhausted arms
36544        // do not fire first on the ordering-precedent they hold over this
36545        // arm.
36546        let mut s = three_member_spec();
36547        s.politicas.timeout = None;
36548        s.politicas.circuit_breaker = None;
36549        s.politicas.retries = Some(5);
36550        s.politicas.rate_limit = Some(RateLimit {
36551            rate: 3,
36552            window: Duration::from_secs(1),
36553        });
36554        let observed = s.validate().unwrap_err();
36555        let retries = s.politicas.retries.unwrap();
36556        let rl = s.politicas.rate_limit.unwrap();
36557        let expected = AplicacaoError::policy_rate_limit_cannot_admit_retry_burst(retries, &rl);
36558        assert_eq!(
36559            observed, expected,
36560            "MeshPolicy::first_cross_axis_violation's starve-under-rate-limit arm's \
36561             Err must byte-equal \
36562             policy_rate_limit_cannot_admit_retry_burst(retries, &rl)"
36563        );
36564        assert_eq!(
36565            observed.to_string(),
36566            expected.to_string(),
36567            "Display byte-string parity"
36568        );
36569    }
36570}